es6.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334
  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. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * 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)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * 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)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * 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)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * 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)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * 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)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * 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)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * 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)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * 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)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * 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)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * 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)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * 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)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * 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.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. BABYLON.ToGammaSpace = 1 / 2.2;
  1397. BABYLON.ToLinearSpace = 2.2;
  1398. BABYLON.Epsilon = 0.001;
  1399. /**
  1400. * Class used to hold a RBG color
  1401. */
  1402. var Color3 = /** @class */ (function () {
  1403. /**
  1404. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1405. * @param r defines the red component (between 0 and 1, default is 0)
  1406. * @param g defines the green component (between 0 and 1, default is 0)
  1407. * @param b defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. function Color3(
  1410. /**
  1411. * Defines the red component (between 0 and 1, default is 0)
  1412. */
  1413. r,
  1414. /**
  1415. * Defines the green component (between 0 and 1, default is 0)
  1416. */
  1417. g,
  1418. /**
  1419. * Defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. b) {
  1422. if (r === void 0) { r = 0; }
  1423. if (g === void 0) { g = 0; }
  1424. if (b === void 0) { b = 0; }
  1425. this.r = r;
  1426. this.g = g;
  1427. this.b = b;
  1428. }
  1429. /**
  1430. * Creates a string with the Color3 current values
  1431. * @returns the string representation of the Color3 object
  1432. */
  1433. Color3.prototype.toString = function () {
  1434. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1435. };
  1436. /**
  1437. * Returns the string "Color3"
  1438. * @returns "Color3"
  1439. */
  1440. Color3.prototype.getClassName = function () {
  1441. return "Color3";
  1442. };
  1443. /**
  1444. * Compute the Color3 hash code
  1445. * @returns an unique number that can be used to hash Color3 objects
  1446. */
  1447. Color3.prototype.getHashCode = function () {
  1448. var hash = this.r || 0;
  1449. hash = (hash * 397) ^ (this.g || 0);
  1450. hash = (hash * 397) ^ (this.b || 0);
  1451. return hash;
  1452. };
  1453. // Operators
  1454. /**
  1455. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1456. * @param array defines the array where to store the r,g,b components
  1457. * @param index defines an optional index in the target array to define where to start storing values
  1458. * @returns the current Color3 object
  1459. */
  1460. Color3.prototype.toArray = function (array, index) {
  1461. if (index === undefined) {
  1462. index = 0;
  1463. }
  1464. array[index] = this.r;
  1465. array[index + 1] = this.g;
  1466. array[index + 2] = this.b;
  1467. return this;
  1468. };
  1469. /**
  1470. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1471. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1472. * @returns a new {BABYLON.Color4} object
  1473. */
  1474. Color3.prototype.toColor4 = function (alpha) {
  1475. if (alpha === void 0) { alpha = 1; }
  1476. return new Color4(this.r, this.g, this.b, alpha);
  1477. };
  1478. /**
  1479. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1480. * @returns the new array
  1481. */
  1482. Color3.prototype.asArray = function () {
  1483. var result = new Array();
  1484. this.toArray(result, 0);
  1485. return result;
  1486. };
  1487. /**
  1488. * Returns the luminance value
  1489. * @returns a float value
  1490. */
  1491. Color3.prototype.toLuminance = function () {
  1492. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1493. };
  1494. /**
  1495. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1496. * @param otherColor defines the second operand
  1497. * @returns the new Color3 object
  1498. */
  1499. Color3.prototype.multiply = function (otherColor) {
  1500. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1501. };
  1502. /**
  1503. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1504. * @param otherColor defines the second operand
  1505. * @param result defines the Color3 object where to store the result
  1506. * @returns the current Color3
  1507. */
  1508. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1509. result.r = this.r * otherColor.r;
  1510. result.g = this.g * otherColor.g;
  1511. result.b = this.b * otherColor.b;
  1512. return this;
  1513. };
  1514. /**
  1515. * Determines equality between Color3 objects
  1516. * @param otherColor defines the second operand
  1517. * @returns true if the rgb values are equal to the given ones
  1518. */
  1519. Color3.prototype.equals = function (otherColor) {
  1520. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1521. };
  1522. /**
  1523. * Determines equality between the current Color3 object and a set of r,b,g values
  1524. * @param r defines the red component to check
  1525. * @param g defines the green component to check
  1526. * @param b defines the blue component to check
  1527. * @returns true if the rgb values are equal to the given ones
  1528. */
  1529. Color3.prototype.equalsFloats = function (r, g, b) {
  1530. return this.r === r && this.g === g && this.b === b;
  1531. };
  1532. /**
  1533. * Multiplies in place each rgb value by scale
  1534. * @param scale defines the scaling factor
  1535. * @returns the updated Color3
  1536. */
  1537. Color3.prototype.scale = function (scale) {
  1538. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1539. };
  1540. /**
  1541. * Multiplies the rgb values by scale and stores the result into "result"
  1542. * @param scale defines the scaling factor
  1543. * @param result defines the Color3 object where to store the result
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleToRef = function (scale, result) {
  1547. result.r = this.r * scale;
  1548. result.g = this.g * scale;
  1549. result.b = this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Scale the current Color3 values by a factor and add the result to a given Color3
  1554. * @param scale defines the scale factor
  1555. * @param result defines color to store the result into
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1559. result.r += this.r * scale;
  1560. result.g += this.g * scale;
  1561. result.b += this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Clamps the rgb values by the min and max values and stores the result into "result"
  1566. * @param min defines minimum clamping value (default is 0)
  1567. * @param max defines maximum clamping value (default is 1)
  1568. * @param result defines color to store the result into
  1569. * @returns the original Color3
  1570. */
  1571. Color3.prototype.clampToRef = function (min, max, result) {
  1572. if (min === void 0) { min = 0; }
  1573. if (max === void 0) { max = 1; }
  1574. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1575. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1576. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1577. return this;
  1578. };
  1579. /**
  1580. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1581. * @param otherColor defines the second operand
  1582. * @returns the new Color3
  1583. */
  1584. Color3.prototype.add = function (otherColor) {
  1585. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1586. };
  1587. /**
  1588. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1589. * @param otherColor defines the second operand
  1590. * @param result defines Color3 object to store the result into
  1591. * @returns the unmodified current Color3
  1592. */
  1593. Color3.prototype.addToRef = function (otherColor, result) {
  1594. result.r = this.r + otherColor.r;
  1595. result.g = this.g + otherColor.g;
  1596. result.b = this.b + otherColor.b;
  1597. return this;
  1598. };
  1599. /**
  1600. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1601. * @param otherColor defines the second operand
  1602. * @returns the new Color3
  1603. */
  1604. Color3.prototype.subtract = function (otherColor) {
  1605. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1606. };
  1607. /**
  1608. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1609. * @param otherColor defines the second operand
  1610. * @param result defines Color3 object to store the result into
  1611. * @returns the unmodified current Color3
  1612. */
  1613. Color3.prototype.subtractToRef = function (otherColor, result) {
  1614. result.r = this.r - otherColor.r;
  1615. result.g = this.g - otherColor.g;
  1616. result.b = this.b - otherColor.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Copy the current object
  1621. * @returns a new Color3 copied the current one
  1622. */
  1623. Color3.prototype.clone = function () {
  1624. return new Color3(this.r, this.g, this.b);
  1625. };
  1626. /**
  1627. * Copies the rgb values from the source in the current Color3
  1628. * @param source defines the source Color3 object
  1629. * @returns the updated Color3 object
  1630. */
  1631. Color3.prototype.copyFrom = function (source) {
  1632. this.r = source.r;
  1633. this.g = source.g;
  1634. this.b = source.b;
  1635. return this;
  1636. };
  1637. /**
  1638. * Updates the Color3 rgb values from the given floats
  1639. * @param r defines the red component to read from
  1640. * @param g defines the green component to read from
  1641. * @param b defines the blue component to read from
  1642. * @returns the current Color3 object
  1643. */
  1644. Color3.prototype.copyFromFloats = function (r, g, b) {
  1645. this.r = r;
  1646. this.g = g;
  1647. this.b = b;
  1648. return this;
  1649. };
  1650. /**
  1651. * Updates the Color3 rgb values from the given floats
  1652. * @param r defines the red component to read from
  1653. * @param g defines the green component to read from
  1654. * @param b defines the blue component to read from
  1655. * @returns the current Color3 object
  1656. */
  1657. Color3.prototype.set = function (r, g, b) {
  1658. return this.copyFromFloats(r, g, b);
  1659. };
  1660. /**
  1661. * Compute the Color3 hexadecimal code as a string
  1662. * @returns a string containing the hexadecimal representation of the Color3 object
  1663. */
  1664. Color3.prototype.toHexString = function () {
  1665. var intR = (this.r * 255) | 0;
  1666. var intG = (this.g * 255) | 0;
  1667. var intB = (this.b * 255) | 0;
  1668. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1669. };
  1670. /**
  1671. * Computes a new Color3 converted from the current one to linear space
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.prototype.toLinearSpace = function () {
  1675. var convertedColor = new Color3();
  1676. this.toLinearSpaceToRef(convertedColor);
  1677. return convertedColor;
  1678. };
  1679. /**
  1680. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1681. * @param convertedColor defines the Color3 object where to store the linear space version
  1682. * @returns the unmodified Color3
  1683. */
  1684. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1685. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1686. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1687. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1688. return this;
  1689. };
  1690. /**
  1691. * Computes a new Color3 converted from the current one to gamma space
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.prototype.toGammaSpace = function () {
  1695. var convertedColor = new Color3();
  1696. this.toGammaSpaceToRef(convertedColor);
  1697. return convertedColor;
  1698. };
  1699. /**
  1700. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1701. * @param convertedColor defines the Color3 object where to store the gamma space version
  1702. * @returns the unmodified Color3
  1703. */
  1704. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1705. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1706. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1707. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1708. return this;
  1709. };
  1710. // Statics
  1711. /**
  1712. * Creates a new Color3 from the string containing valid hexadecimal values
  1713. * @param hex defines a string containing valid hexadecimal values
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromHexString = function (hex) {
  1717. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1718. return new Color3(0, 0, 0);
  1719. }
  1720. var r = parseInt(hex.substring(1, 3), 16);
  1721. var g = parseInt(hex.substring(3, 5), 16);
  1722. var b = parseInt(hex.substring(5, 7), 16);
  1723. return Color3.FromInts(r, g, b);
  1724. };
  1725. /**
  1726. * Creates a new Vector3 from the starting index of the given array
  1727. * @param array defines the source array
  1728. * @param offset defines an offset in the source array
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromArray = function (array, offset) {
  1732. if (offset === void 0) { offset = 0; }
  1733. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1734. };
  1735. /**
  1736. * Creates a new Color3 from integer values (< 256)
  1737. * @param r defines the red component to read from (value between 0 and 255)
  1738. * @param g defines the green component to read from (value between 0 and 255)
  1739. * @param b defines the blue component to read from (value between 0 and 255)
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.FromInts = function (r, g, b) {
  1743. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1744. };
  1745. /**
  1746. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1747. * @param start defines the start Color3 value
  1748. * @param end defines the end Color3 value
  1749. * @param amount defines the gradient value between start and end
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Lerp = function (start, end, amount) {
  1753. var r = start.r + ((end.r - start.r) * amount);
  1754. var g = start.g + ((end.g - start.g) * amount);
  1755. var b = start.b + ((end.b - start.b) * amount);
  1756. return new Color3(r, g, b);
  1757. };
  1758. /**
  1759. * Returns a Color3 value containing a red color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Red = function () { return new Color3(1, 0, 0); };
  1763. /**
  1764. * Returns a Color3 value containing a green color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Green = function () { return new Color3(0, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a blue color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1773. /**
  1774. * Returns a Color3 value containing a black color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Black = function () { return new Color3(0, 0, 0); };
  1778. /**
  1779. * Returns a Color3 value containing a white color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.White = function () { return new Color3(1, 1, 1); };
  1783. /**
  1784. * Returns a Color3 value containing a purple color
  1785. * @returns a new Color3 object
  1786. */
  1787. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1788. /**
  1789. * Returns a Color3 value containing a magenta color
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1793. /**
  1794. * Returns a Color3 value containing a yellow color
  1795. * @returns a new Color3 object
  1796. */
  1797. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1798. /**
  1799. * Returns a Color3 value containing a gray color
  1800. * @returns a new Color3 object
  1801. */
  1802. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1803. /**
  1804. * Returns a Color3 value containing a teal color
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1808. /**
  1809. * Returns a Color3 value containing a random color
  1810. * @returns a new Color3 object
  1811. */
  1812. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1813. return Color3;
  1814. }());
  1815. BABYLON.Color3 = Color3;
  1816. /**
  1817. * Class used to hold a RBGA color
  1818. */
  1819. var Color4 = /** @class */ (function () {
  1820. /**
  1821. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1822. * @param r defines the red component (between 0 and 1, default is 0)
  1823. * @param g defines the green component (between 0 and 1, default is 0)
  1824. * @param b defines the blue component (between 0 and 1, default is 0)
  1825. * @param a defines the alpha component (between 0 and 1, default is 1)
  1826. */
  1827. function Color4(
  1828. /**
  1829. * Defines the red component (between 0 and 1, default is 0)
  1830. */
  1831. r,
  1832. /**
  1833. * Defines the green component (between 0 and 1, default is 0)
  1834. */
  1835. g,
  1836. /**
  1837. * Defines the blue component (between 0 and 1, default is 0)
  1838. */
  1839. b,
  1840. /**
  1841. * Defines the alpha component (between 0 and 1, default is 1)
  1842. */
  1843. a) {
  1844. if (r === void 0) { r = 0; }
  1845. if (g === void 0) { g = 0; }
  1846. if (b === void 0) { b = 0; }
  1847. if (a === void 0) { a = 1; }
  1848. this.r = r;
  1849. this.g = g;
  1850. this.b = b;
  1851. this.a = a;
  1852. }
  1853. // Operators
  1854. /**
  1855. * Adds in place the given Color4 values to the current Color4 object
  1856. * @param right defines the second operand
  1857. * @returns the current updated Color4 object
  1858. */
  1859. Color4.prototype.addInPlace = function (right) {
  1860. this.r += right.r;
  1861. this.g += right.g;
  1862. this.b += right.b;
  1863. this.a += right.a;
  1864. return this;
  1865. };
  1866. /**
  1867. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1868. * @returns the new array
  1869. */
  1870. Color4.prototype.asArray = function () {
  1871. var result = new Array();
  1872. this.toArray(result, 0);
  1873. return result;
  1874. };
  1875. /**
  1876. * Stores from the starting index in the given array the Color4 successive values
  1877. * @param array defines the array where to store the r,g,b components
  1878. * @param index defines an optional index in the target array to define where to start storing values
  1879. * @returns the current Color4 object
  1880. */
  1881. Color4.prototype.toArray = function (array, index) {
  1882. if (index === undefined) {
  1883. index = 0;
  1884. }
  1885. array[index] = this.r;
  1886. array[index + 1] = this.g;
  1887. array[index + 2] = this.b;
  1888. array[index + 3] = this.a;
  1889. return this;
  1890. };
  1891. /**
  1892. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1893. * @param right defines the second operand
  1894. * @returns a new Color4 object
  1895. */
  1896. Color4.prototype.add = function (right) {
  1897. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1898. };
  1899. /**
  1900. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1901. * @param right defines the second operand
  1902. * @returns a new Color4 object
  1903. */
  1904. Color4.prototype.subtract = function (right) {
  1905. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1906. };
  1907. /**
  1908. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1909. * @param right defines the second operand
  1910. * @param result defines the Color4 object where to store the result
  1911. * @returns the current Color4 object
  1912. */
  1913. Color4.prototype.subtractToRef = function (right, result) {
  1914. result.r = this.r - right.r;
  1915. result.g = this.g - right.g;
  1916. result.b = this.b - right.b;
  1917. result.a = this.a - right.a;
  1918. return this;
  1919. };
  1920. /**
  1921. * Creates a new Color4 with the current Color4 values multiplied by scale
  1922. * @param scale defines the scaling factor to apply
  1923. * @returns a new Color4 object
  1924. */
  1925. Color4.prototype.scale = function (scale) {
  1926. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1927. };
  1928. /**
  1929. * Multiplies the current Color4 values by scale and stores the result in "result"
  1930. * @param scale defines the scaling factor to apply
  1931. * @param result defines the Color4 object where to store the result
  1932. * @returns the current unmodified Color4
  1933. */
  1934. Color4.prototype.scaleToRef = function (scale, result) {
  1935. result.r = this.r * scale;
  1936. result.g = this.g * scale;
  1937. result.b = this.b * scale;
  1938. result.a = this.a * scale;
  1939. return this;
  1940. };
  1941. /**
  1942. * Scale the current Color4 values by a factor and add the result to a given Color4
  1943. * @param scale defines the scale factor
  1944. * @param result defines the Color4 object where to store the result
  1945. * @returns the unmodified current Color4
  1946. */
  1947. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1948. result.r += this.r * scale;
  1949. result.g += this.g * scale;
  1950. result.b += this.b * scale;
  1951. result.a += this.a * scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Clamps the rgb values by the min and max values and stores the result into "result"
  1956. * @param min defines minimum clamping value (default is 0)
  1957. * @param max defines maximum clamping value (default is 1)
  1958. * @param result defines color to store the result into.
  1959. * @returns the cuurent Color4
  1960. */
  1961. Color4.prototype.clampToRef = function (min, max, result) {
  1962. if (min === void 0) { min = 0; }
  1963. if (max === void 0) { max = 1; }
  1964. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1965. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1966. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1967. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1968. return this;
  1969. };
  1970. /**
  1971. * Multipy an Color4 value by another and return a new Color4 object
  1972. * @param color defines the Color4 value to multiply by
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.multiply = function (color) {
  1976. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1977. };
  1978. /**
  1979. * Multipy a Color4 value by another and push the result in a reference value
  1980. * @param color defines the Color4 value to multiply by
  1981. * @param result defines the Color4 to fill the result in
  1982. * @returns the result Color4
  1983. */
  1984. Color4.prototype.multiplyToRef = function (color, result) {
  1985. result.r = this.r * color.r;
  1986. result.g = this.g * color.g;
  1987. result.b = this.b * color.b;
  1988. result.a = this.a * color.a;
  1989. return result;
  1990. };
  1991. /**
  1992. * Creates a string with the Color4 current values
  1993. * @returns the string representation of the Color4 object
  1994. */
  1995. Color4.prototype.toString = function () {
  1996. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1997. };
  1998. /**
  1999. * Returns the string "Color4"
  2000. * @returns "Color4"
  2001. */
  2002. Color4.prototype.getClassName = function () {
  2003. return "Color4";
  2004. };
  2005. /**
  2006. * Compute the Color4 hash code
  2007. * @returns an unique number that can be used to hash Color4 objects
  2008. */
  2009. Color4.prototype.getHashCode = function () {
  2010. var hash = this.r || 0;
  2011. hash = (hash * 397) ^ (this.g || 0);
  2012. hash = (hash * 397) ^ (this.b || 0);
  2013. hash = (hash * 397) ^ (this.a || 0);
  2014. return hash;
  2015. };
  2016. /**
  2017. * Creates a new Color4 copied from the current one
  2018. * @returns a new Color4 object
  2019. */
  2020. Color4.prototype.clone = function () {
  2021. return new Color4(this.r, this.g, this.b, this.a);
  2022. };
  2023. /**
  2024. * Copies the given Color4 values into the current one
  2025. * @param source defines the source Color4 object
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.copyFrom = function (source) {
  2029. this.r = source.r;
  2030. this.g = source.g;
  2031. this.b = source.b;
  2032. this.a = source.a;
  2033. return this;
  2034. };
  2035. /**
  2036. * Copies the given float values into the current one
  2037. * @param r defines the red component to read from
  2038. * @param g defines the green component to read from
  2039. * @param b defines the blue component to read from
  2040. * @param a defines the alpha component to read from
  2041. * @returns the current updated Color4 object
  2042. */
  2043. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2044. this.r = r;
  2045. this.g = g;
  2046. this.b = b;
  2047. this.a = a;
  2048. return this;
  2049. };
  2050. /**
  2051. * Copies the given float values into the current one
  2052. * @param r defines the red component to read from
  2053. * @param g defines the green component to read from
  2054. * @param b defines the blue component to read from
  2055. * @param a defines the alpha component to read from
  2056. * @returns the current updated Color4 object
  2057. */
  2058. Color4.prototype.set = function (r, g, b, a) {
  2059. return this.copyFromFloats(r, g, b, a);
  2060. };
  2061. /**
  2062. * Compute the Color4 hexadecimal code as a string
  2063. * @returns a string containing the hexadecimal representation of the Color4 object
  2064. */
  2065. Color4.prototype.toHexString = function () {
  2066. var intR = (this.r * 255) | 0;
  2067. var intG = (this.g * 255) | 0;
  2068. var intB = (this.b * 255) | 0;
  2069. var intA = (this.a * 255) | 0;
  2070. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2071. };
  2072. /**
  2073. * Computes a new Color4 converted from the current one to linear space
  2074. * @returns a new Color4 object
  2075. */
  2076. Color4.prototype.toLinearSpace = function () {
  2077. var convertedColor = new Color4();
  2078. this.toLinearSpaceToRef(convertedColor);
  2079. return convertedColor;
  2080. };
  2081. /**
  2082. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2083. * @param convertedColor defines the Color4 object where to store the linear space version
  2084. * @returns the unmodified Color4
  2085. */
  2086. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2087. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2088. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2089. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2090. convertedColor.a = this.a;
  2091. return this;
  2092. };
  2093. /**
  2094. * Computes a new Color4 converted from the current one to gamma space
  2095. * @returns a new Color4 object
  2096. */
  2097. Color4.prototype.toGammaSpace = function () {
  2098. var convertedColor = new Color4();
  2099. this.toGammaSpaceToRef(convertedColor);
  2100. return convertedColor;
  2101. };
  2102. /**
  2103. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2104. * @param convertedColor defines the Color4 object where to store the gamma space version
  2105. * @returns the unmodified Color4
  2106. */
  2107. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2108. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2109. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2110. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2111. convertedColor.a = this.a;
  2112. return this;
  2113. };
  2114. // Statics
  2115. /**
  2116. * Creates a new Color4 from the string containing valid hexadecimal values
  2117. * @param hex defines a string containing valid hexadecimal values
  2118. * @returns a new Color4 object
  2119. */
  2120. Color4.FromHexString = function (hex) {
  2121. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2122. return new Color4(0.0, 0.0, 0.0, 0.0);
  2123. }
  2124. var r = parseInt(hex.substring(1, 3), 16);
  2125. var g = parseInt(hex.substring(3, 5), 16);
  2126. var b = parseInt(hex.substring(5, 7), 16);
  2127. var a = parseInt(hex.substring(7, 9), 16);
  2128. return Color4.FromInts(r, g, b, a);
  2129. };
  2130. /**
  2131. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2132. * @param left defines the start value
  2133. * @param right defines the end value
  2134. * @param amount defines the gradient factor
  2135. * @returns a new Color4 object
  2136. */
  2137. Color4.Lerp = function (left, right, amount) {
  2138. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2139. Color4.LerpToRef(left, right, amount, result);
  2140. return result;
  2141. };
  2142. /**
  2143. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2144. * @param left defines the start value
  2145. * @param right defines the end value
  2146. * @param amount defines the gradient factor
  2147. * @param result defines the Color4 object where to store data
  2148. */
  2149. Color4.LerpToRef = function (left, right, amount, result) {
  2150. result.r = left.r + (right.r - left.r) * amount;
  2151. result.g = left.g + (right.g - left.g) * amount;
  2152. result.b = left.b + (right.b - left.b) * amount;
  2153. result.a = left.a + (right.a - left.a) * amount;
  2154. };
  2155. /**
  2156. * Creates a new Color4 from the starting index element of the given array
  2157. * @param array defines the source array to read from
  2158. * @param offset defines the offset in the source array
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.FromArray = function (array, offset) {
  2162. if (offset === void 0) { offset = 0; }
  2163. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2164. };
  2165. /**
  2166. * Creates a new Color3 from integer values (< 256)
  2167. * @param r defines the red component to read from (value between 0 and 255)
  2168. * @param g defines the green component to read from (value between 0 and 255)
  2169. * @param b defines the blue component to read from (value between 0 and 255)
  2170. * @param a defines the alpha component to read from (value between 0 and 255)
  2171. * @returns a new Color3 object
  2172. */
  2173. Color4.FromInts = function (r, g, b, a) {
  2174. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2175. };
  2176. /**
  2177. * Check the content of a given array and convert it to an array containing RGBA data
  2178. * If the original array was already containing count * 4 values then it is returned directly
  2179. * @param colors defines the array to check
  2180. * @param count defines the number of RGBA data to expect
  2181. * @returns an array containing count * 4 values (RGBA)
  2182. */
  2183. Color4.CheckColors4 = function (colors, count) {
  2184. // Check if color3 was used
  2185. if (colors.length === count * 3) {
  2186. var colors4 = [];
  2187. for (var index = 0; index < colors.length; index += 3) {
  2188. var newIndex = (index / 3) * 4;
  2189. colors4[newIndex] = colors[index];
  2190. colors4[newIndex + 1] = colors[index + 1];
  2191. colors4[newIndex + 2] = colors[index + 2];
  2192. colors4[newIndex + 3] = 1.0;
  2193. }
  2194. return colors4;
  2195. }
  2196. return colors;
  2197. };
  2198. return Color4;
  2199. }());
  2200. BABYLON.Color4 = Color4;
  2201. /**
  2202. * Class representing a vector containing 2 coordinates
  2203. */
  2204. var Vector2 = /** @class */ (function () {
  2205. /**
  2206. * Creates a new Vector2 from the given x and y coordinates
  2207. * @param x defines the first coordinate
  2208. * @param y defines the second coordinate
  2209. */
  2210. function Vector2(
  2211. /** defines the first coordinate */
  2212. x,
  2213. /** defines the second coordinate */
  2214. y) {
  2215. if (x === void 0) { x = 0; }
  2216. if (y === void 0) { y = 0; }
  2217. this.x = x;
  2218. this.y = y;
  2219. }
  2220. /**
  2221. * Gets a string with the Vector2 coordinates
  2222. * @returns a string with the Vector2 coordinates
  2223. */
  2224. Vector2.prototype.toString = function () {
  2225. return "{X: " + this.x + " Y:" + this.y + "}";
  2226. };
  2227. /**
  2228. * Gets class name
  2229. * @returns the string "Vector2"
  2230. */
  2231. Vector2.prototype.getClassName = function () {
  2232. return "Vector2";
  2233. };
  2234. /**
  2235. * Gets current vector hash code
  2236. * @returns the Vector2 hash code as a number
  2237. */
  2238. Vector2.prototype.getHashCode = function () {
  2239. var hash = this.x || 0;
  2240. hash = (hash * 397) ^ (this.y || 0);
  2241. return hash;
  2242. };
  2243. // Operators
  2244. /**
  2245. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2246. * @param array defines the source array
  2247. * @param index defines the offset in source array
  2248. * @returns the current Vector2
  2249. */
  2250. Vector2.prototype.toArray = function (array, index) {
  2251. if (index === void 0) { index = 0; }
  2252. array[index] = this.x;
  2253. array[index + 1] = this.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Copy the current vector to an array
  2258. * @returns a new array with 2 elements: the Vector2 coordinates.
  2259. */
  2260. Vector2.prototype.asArray = function () {
  2261. var result = new Array();
  2262. this.toArray(result, 0);
  2263. return result;
  2264. };
  2265. /**
  2266. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2267. * @param source defines the source Vector2
  2268. * @returns the current updated Vector2
  2269. */
  2270. Vector2.prototype.copyFrom = function (source) {
  2271. this.x = source.x;
  2272. this.y = source.y;
  2273. return this;
  2274. };
  2275. /**
  2276. * Sets the Vector2 coordinates with the given floats
  2277. * @param x defines the first coordinate
  2278. * @param y defines the second coordinate
  2279. * @returns the current updated Vector2
  2280. */
  2281. Vector2.prototype.copyFromFloats = function (x, y) {
  2282. this.x = x;
  2283. this.y = y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given floats
  2288. * @param x defines the first coordinate
  2289. * @param y defines the second coordinate
  2290. * @returns the current updated Vector2
  2291. */
  2292. Vector2.prototype.set = function (x, y) {
  2293. return this.copyFromFloats(x, y);
  2294. };
  2295. /**
  2296. * Add another vector with the current one
  2297. * @param otherVector defines the other vector
  2298. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2299. */
  2300. Vector2.prototype.add = function (otherVector) {
  2301. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2305. * @param otherVector defines the other vector
  2306. * @param result defines the target vector
  2307. * @returns the unmodified current Vector2
  2308. */
  2309. Vector2.prototype.addToRef = function (otherVector, result) {
  2310. result.x = this.x + otherVector.x;
  2311. result.y = this.y + otherVector.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2316. * @param otherVector defines the other vector
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.addInPlace = function (otherVector) {
  2320. this.x += otherVector.x;
  2321. this.y += otherVector.y;
  2322. return this;
  2323. };
  2324. /**
  2325. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.addVector3 = function (otherVector) {
  2330. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2331. };
  2332. /**
  2333. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2334. * @param otherVector defines the other vector
  2335. * @returns a new Vector2
  2336. */
  2337. Vector2.prototype.subtract = function (otherVector) {
  2338. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2339. };
  2340. /**
  2341. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2342. * @param otherVector defines the other vector
  2343. * @param result defines the target vector
  2344. * @returns the unmodified current Vector2
  2345. */
  2346. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2347. result.x = this.x - otherVector.x;
  2348. result.y = this.y - otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns the current updated Vector2
  2355. */
  2356. Vector2.prototype.subtractInPlace = function (otherVector) {
  2357. this.x -= otherVector.x;
  2358. this.y -= otherVector.y;
  2359. return this;
  2360. };
  2361. /**
  2362. * Multiplies in place the current Vector2 coordinates by the given ones
  2363. * @param otherVector defines the other vector
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2367. this.x *= otherVector.x;
  2368. this.y *= otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.multiply = function (otherVector) {
  2377. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2378. };
  2379. /**
  2380. * Sets "result" coordinates with the multiplication of the current Vector2 and 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.multiplyToRef = function (otherVector, result) {
  2386. result.x = this.x * otherVector.x;
  2387. result.y = this.y * otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2392. * @param x defines the first coordinate
  2393. * @param y defines the second coordinate
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.multiplyByFloats = function (x, y) {
  2397. return new Vector2(this.x * x, this.y * y);
  2398. };
  2399. /**
  2400. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.divide = function (otherVector) {
  2405. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2406. };
  2407. /**
  2408. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2409. * @param otherVector defines the other vector
  2410. * @param result defines the target vector
  2411. * @returns the unmodified current Vector2
  2412. */
  2413. Vector2.prototype.divideToRef = function (otherVector, result) {
  2414. result.x = this.x / otherVector.x;
  2415. result.y = this.y / otherVector.y;
  2416. return this;
  2417. };
  2418. /**
  2419. * Divides the current Vector2 coordinates by the given ones
  2420. * @param otherVector defines the other vector
  2421. * @returns the current updated Vector2
  2422. */
  2423. Vector2.prototype.divideInPlace = function (otherVector) {
  2424. return this.divideToRef(otherVector, this);
  2425. };
  2426. /**
  2427. * Gets a new Vector2 with current Vector2 negated coordinates
  2428. * @returns a new Vector2
  2429. */
  2430. Vector2.prototype.negate = function () {
  2431. return new Vector2(-this.x, -this.y);
  2432. };
  2433. /**
  2434. * Multiply the Vector2 coordinates by scale
  2435. * @param scale defines the scaling factor
  2436. * @returns the current updated Vector2
  2437. */
  2438. Vector2.prototype.scaleInPlace = function (scale) {
  2439. this.x *= scale;
  2440. this.y *= scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2445. * @param scale defines the scaling factor
  2446. * @returns a new Vector2
  2447. */
  2448. Vector2.prototype.scale = function (scale) {
  2449. var result = new Vector2(0, 0);
  2450. this.scaleToRef(scale, result);
  2451. return result;
  2452. };
  2453. /**
  2454. * Scale the current Vector2 values by a factor to a given Vector2
  2455. * @param scale defines the scale factor
  2456. * @param result defines the Vector2 object where to store the result
  2457. * @returns the unmodified current Vector2
  2458. */
  2459. Vector2.prototype.scaleToRef = function (scale, result) {
  2460. result.x = this.x * scale;
  2461. result.y = this.y * scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2466. * @param scale defines the scale factor
  2467. * @param result defines the Vector2 object where to store the result
  2468. * @returns the unmodified current Vector2
  2469. */
  2470. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2471. result.x += this.x * scale;
  2472. result.y += this.y * scale;
  2473. return this;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals
  2477. * @param otherVector defines the other vector
  2478. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2479. */
  2480. Vector2.prototype.equals = function (otherVector) {
  2481. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2482. };
  2483. /**
  2484. * Gets a boolean if two vectors are equals (using an epsilon value)
  2485. * @param otherVector defines the other vector
  2486. * @param epsilon defines the minimal distance to consider equality
  2487. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2488. */
  2489. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2490. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2491. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2492. };
  2493. /**
  2494. * Gets a new Vector2 from current Vector2 floored values
  2495. * @returns a new Vector2
  2496. */
  2497. Vector2.prototype.floor = function () {
  2498. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2499. };
  2500. /**
  2501. * Gets a new Vector2 from current Vector2 floored values
  2502. * @returns a new Vector2
  2503. */
  2504. Vector2.prototype.fract = function () {
  2505. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2506. };
  2507. // Properties
  2508. /**
  2509. * Gets the length of the vector
  2510. * @returns the vector length (float)
  2511. */
  2512. Vector2.prototype.length = function () {
  2513. return Math.sqrt(this.x * this.x + this.y * this.y);
  2514. };
  2515. /**
  2516. * Gets the vector squared length
  2517. * @returns the vector squared length (float)
  2518. */
  2519. Vector2.prototype.lengthSquared = function () {
  2520. return (this.x * this.x + this.y * this.y);
  2521. };
  2522. // Methods
  2523. /**
  2524. * Normalize the vector
  2525. * @returns the current updated Vector2
  2526. */
  2527. Vector2.prototype.normalize = function () {
  2528. var len = this.length();
  2529. if (len === 0)
  2530. return this;
  2531. var num = 1.0 / len;
  2532. this.x *= num;
  2533. this.y *= num;
  2534. return this;
  2535. };
  2536. /**
  2537. * Gets a new Vector2 copied from the Vector2
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.prototype.clone = function () {
  2541. return new Vector2(this.x, this.y);
  2542. };
  2543. // Statics
  2544. /**
  2545. * Gets a new Vector2(0, 0)
  2546. * @returns a new Vector2
  2547. */
  2548. Vector2.Zero = function () {
  2549. return new Vector2(0, 0);
  2550. };
  2551. /**
  2552. * Gets a new Vector2(1, 1)
  2553. * @returns a new Vector2
  2554. */
  2555. Vector2.One = function () {
  2556. return new Vector2(1, 1);
  2557. };
  2558. /**
  2559. * Gets a new Vector2 set from the given index element of the given array
  2560. * @param array defines the data source
  2561. * @param offset defines the offset in the data source
  2562. * @returns a new Vector2
  2563. */
  2564. Vector2.FromArray = function (array, offset) {
  2565. if (offset === void 0) { offset = 0; }
  2566. return new Vector2(array[offset], array[offset + 1]);
  2567. };
  2568. /**
  2569. * Sets "result" from the given index element of the given array
  2570. * @param array defines the data source
  2571. * @param offset defines the offset in the data source
  2572. * @param result defines the target vector
  2573. */
  2574. Vector2.FromArrayToRef = function (array, offset, result) {
  2575. result.x = array[offset];
  2576. result.y = array[offset + 1];
  2577. };
  2578. /**
  2579. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2580. * @param value1 defines 1st point of control
  2581. * @param value2 defines 2nd point of control
  2582. * @param value3 defines 3rd point of control
  2583. * @param value4 defines 4th point of control
  2584. * @param amount defines the interpolation factor
  2585. * @returns a new Vector2
  2586. */
  2587. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2588. var squared = amount * amount;
  2589. var cubed = amount * squared;
  2590. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2591. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2592. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2594. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2595. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2596. return new Vector2(x, y);
  2597. };
  2598. /**
  2599. * 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".
  2600. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2601. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2602. * @param value defines the value to clamp
  2603. * @param min defines the lower limit
  2604. * @param max defines the upper limit
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.Clamp = function (value, min, max) {
  2608. var x = value.x;
  2609. x = (x > max.x) ? max.x : x;
  2610. x = (x < min.x) ? min.x : x;
  2611. var y = value.y;
  2612. y = (y > max.y) ? max.y : y;
  2613. y = (y < min.y) ? min.y : y;
  2614. return new Vector2(x, y);
  2615. };
  2616. /**
  2617. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2618. * @param value1 defines the 1st control point
  2619. * @param tangent1 defines the outgoing tangent
  2620. * @param value2 defines the 2nd control point
  2621. * @param tangent2 defines the incoming tangent
  2622. * @param amount defines the interpolation factor
  2623. * @returns a new Vector2
  2624. */
  2625. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2626. var squared = amount * amount;
  2627. var cubed = amount * squared;
  2628. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2629. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2630. var part3 = (cubed - (2.0 * squared)) + amount;
  2631. var part4 = cubed - squared;
  2632. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2633. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2638. * @param start defines the start vector
  2639. * @param end defines the end vector
  2640. * @param amount defines the interpolation factor
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Lerp = function (start, end, amount) {
  2644. var x = start.x + ((end.x - start.x) * amount);
  2645. var y = start.y + ((end.y - start.y) * amount);
  2646. return new Vector2(x, y);
  2647. };
  2648. /**
  2649. * Gets the dot product of the vector "left" and the vector "right"
  2650. * @param left defines first vector
  2651. * @param right defines second vector
  2652. * @returns the dot product (float)
  2653. */
  2654. Vector2.Dot = function (left, right) {
  2655. return left.x * right.x + left.y * right.y;
  2656. };
  2657. /**
  2658. * Returns a new Vector2 equal to the normalized given vector
  2659. * @param vector defines the vector to normalize
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Normalize = function (vector) {
  2663. var newVector = vector.clone();
  2664. newVector.normalize();
  2665. return newVector;
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2669. * @param left defines 1st vector
  2670. * @param right defines 2nd vector
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Minimize = function (left, right) {
  2674. var x = (left.x < right.x) ? left.x : right.x;
  2675. var y = (left.y < right.y) ? left.y : right.y;
  2676. return new Vector2(x, y);
  2677. };
  2678. /**
  2679. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2680. * @param left defines 1st vector
  2681. * @param right defines 2nd vector
  2682. * @returns a new Vector2
  2683. */
  2684. Vector2.Maximize = function (left, right) {
  2685. var x = (left.x > right.x) ? left.x : right.x;
  2686. var y = (left.y > right.y) ? left.y : right.y;
  2687. return new Vector2(x, y);
  2688. };
  2689. /**
  2690. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2691. * @param vector defines the vector to transform
  2692. * @param transformation defines the matrix to apply
  2693. * @returns a new Vector2
  2694. */
  2695. Vector2.Transform = function (vector, transformation) {
  2696. var r = Vector2.Zero();
  2697. Vector2.TransformToRef(vector, transformation, r);
  2698. return r;
  2699. };
  2700. /**
  2701. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2702. * @param vector defines the vector to transform
  2703. * @param transformation defines the matrix to apply
  2704. * @param result defines the target vector
  2705. */
  2706. Vector2.TransformToRef = function (vector, transformation, result) {
  2707. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2708. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2709. result.x = x;
  2710. result.y = y;
  2711. };
  2712. /**
  2713. * Determines if a given vector is included in a triangle
  2714. * @param p defines the vector to test
  2715. * @param p0 defines 1st triangle point
  2716. * @param p1 defines 2nd triangle point
  2717. * @param p2 defines 3rd triangle point
  2718. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2719. */
  2720. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2721. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2722. var sign = a < 0 ? -1 : 1;
  2723. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2724. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2725. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2726. };
  2727. /**
  2728. * Gets the distance between the vectors "value1" and "value2"
  2729. * @param value1 defines first vector
  2730. * @param value2 defines second vector
  2731. * @returns the distance between vectors
  2732. */
  2733. Vector2.Distance = function (value1, value2) {
  2734. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2735. };
  2736. /**
  2737. * Returns the squared distance between the vectors "value1" and "value2"
  2738. * @param value1 defines first vector
  2739. * @param value2 defines second vector
  2740. * @returns the squared distance between vectors
  2741. */
  2742. Vector2.DistanceSquared = function (value1, value2) {
  2743. var x = value1.x - value2.x;
  2744. var y = value1.y - value2.y;
  2745. return (x * x) + (y * y);
  2746. };
  2747. /**
  2748. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2749. * @param value1 defines first vector
  2750. * @param value2 defines second vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Center = function (value1, value2) {
  2754. var center = value1.add(value2);
  2755. center.scaleInPlace(0.5);
  2756. return center;
  2757. };
  2758. /**
  2759. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2760. * @param p defines the middle point
  2761. * @param segA defines one point of the segment
  2762. * @param segB defines the other point of the segment
  2763. * @returns the shortest distance
  2764. */
  2765. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2766. var l2 = Vector2.DistanceSquared(segA, segB);
  2767. if (l2 === 0.0) {
  2768. return Vector2.Distance(p, segA);
  2769. }
  2770. var v = segB.subtract(segA);
  2771. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2772. var proj = segA.add(v.multiplyByFloats(t, t));
  2773. return Vector2.Distance(p, proj);
  2774. };
  2775. return Vector2;
  2776. }());
  2777. BABYLON.Vector2 = Vector2;
  2778. /**
  2779. * Classed used to store (x,y,z) vector representation
  2780. * A Vector3 is the main object used in 3D geometry
  2781. * It can represent etiher the coordinates of a point the space, either a direction
  2782. * Reminder: Babylon.js uses a left handed forward facing system
  2783. */
  2784. var Vector3 = /** @class */ (function () {
  2785. /**
  2786. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2787. * @param x defines the first coordinates (on X axis)
  2788. * @param y defines the second coordinates (on Y axis)
  2789. * @param z defines the third coordinates (on Z axis)
  2790. */
  2791. function Vector3(
  2792. /**
  2793. * Defines the first coordinates (on X axis)
  2794. */
  2795. x,
  2796. /**
  2797. * Defines the second coordinates (on Y axis)
  2798. */
  2799. y,
  2800. /**
  2801. * Defines the third coordinates (on Z axis)
  2802. */
  2803. z) {
  2804. if (x === void 0) { x = 0; }
  2805. if (y === void 0) { y = 0; }
  2806. if (z === void 0) { z = 0; }
  2807. this.x = x;
  2808. this.y = y;
  2809. this.z = z;
  2810. }
  2811. /**
  2812. * Creates a string representation of the Vector3
  2813. * @returns a string with the Vector3 coordinates.
  2814. */
  2815. Vector3.prototype.toString = function () {
  2816. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2817. };
  2818. /**
  2819. * Gets the class name
  2820. * @returns the string "Vector3"
  2821. */
  2822. Vector3.prototype.getClassName = function () {
  2823. return "Vector3";
  2824. };
  2825. /**
  2826. * Creates the Vector3 hash code
  2827. * @returns a number which tends to be unique between Vector3 instances
  2828. */
  2829. Vector3.prototype.getHashCode = function () {
  2830. var hash = this.x || 0;
  2831. hash = (hash * 397) ^ (this.y || 0);
  2832. hash = (hash * 397) ^ (this.z || 0);
  2833. return hash;
  2834. };
  2835. // Operators
  2836. /**
  2837. * Creates an array containing three elements : the coordinates of the Vector3
  2838. * @returns a new array of numbers
  2839. */
  2840. Vector3.prototype.asArray = function () {
  2841. var result = [];
  2842. this.toArray(result, 0);
  2843. return result;
  2844. };
  2845. /**
  2846. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2847. * @param array defines the destination array
  2848. * @param index defines the offset in the destination array
  2849. * @returns the current Vector3
  2850. */
  2851. Vector3.prototype.toArray = function (array, index) {
  2852. if (index === void 0) { index = 0; }
  2853. array[index] = this.x;
  2854. array[index + 1] = this.y;
  2855. array[index + 2] = this.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2860. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2861. */
  2862. Vector3.prototype.toQuaternion = function () {
  2863. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2864. };
  2865. /**
  2866. * Adds the given vector to the current Vector3
  2867. * @param otherVector defines the second operand
  2868. * @returns the current updated Vector3
  2869. */
  2870. Vector3.prototype.addInPlace = function (otherVector) {
  2871. this.x += otherVector.x;
  2872. this.y += otherVector.y;
  2873. this.z += otherVector.z;
  2874. return this;
  2875. };
  2876. /**
  2877. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2878. * @param otherVector defines the second operand
  2879. * @returns the resulting Vector3
  2880. */
  2881. Vector3.prototype.add = function (otherVector) {
  2882. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2883. };
  2884. /**
  2885. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2886. * @param otherVector defines the second operand
  2887. * @param result defines the Vector3 object where to store the result
  2888. * @returns the current Vector3
  2889. */
  2890. Vector3.prototype.addToRef = function (otherVector, result) {
  2891. result.x = this.x + otherVector.x;
  2892. result.y = this.y + otherVector.y;
  2893. result.z = this.z + otherVector.z;
  2894. return this;
  2895. };
  2896. /**
  2897. * Subtract the given vector from the current Vector3
  2898. * @param otherVector defines the second operand
  2899. * @returns the current updated Vector3
  2900. */
  2901. Vector3.prototype.subtractInPlace = function (otherVector) {
  2902. this.x -= otherVector.x;
  2903. this.y -= otherVector.y;
  2904. this.z -= otherVector.z;
  2905. return this;
  2906. };
  2907. /**
  2908. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2909. * @param otherVector defines the second operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtract = function (otherVector) {
  2913. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2914. };
  2915. /**
  2916. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2917. * @param otherVector defines the second operand
  2918. * @param result defines the Vector3 object where to store the result
  2919. * @returns the current Vector3
  2920. */
  2921. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2922. result.x = this.x - otherVector.x;
  2923. result.y = this.y - otherVector.y;
  2924. result.z = this.z - otherVector.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2929. * @param x defines the x coordinate of the operand
  2930. * @param y defines the y coordinate of the operand
  2931. * @param z defines the z coordinate of the operand
  2932. * @returns the resulting Vector3
  2933. */
  2934. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2935. return new Vector3(this.x - x, this.y - y, this.z - z);
  2936. };
  2937. /**
  2938. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2939. * @param x defines the x coordinate of the operand
  2940. * @param y defines the y coordinate of the operand
  2941. * @param z defines the z coordinate of the operand
  2942. * @param result defines the Vector3 object where to store the result
  2943. * @returns the current Vector3
  2944. */
  2945. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2946. result.x = this.x - x;
  2947. result.y = this.y - y;
  2948. result.z = this.z - z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2953. * @returns a new Vector3
  2954. */
  2955. Vector3.prototype.negate = function () {
  2956. return new Vector3(-this.x, -this.y, -this.z);
  2957. };
  2958. /**
  2959. * Multiplies the Vector3 coordinates by the float "scale"
  2960. * @param scale defines the multiplier factor
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.scaleInPlace = function (scale) {
  2964. this.x *= scale;
  2965. this.y *= scale;
  2966. this.z *= scale;
  2967. return this;
  2968. };
  2969. /**
  2970. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2971. * @param scale defines the multiplier factor
  2972. * @returns a new Vector3
  2973. */
  2974. Vector3.prototype.scale = function (scale) {
  2975. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2979. * @param scale defines the multiplier factor
  2980. * @param result defines the Vector3 object where to store the result
  2981. * @returns the current Vector3
  2982. */
  2983. Vector3.prototype.scaleToRef = function (scale, result) {
  2984. result.x = this.x * scale;
  2985. result.y = this.y * scale;
  2986. result.z = this.z * scale;
  2987. return this;
  2988. };
  2989. /**
  2990. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2991. * @param scale defines the scale factor
  2992. * @param result defines the Vector3 object where to store the result
  2993. * @returns the unmodified current Vector3
  2994. */
  2995. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2996. result.x += this.x * scale;
  2997. result.y += this.y * scale;
  2998. result.z += this.z * scale;
  2999. return this;
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3003. * @param otherVector defines the second operand
  3004. * @returns true if both vectors are equals
  3005. */
  3006. Vector3.prototype.equals = function (otherVector) {
  3007. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3008. };
  3009. /**
  3010. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3011. * @param otherVector defines the second operand
  3012. * @param epsilon defines the minimal distance to define values as equals
  3013. * @returns true if both vectors are distant less than epsilon
  3014. */
  3015. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3017. 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);
  3018. };
  3019. /**
  3020. * Returns true if the current Vector3 coordinates equals the given floats
  3021. * @param x defines the x coordinate of the operand
  3022. * @param y defines the y coordinate of the operand
  3023. * @param z defines the z coordinate of the operand
  3024. * @returns true if both vectors are equals
  3025. */
  3026. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3027. return this.x === x && this.y === y && this.z === z;
  3028. };
  3029. /**
  3030. * Multiplies the current Vector3 coordinates by the given ones
  3031. * @param otherVector defines the second operand
  3032. * @returns the current updated Vector3
  3033. */
  3034. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3035. this.x *= otherVector.x;
  3036. this.y *= otherVector.y;
  3037. this.z *= otherVector.z;
  3038. return this;
  3039. };
  3040. /**
  3041. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3042. * @param otherVector defines the second operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiply = function (otherVector) {
  3046. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3047. };
  3048. /**
  3049. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3050. * @param otherVector defines the second operand
  3051. * @param result defines the Vector3 object where to store the result
  3052. * @returns the current Vector3
  3053. */
  3054. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3055. result.x = this.x * otherVector.x;
  3056. result.y = this.y * otherVector.y;
  3057. result.z = this.z * otherVector.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3062. * @param x defines the x coordinate of the operand
  3063. * @param y defines the y coordinate of the operand
  3064. * @param z defines the z coordinate of the operand
  3065. * @returns the new Vector3
  3066. */
  3067. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3068. return new Vector3(this.x * x, this.y * y, this.z * z);
  3069. };
  3070. /**
  3071. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3072. * @param otherVector defines the second operand
  3073. * @returns the new Vector3
  3074. */
  3075. Vector3.prototype.divide = function (otherVector) {
  3076. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3077. };
  3078. /**
  3079. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3080. * @param otherVector defines the second operand
  3081. * @param result defines the Vector3 object where to store the result
  3082. * @returns the current Vector3
  3083. */
  3084. Vector3.prototype.divideToRef = function (otherVector, result) {
  3085. result.x = this.x / otherVector.x;
  3086. result.y = this.y / otherVector.y;
  3087. result.z = this.z / otherVector.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Divides the current Vector3 coordinates by the given ones.
  3092. * @param otherVector defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.divideInPlace = function (otherVector) {
  3096. return this.divideToRef(otherVector, this);
  3097. };
  3098. /**
  3099. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3100. * @param other defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.minimizeInPlace = function (other) {
  3104. if (other.x < this.x)
  3105. this.x = other.x;
  3106. if (other.y < this.y)
  3107. this.y = other.y;
  3108. if (other.z < this.z)
  3109. this.z = other.z;
  3110. return this;
  3111. };
  3112. /**
  3113. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3114. * @param other defines the second operand
  3115. * @returns the current updated Vector3
  3116. */
  3117. Vector3.prototype.maximizeInPlace = function (other) {
  3118. if (other.x > this.x)
  3119. this.x = other.x;
  3120. if (other.y > this.y)
  3121. this.y = other.y;
  3122. if (other.z > this.z)
  3123. this.z = other.z;
  3124. return this;
  3125. };
  3126. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3127. /**
  3128. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3129. */
  3130. get: function () {
  3131. var absX = Math.abs(this.x);
  3132. var absY = Math.abs(this.y);
  3133. if (absX !== absY) {
  3134. return true;
  3135. }
  3136. var absZ = Math.abs(this.z);
  3137. if (absX !== absZ) {
  3138. return true;
  3139. }
  3140. if (absY !== absZ) {
  3141. return true;
  3142. }
  3143. return false;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. /**
  3149. * Gets a new Vector3 from current Vector3 floored values
  3150. * @returns a new Vector3
  3151. */
  3152. Vector3.prototype.floor = function () {
  3153. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3154. };
  3155. /**
  3156. * Gets a new Vector3 from current Vector3 floored values
  3157. * @returns a new Vector3
  3158. */
  3159. Vector3.prototype.fract = function () {
  3160. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3161. };
  3162. // Properties
  3163. /**
  3164. * Gets the length of the Vector3
  3165. * @returns the length of the Vecto3
  3166. */
  3167. Vector3.prototype.length = function () {
  3168. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3169. };
  3170. /**
  3171. * Gets the squared length of the Vector3
  3172. * @returns squared length of the Vector3
  3173. */
  3174. Vector3.prototype.lengthSquared = function () {
  3175. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3176. };
  3177. /**
  3178. * Normalize the current Vector3.
  3179. * Please note that this is an in place operation.
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.normalize = function () {
  3183. var len = this.length();
  3184. if (len === 0 || len === 1.0)
  3185. return this;
  3186. var num = 1.0 / len;
  3187. this.x *= num;
  3188. this.y *= num;
  3189. this.z *= num;
  3190. return this;
  3191. };
  3192. /**
  3193. * Normalize the current Vector3 to a new vector
  3194. * @returns the new Vector3
  3195. */
  3196. Vector3.prototype.normalizeToNew = function () {
  3197. var normalized = new Vector3(0, 0, 0);
  3198. this.normalizeToRef(normalized);
  3199. return normalized;
  3200. };
  3201. /**
  3202. * Normalize the current Vector3 to the reference
  3203. * @param reference define the Vector3 to update
  3204. * @returns the updated Vector3
  3205. */
  3206. Vector3.prototype.normalizeToRef = function (reference) {
  3207. var len = this.length();
  3208. if (len === 0 || len === 1.0) {
  3209. reference.set(this.x, this.y, this.z);
  3210. return reference;
  3211. }
  3212. var scale = 1.0 / len;
  3213. this.scaleToRef(scale, reference);
  3214. return reference;
  3215. };
  3216. /**
  3217. * Creates a new Vector3 copied from the current Vector3
  3218. * @returns the new Vector3
  3219. */
  3220. Vector3.prototype.clone = function () {
  3221. return new Vector3(this.x, this.y, this.z);
  3222. };
  3223. /**
  3224. * Copies the given vector coordinates to the current Vector3 ones
  3225. * @param source defines the source Vector3
  3226. * @returns the current updated Vector3
  3227. */
  3228. Vector3.prototype.copyFrom = function (source) {
  3229. this.x = source.x;
  3230. this.y = source.y;
  3231. this.z = source.z;
  3232. return this;
  3233. };
  3234. /**
  3235. * Copies the given floats to the current Vector3 coordinates
  3236. * @param x defines the x coordinate of the operand
  3237. * @param y defines the y coordinate of the operand
  3238. * @param z defines the z coordinate of the operand
  3239. * @returns the current updated Vector3
  3240. */
  3241. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3242. this.x = x;
  3243. this.y = y;
  3244. this.z = z;
  3245. return this;
  3246. };
  3247. /**
  3248. * Copies the given floats to the current Vector3 coordinates
  3249. * @param x defines the x coordinate of the operand
  3250. * @param y defines the y coordinate of the operand
  3251. * @param z defines the z coordinate of the operand
  3252. * @returns the current updated Vector3
  3253. */
  3254. Vector3.prototype.set = function (x, y, z) {
  3255. return this.copyFromFloats(x, y, z);
  3256. };
  3257. // Statics
  3258. /**
  3259. * Get the clip factor between two vectors
  3260. * @param vector0 defines the first operand
  3261. * @param vector1 defines the second operand
  3262. * @param axis defines the axis to use
  3263. * @param size defines the size along the axis
  3264. * @returns the clip factor
  3265. */
  3266. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3267. var d0 = Vector3.Dot(vector0, axis) - size;
  3268. var d1 = Vector3.Dot(vector1, axis) - size;
  3269. var s = d0 / (d0 - d1);
  3270. return s;
  3271. };
  3272. /**
  3273. * Get angle between two vectors
  3274. * @param vector0 angle between vector0 and vector1
  3275. * @param vector1 angle between vector0 and vector1
  3276. * @param normal direction of the normal
  3277. * @return the angle between vector0 and vector1
  3278. */
  3279. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3280. var v0 = vector0.clone().normalize();
  3281. var v1 = vector1.clone().normalize();
  3282. var dot = Vector3.Dot(v0, v1);
  3283. var n = Vector3.Cross(v0, v1);
  3284. if (Vector3.Dot(n, normal) > 0) {
  3285. return Math.acos(dot);
  3286. }
  3287. return -Math.acos(dot);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set from the index "offset" of the given array
  3291. * @param array defines the source array
  3292. * @param offset defines the offset in the source array
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.FromArray = function (array, offset) {
  3296. if (!offset) {
  3297. offset = 0;
  3298. }
  3299. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3300. };
  3301. /**
  3302. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3303. * This function is deprecated. Use FromArray instead
  3304. * @param array defines the source array
  3305. * @param offset defines the offset in the source array
  3306. * @returns the new Vector3
  3307. */
  3308. Vector3.FromFloatArray = function (array, offset) {
  3309. return Vector3.FromArray(array, offset);
  3310. };
  3311. /**
  3312. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3313. * @param array defines the source array
  3314. * @param offset defines the offset in the source array
  3315. * @param result defines the Vector3 where to store the result
  3316. */
  3317. Vector3.FromArrayToRef = function (array, offset, result) {
  3318. result.x = array[offset];
  3319. result.y = array[offset + 1];
  3320. result.z = array[offset + 2];
  3321. };
  3322. /**
  3323. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArrayToRef instead.
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @param result defines the Vector3 where to store the result
  3328. */
  3329. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3330. return Vector3.FromArrayToRef(array, offset, result);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the given floats.
  3334. * @param x defines the x coordinate of the source
  3335. * @param y defines the y coordinate of the source
  3336. * @param z defines the z coordinate of the source
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3340. result.x = x;
  3341. result.y = y;
  3342. result.z = z;
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3346. * @returns a new empty Vector3
  3347. */
  3348. Vector3.Zero = function () {
  3349. return new Vector3(0.0, 0.0, 0.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3353. * @returns a new unit Vector3
  3354. */
  3355. Vector3.One = function () {
  3356. return new Vector3(1.0, 1.0, 1.0);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3360. * @returns a new up Vector3
  3361. */
  3362. Vector3.Up = function () {
  3363. return new Vector3(0.0, 1.0, 0.0);
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3367. * @returns a new down Vector3
  3368. */
  3369. Vector3.Down = function () {
  3370. return new Vector3(0.0, -1.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3374. * @returns a new forward Vector3
  3375. */
  3376. Vector3.Forward = function () {
  3377. return new Vector3(0.0, 0.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3381. * @returns a new right Vector3
  3382. */
  3383. Vector3.Right = function () {
  3384. return new Vector3(1.0, 0.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3388. * @returns a new left Vector3
  3389. */
  3390. Vector3.Left = function () {
  3391. return new Vector3(-1.0, 0.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3395. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3396. * @param vector defines the Vector3 to transform
  3397. * @param transformation defines the transformation matrix
  3398. * @returns the transformed Vector3
  3399. */
  3400. Vector3.TransformCoordinates = function (vector, transformation) {
  3401. var result = Vector3.Zero();
  3402. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3403. return result;
  3404. };
  3405. /**
  3406. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3407. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3408. * @param vector defines the Vector3 to transform
  3409. * @param transformation defines the transformation matrix
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3413. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3414. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3415. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3416. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3417. result.x = x / w;
  3418. result.y = y / w;
  3419. result.z = z / w;
  3420. };
  3421. /**
  3422. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3423. * This method computes tranformed coordinates only, not transformed direction vectors
  3424. * @param x define the x coordinate of the source vector
  3425. * @param y define the y coordinate of the source vector
  3426. * @param z define the z coordinate of the source vector
  3427. * @param transformation defines the transformation matrix
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3435. result.x = rx / rw;
  3436. result.y = ry / rw;
  3437. result.z = rz / rw;
  3438. };
  3439. /**
  3440. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param vector defines the Vector3 to transform
  3443. * @param transformation defines the transformation matrix
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.TransformNormal = function (vector, transformation) {
  3447. var result = Vector3.Zero();
  3448. Vector3.TransformNormalToRef(vector, transformation, result);
  3449. return result;
  3450. };
  3451. /**
  3452. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3453. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3454. * @param vector defines the Vector3 to transform
  3455. * @param transformation defines the transformation matrix
  3456. * @param result defines the Vector3 where to store the result
  3457. */
  3458. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3459. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3460. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3461. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3462. result.x = x;
  3463. result.y = y;
  3464. result.z = z;
  3465. };
  3466. /**
  3467. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param x define the x coordinate of the source vector
  3470. * @param y define the y coordinate of the source vector
  3471. * @param z define the z coordinate of the source vector
  3472. * @param transformation defines the transformation matrix
  3473. * @param result defines the Vector3 where to store the result
  3474. */
  3475. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3476. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3477. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3478. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3479. };
  3480. /**
  3481. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3482. * @param value1 defines the first control point
  3483. * @param value2 defines the second control point
  3484. * @param value3 defines the third control point
  3485. * @param value4 defines the fourth control point
  3486. * @param amount defines the amount on the spline to use
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3490. var squared = amount * amount;
  3491. var cubed = amount * squared;
  3492. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3493. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3494. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3495. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3496. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3497. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3498. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3499. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3500. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3501. return new Vector3(x, y, z);
  3502. };
  3503. /**
  3504. * 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"
  3505. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3506. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3507. * @param value defines the current value
  3508. * @param min defines the lower range value
  3509. * @param max defines the upper range value
  3510. * @returns the new Vector3
  3511. */
  3512. Vector3.Clamp = function (value, min, max) {
  3513. var x = value.x;
  3514. x = (x > max.x) ? max.x : x;
  3515. x = (x < min.x) ? min.x : x;
  3516. var y = value.y;
  3517. y = (y > max.y) ? max.y : y;
  3518. y = (y < min.y) ? min.y : y;
  3519. var z = value.z;
  3520. z = (z > max.z) ? max.z : z;
  3521. z = (z < min.z) ? min.z : z;
  3522. return new Vector3(x, y, z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3526. * @param value1 defines the first control point
  3527. * @param tangent1 defines the first tangent vector
  3528. * @param value2 defines the second control point
  3529. * @param tangent2 defines the second tangent vector
  3530. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3531. * @returns the new Vector3
  3532. */
  3533. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3534. var squared = amount * amount;
  3535. var cubed = amount * squared;
  3536. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3537. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3538. var part3 = (cubed - (2.0 * squared)) + amount;
  3539. var part4 = cubed - squared;
  3540. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3541. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3542. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3543. return new Vector3(x, y, z);
  3544. };
  3545. /**
  3546. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3547. * @param start defines the start value
  3548. * @param end defines the end value
  3549. * @param amount max defines amount between both (between 0 and 1)
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Lerp = function (start, end, amount) {
  3553. var result = new Vector3(0, 0, 0);
  3554. Vector3.LerpToRef(start, end, amount, result);
  3555. return result;
  3556. };
  3557. /**
  3558. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3559. * @param start defines the start value
  3560. * @param end defines the end value
  3561. * @param amount max defines amount between both (between 0 and 1)
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.LerpToRef = function (start, end, amount, result) {
  3565. result.x = start.x + ((end.x - start.x) * amount);
  3566. result.y = start.y + ((end.y - start.y) * amount);
  3567. result.z = start.z + ((end.z - start.z) * amount);
  3568. };
  3569. /**
  3570. * Returns the dot product (float) between the vectors "left" and "right"
  3571. * @param left defines the left operand
  3572. * @param right defines the right operand
  3573. * @returns the dot product
  3574. */
  3575. Vector3.Dot = function (left, right) {
  3576. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3577. };
  3578. /**
  3579. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3580. * The cross product is then orthogonal to both "left" and "right"
  3581. * @param left defines the left operand
  3582. * @param right defines the right operand
  3583. * @returns the cross product
  3584. */
  3585. Vector3.Cross = function (left, right) {
  3586. var result = Vector3.Zero();
  3587. Vector3.CrossToRef(left, right, result);
  3588. return result;
  3589. };
  3590. /**
  3591. * Sets the given vector "result" with the cross product of "left" and "right"
  3592. * The cross product is then orthogonal to both "left" and "right"
  3593. * @param left defines the left operand
  3594. * @param right defines the right operand
  3595. * @param result defines the Vector3 where to store the result
  3596. */
  3597. Vector3.CrossToRef = function (left, right, result) {
  3598. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3599. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3600. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3601. result.copyFrom(MathTmp.Vector3[0]);
  3602. };
  3603. /**
  3604. * Returns a new Vector3 as the normalization of the given vector
  3605. * @param vector defines the Vector3 to normalize
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Normalize = function (vector) {
  3609. var result = Vector3.Zero();
  3610. Vector3.NormalizeToRef(vector, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Sets the given vector "result" with the normalization of the given first vector
  3615. * @param vector defines the Vector3 to normalize
  3616. * @param result defines the Vector3 where to store the result
  3617. */
  3618. Vector3.NormalizeToRef = function (vector, result) {
  3619. result.copyFrom(vector);
  3620. result.normalize();
  3621. };
  3622. /**
  3623. * Project a Vector3 onto screen space
  3624. * @param vector defines the Vector3 to project
  3625. * @param world defines the world matrix to use
  3626. * @param transform defines the transform (view x projection) matrix to use
  3627. * @param viewport defines the screen viewport to use
  3628. * @returns the new Vector3
  3629. */
  3630. Vector3.Project = function (vector, world, transform, viewport) {
  3631. var cw = viewport.width;
  3632. var ch = viewport.height;
  3633. var cx = viewport.x;
  3634. var cy = viewport.y;
  3635. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3636. 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);
  3637. var matrix = MathTmp.Matrix[0];
  3638. world.multiplyToRef(transform, matrix);
  3639. matrix.multiplyToRef(viewportMatrix, matrix);
  3640. return Vector3.TransformCoordinates(vector, matrix);
  3641. };
  3642. /**
  3643. * Unproject from screen space to object space
  3644. * @param source defines the screen space Vector3 to use
  3645. * @param viewportWidth defines the current width of the viewport
  3646. * @param viewportHeight defines the current height of the viewport
  3647. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3648. * @param transform defines the transform (view x projection) matrix to use
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3652. var matrix = MathTmp.Matrix[0];
  3653. world.multiplyToRef(transform, matrix);
  3654. matrix.invert();
  3655. source.x = source.x / viewportWidth * 2 - 1;
  3656. source.y = -(source.y / viewportHeight * 2 - 1);
  3657. var vector = Vector3.TransformCoordinates(source, matrix);
  3658. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3659. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3660. vector = vector.scale(1.0 / num);
  3661. }
  3662. return vector;
  3663. };
  3664. /**
  3665. * Unproject from screen space to object space
  3666. * @param source defines the screen space Vector3 to use
  3667. * @param viewportWidth defines the current width of the viewport
  3668. * @param viewportHeight defines the current height of the viewport
  3669. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3670. * @param view defines the view matrix to use
  3671. * @param projection defines the projection matrix to use
  3672. * @returns the new Vector3
  3673. */
  3674. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3675. var result = Vector3.Zero();
  3676. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3677. return result;
  3678. };
  3679. /**
  3680. * Unproject from screen space to object space
  3681. * @param source defines the screen space Vector3 to use
  3682. * @param viewportWidth defines the current width of the viewport
  3683. * @param viewportHeight defines the current height of the viewport
  3684. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3685. * @param view defines the view matrix to use
  3686. * @param projection defines the projection matrix to use
  3687. * @param result defines the Vector3 where to store the result
  3688. */
  3689. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3690. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3691. };
  3692. /**
  3693. * Unproject from screen space to object space
  3694. * @param sourceX defines the screen space x coordinate to use
  3695. * @param sourceY defines the screen space y coordinate to use
  3696. * @param sourceZ defines the screen space z coordinate to use
  3697. * @param viewportWidth defines the current width of the viewport
  3698. * @param viewportHeight defines the current height of the viewport
  3699. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3700. * @param view defines the view matrix to use
  3701. * @param projection defines the projection matrix to use
  3702. * @param result defines the Vector3 where to store the result
  3703. */
  3704. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3705. var matrix = MathTmp.Matrix[0];
  3706. world.multiplyToRef(view, matrix);
  3707. matrix.multiplyToRef(projection, matrix);
  3708. matrix.invert();
  3709. var screenSource = MathTmp.Vector3[0];
  3710. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3711. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3712. screenSource.z = 2 * sourceZ - 1.0;
  3713. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3714. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3715. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3716. result.scaleInPlace(1.0 / num);
  3717. }
  3718. };
  3719. /**
  3720. * Gets the minimal coordinate values between two Vector3
  3721. * @param left defines the first operand
  3722. * @param right defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Minimize = function (left, right) {
  3726. var min = left.clone();
  3727. min.minimizeInPlace(right);
  3728. return min;
  3729. };
  3730. /**
  3731. * Gets the maximal coordinate values between two Vector3
  3732. * @param left defines the first operand
  3733. * @param right defines the second operand
  3734. * @returns the new Vector3
  3735. */
  3736. Vector3.Maximize = function (left, right) {
  3737. var max = left.clone();
  3738. max.maximizeInPlace(right);
  3739. return max;
  3740. };
  3741. /**
  3742. * Returns the distance between the vectors "value1" and "value2"
  3743. * @param value1 defines the first operand
  3744. * @param value2 defines the second operand
  3745. * @returns the distance
  3746. */
  3747. Vector3.Distance = function (value1, value2) {
  3748. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3749. };
  3750. /**
  3751. * Returns the squared distance between the vectors "value1" and "value2"
  3752. * @param value1 defines the first operand
  3753. * @param value2 defines the second operand
  3754. * @returns the squared distance
  3755. */
  3756. Vector3.DistanceSquared = function (value1, value2) {
  3757. var x = value1.x - value2.x;
  3758. var y = value1.y - value2.y;
  3759. var z = value1.z - value2.z;
  3760. return (x * x) + (y * y) + (z * z);
  3761. };
  3762. /**
  3763. * Returns a new Vector3 located at the center between "value1" and "value2"
  3764. * @param value1 defines the first operand
  3765. * @param value2 defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Center = function (value1, value2) {
  3769. var center = value1.add(value2);
  3770. center.scaleInPlace(0.5);
  3771. return center;
  3772. };
  3773. /**
  3774. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3775. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3776. * to something in order to rotate it from its local system to the given target system
  3777. * Note: axis1, axis2 and axis3 are normalized during this operation
  3778. * @param axis1 defines the first axis
  3779. * @param axis2 defines the second axis
  3780. * @param axis3 defines the third axis
  3781. * @returns a new Vector3
  3782. */
  3783. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3784. var rotation = Vector3.Zero();
  3785. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3786. return rotation;
  3787. };
  3788. /**
  3789. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3790. * @param axis1 defines the first axis
  3791. * @param axis2 defines the second axis
  3792. * @param axis3 defines the third axis
  3793. * @param ref defines the Vector3 where to store the result
  3794. */
  3795. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3796. var quat = MathTmp.Quaternion[0];
  3797. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3798. quat.toEulerAnglesToRef(ref);
  3799. };
  3800. return Vector3;
  3801. }());
  3802. BABYLON.Vector3 = Vector3;
  3803. //Vector4 class created for EulerAngle class conversion to Quaternion
  3804. var Vector4 = /** @class */ (function () {
  3805. /**
  3806. * Creates a Vector4 object from the given floats.
  3807. */
  3808. function Vector4(x, y, z, w) {
  3809. this.x = x;
  3810. this.y = y;
  3811. this.z = z;
  3812. this.w = w;
  3813. }
  3814. /**
  3815. * Returns the string with the Vector4 coordinates.
  3816. */
  3817. Vector4.prototype.toString = function () {
  3818. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3819. };
  3820. /**
  3821. * Returns the string "Vector4".
  3822. */
  3823. Vector4.prototype.getClassName = function () {
  3824. return "Vector4";
  3825. };
  3826. /**
  3827. * Returns the Vector4 hash code.
  3828. */
  3829. Vector4.prototype.getHashCode = function () {
  3830. var hash = this.x || 0;
  3831. hash = (hash * 397) ^ (this.y || 0);
  3832. hash = (hash * 397) ^ (this.z || 0);
  3833. hash = (hash * 397) ^ (this.w || 0);
  3834. return hash;
  3835. };
  3836. // Operators
  3837. /**
  3838. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3839. */
  3840. Vector4.prototype.asArray = function () {
  3841. var result = new Array();
  3842. this.toArray(result, 0);
  3843. return result;
  3844. };
  3845. /**
  3846. * Populates the given array from the given index with the Vector4 coordinates.
  3847. * Returns the Vector4.
  3848. */
  3849. Vector4.prototype.toArray = function (array, index) {
  3850. if (index === undefined) {
  3851. index = 0;
  3852. }
  3853. array[index] = this.x;
  3854. array[index + 1] = this.y;
  3855. array[index + 2] = this.z;
  3856. array[index + 3] = this.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Adds the given vector to the current Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.addInPlace = function (otherVector) {
  3864. this.x += otherVector.x;
  3865. this.y += otherVector.y;
  3866. this.z += otherVector.z;
  3867. this.w += otherVector.w;
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3872. */
  3873. Vector4.prototype.add = function (otherVector) {
  3874. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3875. };
  3876. /**
  3877. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3878. * Returns the current Vector4.
  3879. */
  3880. Vector4.prototype.addToRef = function (otherVector, result) {
  3881. result.x = this.x + otherVector.x;
  3882. result.y = this.y + otherVector.y;
  3883. result.z = this.z + otherVector.z;
  3884. result.w = this.w + otherVector.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Subtract in place the given vector from the current Vector4.
  3889. * Returns the updated Vector4.
  3890. */
  3891. Vector4.prototype.subtractInPlace = function (otherVector) {
  3892. this.x -= otherVector.x;
  3893. this.y -= otherVector.y;
  3894. this.z -= otherVector.z;
  3895. this.w -= otherVector.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3900. */
  3901. Vector4.prototype.subtract = function (otherVector) {
  3902. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3903. };
  3904. /**
  3905. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3906. * Returns the current Vector4.
  3907. */
  3908. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3909. result.x = this.x - otherVector.x;
  3910. result.y = this.y - otherVector.y;
  3911. result.z = this.z - otherVector.z;
  3912. result.w = this.w - otherVector.w;
  3913. return this;
  3914. };
  3915. /**
  3916. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3917. */
  3918. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3919. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3920. };
  3921. /**
  3922. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3923. * Returns the current Vector4.
  3924. */
  3925. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3926. result.x = this.x - x;
  3927. result.y = this.y - y;
  3928. result.z = this.z - z;
  3929. result.w = this.w - w;
  3930. return this;
  3931. };
  3932. /**
  3933. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3934. */
  3935. Vector4.prototype.negate = function () {
  3936. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3937. };
  3938. /**
  3939. * Multiplies the current Vector4 coordinates by scale (float).
  3940. * Returns the updated Vector4.
  3941. */
  3942. Vector4.prototype.scaleInPlace = function (scale) {
  3943. this.x *= scale;
  3944. this.y *= scale;
  3945. this.z *= scale;
  3946. this.w *= scale;
  3947. return this;
  3948. };
  3949. /**
  3950. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3951. */
  3952. Vector4.prototype.scale = function (scale) {
  3953. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3954. };
  3955. /**
  3956. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3957. * Returns the current Vector4.
  3958. */
  3959. Vector4.prototype.scaleToRef = function (scale, result) {
  3960. result.x = this.x * scale;
  3961. result.y = this.y * scale;
  3962. result.z = this.z * scale;
  3963. result.w = this.w * scale;
  3964. return this;
  3965. };
  3966. /**
  3967. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3968. * @param scale defines the scale factor
  3969. * @param result defines the Vector4 object where to store the result
  3970. * @returns the unmodified current Vector4
  3971. */
  3972. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3973. result.x += this.x * scale;
  3974. result.y += this.y * scale;
  3975. result.z += this.z * scale;
  3976. result.w += this.w * scale;
  3977. return this;
  3978. };
  3979. /**
  3980. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3981. */
  3982. Vector4.prototype.equals = function (otherVector) {
  3983. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3984. };
  3985. /**
  3986. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3987. */
  3988. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3989. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3990. return otherVector
  3991. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3992. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3993. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3994. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3995. };
  3996. /**
  3997. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3998. */
  3999. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4000. return this.x === x && this.y === y && this.z === z && this.w === w;
  4001. };
  4002. /**
  4003. * Multiplies in place the current Vector4 by the given one.
  4004. * Returns the updated Vector4.
  4005. */
  4006. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4007. this.x *= otherVector.x;
  4008. this.y *= otherVector.y;
  4009. this.z *= otherVector.z;
  4010. this.w *= otherVector.w;
  4011. return this;
  4012. };
  4013. /**
  4014. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4015. */
  4016. Vector4.prototype.multiply = function (otherVector) {
  4017. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4018. };
  4019. /**
  4020. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4021. * Returns the current Vector4.
  4022. */
  4023. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4024. result.x = this.x * otherVector.x;
  4025. result.y = this.y * otherVector.y;
  4026. result.z = this.z * otherVector.z;
  4027. result.w = this.w * otherVector.w;
  4028. return this;
  4029. };
  4030. /**
  4031. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4032. */
  4033. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4034. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4035. };
  4036. /**
  4037. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4038. */
  4039. Vector4.prototype.divide = function (otherVector) {
  4040. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4041. };
  4042. /**
  4043. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4044. * Returns the current Vector4.
  4045. */
  4046. Vector4.prototype.divideToRef = function (otherVector, result) {
  4047. result.x = this.x / otherVector.x;
  4048. result.y = this.y / otherVector.y;
  4049. result.z = this.z / otherVector.z;
  4050. result.w = this.w / otherVector.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Divides the current Vector3 coordinates by the given ones.
  4055. * @returns the updated Vector3.
  4056. */
  4057. Vector4.prototype.divideInPlace = function (otherVector) {
  4058. return this.divideToRef(otherVector, this);
  4059. };
  4060. /**
  4061. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4062. * @param other defines the second operand
  4063. * @returns the current updated Vector4
  4064. */
  4065. Vector4.prototype.minimizeInPlace = function (other) {
  4066. if (other.x < this.x)
  4067. this.x = other.x;
  4068. if (other.y < this.y)
  4069. this.y = other.y;
  4070. if (other.z < this.z)
  4071. this.z = other.z;
  4072. if (other.w < this.w)
  4073. this.w = other.w;
  4074. return this;
  4075. };
  4076. /**
  4077. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4078. * @param other defines the second operand
  4079. * @returns the current updated Vector4
  4080. */
  4081. Vector4.prototype.maximizeInPlace = function (other) {
  4082. if (other.x > this.x)
  4083. this.x = other.x;
  4084. if (other.y > this.y)
  4085. this.y = other.y;
  4086. if (other.z > this.z)
  4087. this.z = other.z;
  4088. if (other.w > this.w)
  4089. this.w = other.w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Gets a new Vector4 from current Vector4 floored values
  4094. * @returns a new Vector4
  4095. */
  4096. Vector4.prototype.floor = function () {
  4097. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4098. };
  4099. /**
  4100. * Gets a new Vector4 from current Vector3 floored values
  4101. * @returns a new Vector4
  4102. */
  4103. Vector4.prototype.fract = function () {
  4104. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4105. };
  4106. // Properties
  4107. /**
  4108. * Returns the Vector4 length (float).
  4109. */
  4110. Vector4.prototype.length = function () {
  4111. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4112. };
  4113. /**
  4114. * Returns the Vector4 squared length (float).
  4115. */
  4116. Vector4.prototype.lengthSquared = function () {
  4117. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4118. };
  4119. // Methods
  4120. /**
  4121. * Normalizes in place the Vector4.
  4122. * Returns the updated Vector4.
  4123. */
  4124. Vector4.prototype.normalize = function () {
  4125. var len = this.length();
  4126. if (len === 0)
  4127. return this;
  4128. var num = 1.0 / len;
  4129. this.x *= num;
  4130. this.y *= num;
  4131. this.z *= num;
  4132. this.w *= num;
  4133. return this;
  4134. };
  4135. /**
  4136. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4137. */
  4138. Vector4.prototype.toVector3 = function () {
  4139. return new Vector3(this.x, this.y, this.z);
  4140. };
  4141. /**
  4142. * Returns a new Vector4 copied from the current one.
  4143. */
  4144. Vector4.prototype.clone = function () {
  4145. return new Vector4(this.x, this.y, this.z, this.w);
  4146. };
  4147. /**
  4148. * Updates the current Vector4 with the given one coordinates.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.copyFrom = function (source) {
  4152. this.x = source.x;
  4153. this.y = source.y;
  4154. this.z = source.z;
  4155. this.w = source.w;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates the current Vector4 coordinates with the given floats.
  4160. * Returns the updated Vector4.
  4161. */
  4162. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4163. this.x = x;
  4164. this.y = y;
  4165. this.z = z;
  4166. this.w = w;
  4167. return this;
  4168. };
  4169. /**
  4170. * Updates the current Vector4 coordinates with the given floats.
  4171. * Returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.set = function (x, y, z, w) {
  4174. return this.copyFromFloats(x, y, z, w);
  4175. };
  4176. // Statics
  4177. /**
  4178. * Returns a new Vector4 set from the starting index of the given array.
  4179. */
  4180. Vector4.FromArray = function (array, offset) {
  4181. if (!offset) {
  4182. offset = 0;
  4183. }
  4184. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4185. };
  4186. /**
  4187. * Updates the given vector "result" from the starting index of the given array.
  4188. */
  4189. Vector4.FromArrayToRef = function (array, offset, result) {
  4190. result.x = array[offset];
  4191. result.y = array[offset + 1];
  4192. result.z = array[offset + 2];
  4193. result.w = array[offset + 3];
  4194. };
  4195. /**
  4196. * Updates the given vector "result" from the starting index of the given Float32Array.
  4197. */
  4198. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4199. Vector4.FromArrayToRef(array, offset, result);
  4200. };
  4201. /**
  4202. * Updates the given vector "result" coordinates from the given floats.
  4203. */
  4204. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4205. result.x = x;
  4206. result.y = y;
  4207. result.z = z;
  4208. result.w = w;
  4209. };
  4210. /**
  4211. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4212. */
  4213. Vector4.Zero = function () {
  4214. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4215. };
  4216. /**
  4217. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4218. */
  4219. Vector4.One = function () {
  4220. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4221. };
  4222. /**
  4223. * Returns a new normalized Vector4 from the given one.
  4224. */
  4225. Vector4.Normalize = function (vector) {
  4226. var result = Vector4.Zero();
  4227. Vector4.NormalizeToRef(vector, result);
  4228. return result;
  4229. };
  4230. /**
  4231. * Updates the given vector "result" from the normalization of the given one.
  4232. */
  4233. Vector4.NormalizeToRef = function (vector, result) {
  4234. result.copyFrom(vector);
  4235. result.normalize();
  4236. };
  4237. Vector4.Minimize = function (left, right) {
  4238. var min = left.clone();
  4239. min.minimizeInPlace(right);
  4240. return min;
  4241. };
  4242. Vector4.Maximize = function (left, right) {
  4243. var max = left.clone();
  4244. max.maximizeInPlace(right);
  4245. return max;
  4246. };
  4247. /**
  4248. * Returns the distance (float) between the vectors "value1" and "value2".
  4249. */
  4250. Vector4.Distance = function (value1, value2) {
  4251. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4252. };
  4253. /**
  4254. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4255. */
  4256. Vector4.DistanceSquared = function (value1, value2) {
  4257. var x = value1.x - value2.x;
  4258. var y = value1.y - value2.y;
  4259. var z = value1.z - value2.z;
  4260. var w = value1.w - value2.w;
  4261. return (x * x) + (y * y) + (z * z) + (w * w);
  4262. };
  4263. /**
  4264. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4265. */
  4266. Vector4.Center = function (value1, value2) {
  4267. var center = value1.add(value2);
  4268. center.scaleInPlace(0.5);
  4269. return center;
  4270. };
  4271. /**
  4272. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4273. * This methods computes transformed normalized direction vectors only.
  4274. */
  4275. Vector4.TransformNormal = function (vector, transformation) {
  4276. var result = Vector4.Zero();
  4277. Vector4.TransformNormalToRef(vector, transformation, result);
  4278. return result;
  4279. };
  4280. /**
  4281. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4282. * This methods computes transformed normalized direction vectors only.
  4283. */
  4284. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4285. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4286. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4287. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4288. result.x = x;
  4289. result.y = y;
  4290. result.z = z;
  4291. result.w = vector.w;
  4292. };
  4293. /**
  4294. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4295. * This methods computes transformed normalized direction vectors only.
  4296. */
  4297. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4298. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4299. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4300. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4301. result.w = w;
  4302. };
  4303. return Vector4;
  4304. }());
  4305. BABYLON.Vector4 = Vector4;
  4306. var Size = /** @class */ (function () {
  4307. /**
  4308. * Creates a Size object from the given width and height (floats).
  4309. */
  4310. function Size(width, height) {
  4311. this.width = width;
  4312. this.height = height;
  4313. }
  4314. // Returns a string with the Size width and height.
  4315. Size.prototype.toString = function () {
  4316. return "{W: " + this.width + ", H: " + this.height + "}";
  4317. };
  4318. /**
  4319. * Returns the string "Size"
  4320. */
  4321. Size.prototype.getClassName = function () {
  4322. return "Size";
  4323. };
  4324. /**
  4325. * Returns the Size hash code.
  4326. */
  4327. Size.prototype.getHashCode = function () {
  4328. var hash = this.width || 0;
  4329. hash = (hash * 397) ^ (this.height || 0);
  4330. return hash;
  4331. };
  4332. /**
  4333. * Updates the current size from the given one.
  4334. * Returns the updated Size.
  4335. */
  4336. Size.prototype.copyFrom = function (src) {
  4337. this.width = src.width;
  4338. this.height = src.height;
  4339. };
  4340. /**
  4341. * Updates in place the current Size from the given floats.
  4342. * Returns the updated Size.
  4343. */
  4344. Size.prototype.copyFromFloats = function (width, height) {
  4345. this.width = width;
  4346. this.height = height;
  4347. return this;
  4348. };
  4349. /**
  4350. * Updates in place the current Size from the given floats.
  4351. * Returns the updated Size.
  4352. */
  4353. Size.prototype.set = function (width, height) {
  4354. return this.copyFromFloats(width, height);
  4355. };
  4356. /**
  4357. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4358. */
  4359. Size.prototype.multiplyByFloats = function (w, h) {
  4360. return new Size(this.width * w, this.height * h);
  4361. };
  4362. /**
  4363. * Returns a new Size copied from the given one.
  4364. */
  4365. Size.prototype.clone = function () {
  4366. return new Size(this.width, this.height);
  4367. };
  4368. /**
  4369. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4370. */
  4371. Size.prototype.equals = function (other) {
  4372. if (!other) {
  4373. return false;
  4374. }
  4375. return (this.width === other.width) && (this.height === other.height);
  4376. };
  4377. Object.defineProperty(Size.prototype, "surface", {
  4378. /**
  4379. * Returns the surface of the Size : width * height (float).
  4380. */
  4381. get: function () {
  4382. return this.width * this.height;
  4383. },
  4384. enumerable: true,
  4385. configurable: true
  4386. });
  4387. /**
  4388. * Returns a new Size set to (0.0, 0.0)
  4389. */
  4390. Size.Zero = function () {
  4391. return new Size(0.0, 0.0);
  4392. };
  4393. /**
  4394. * Returns a new Size set as the addition result of the current Size and the given one.
  4395. */
  4396. Size.prototype.add = function (otherSize) {
  4397. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4398. return r;
  4399. };
  4400. /**
  4401. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4402. */
  4403. Size.prototype.subtract = function (otherSize) {
  4404. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4405. return r;
  4406. };
  4407. /**
  4408. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4409. */
  4410. Size.Lerp = function (start, end, amount) {
  4411. var w = start.width + ((end.width - start.width) * amount);
  4412. var h = start.height + ((end.height - start.height) * amount);
  4413. return new Size(w, h);
  4414. };
  4415. return Size;
  4416. }());
  4417. BABYLON.Size = Size;
  4418. /**
  4419. * Class used to store quaternion data
  4420. * @see https://en.wikipedia.org/wiki/Quaternion
  4421. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4422. */
  4423. var Quaternion = /** @class */ (function () {
  4424. /**
  4425. * Creates a new Quaternion from the given floats
  4426. * @param x defines the first component (0 by default)
  4427. * @param y defines the second component (0 by default)
  4428. * @param z defines the third component (0 by default)
  4429. * @param w defines the fourth component (1.0 by default)
  4430. */
  4431. function Quaternion(
  4432. /** defines the first component (0 by default) */
  4433. x,
  4434. /** defines the second component (0 by default) */
  4435. y,
  4436. /** defines the third component (0 by default) */
  4437. z,
  4438. /** defines the fourth component (1.0 by default) */
  4439. w) {
  4440. if (x === void 0) { x = 0.0; }
  4441. if (y === void 0) { y = 0.0; }
  4442. if (z === void 0) { z = 0.0; }
  4443. if (w === void 0) { w = 1.0; }
  4444. this.x = x;
  4445. this.y = y;
  4446. this.z = z;
  4447. this.w = w;
  4448. }
  4449. /**
  4450. * Gets a string representation for the current quaternion
  4451. * @returns a string with the Quaternion coordinates
  4452. */
  4453. Quaternion.prototype.toString = function () {
  4454. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4455. };
  4456. /**
  4457. * Gets the class name of the quaternion
  4458. * @returns the string "Quaternion"
  4459. */
  4460. Quaternion.prototype.getClassName = function () {
  4461. return "Quaternion";
  4462. };
  4463. /**
  4464. * Gets a hash code for this quaternion
  4465. * @returns the quaternion hash code
  4466. */
  4467. Quaternion.prototype.getHashCode = function () {
  4468. var hash = this.x || 0;
  4469. hash = (hash * 397) ^ (this.y || 0);
  4470. hash = (hash * 397) ^ (this.z || 0);
  4471. hash = (hash * 397) ^ (this.w || 0);
  4472. return hash;
  4473. };
  4474. /**
  4475. * Copy the quaternion to an array
  4476. * @returns a new array populated with 4 elements from the quaternion coordinates
  4477. */
  4478. Quaternion.prototype.asArray = function () {
  4479. return [this.x, this.y, this.z, this.w];
  4480. };
  4481. /**
  4482. * Check if two quaternions are equals
  4483. * @param otherQuaternion defines the second operand
  4484. * @return true if the current quaternion and the given one coordinates are strictly equals
  4485. */
  4486. Quaternion.prototype.equals = function (otherQuaternion) {
  4487. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4488. };
  4489. /**
  4490. * Clone the current quaternion
  4491. * @returns a new quaternion copied from the current one
  4492. */
  4493. Quaternion.prototype.clone = function () {
  4494. return new Quaternion(this.x, this.y, this.z, this.w);
  4495. };
  4496. /**
  4497. * Copy a quaternion to the current one
  4498. * @param other defines the other quaternion
  4499. * @returns the updated current quaternion
  4500. */
  4501. Quaternion.prototype.copyFrom = function (other) {
  4502. this.x = other.x;
  4503. this.y = other.y;
  4504. this.z = other.z;
  4505. this.w = other.w;
  4506. return this;
  4507. };
  4508. /**
  4509. * Updates the current quaternion with the given float coordinates
  4510. * @param x defines the x coordinate
  4511. * @param y defines the y coordinate
  4512. * @param z defines the z coordinate
  4513. * @param w defines the w coordinate
  4514. * @returns the updated current quaternion
  4515. */
  4516. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4517. this.x = x;
  4518. this.y = y;
  4519. this.z = z;
  4520. this.w = w;
  4521. return this;
  4522. };
  4523. /**
  4524. * Updates the current quaternion from the given float coordinates
  4525. * @param x defines the x coordinate
  4526. * @param y defines the y coordinate
  4527. * @param z defines the z coordinate
  4528. * @param w defines the w coordinate
  4529. * @returns the updated current quaternion
  4530. */
  4531. Quaternion.prototype.set = function (x, y, z, w) {
  4532. return this.copyFromFloats(x, y, z, w);
  4533. };
  4534. /**
  4535. * Adds two quaternions
  4536. * @param other defines the second operand
  4537. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4538. */
  4539. Quaternion.prototype.add = function (other) {
  4540. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4541. };
  4542. /**
  4543. * Add a quaternion to the current one
  4544. * @param other defines the quaternion to add
  4545. * @returns the current quaternion
  4546. */
  4547. Quaternion.prototype.addInPlace = function (other) {
  4548. this.x += other.x;
  4549. this.y += other.y;
  4550. this.z += other.z;
  4551. this.w += other.w;
  4552. return this;
  4553. };
  4554. /**
  4555. * Subtract two quaternions
  4556. * @param other defines the second operand
  4557. * @returns a new quaternion as the subtraction result of the given one from the current one
  4558. */
  4559. Quaternion.prototype.subtract = function (other) {
  4560. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4561. };
  4562. /**
  4563. * Multiplies the current quaternion by a scale factor
  4564. * @param value defines the scale factor
  4565. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4566. */
  4567. Quaternion.prototype.scale = function (value) {
  4568. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4569. };
  4570. /**
  4571. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4572. * @param scale defines the scale factor
  4573. * @param result defines the Quaternion object where to store the result
  4574. * @returns the unmodified current quaternion
  4575. */
  4576. Quaternion.prototype.scaleToRef = function (scale, result) {
  4577. result.x = this.x * scale;
  4578. result.y = this.y * scale;
  4579. result.z = this.z * scale;
  4580. result.w = this.w * scale;
  4581. return this;
  4582. };
  4583. /**
  4584. * Multiplies in place the current quaternion by a scale factor
  4585. * @param value defines the scale factor
  4586. * @returns the current modified quaternion
  4587. */
  4588. Quaternion.prototype.scaleInPlace = function (value) {
  4589. this.x *= value;
  4590. this.y *= value;
  4591. this.z *= value;
  4592. this.w *= value;
  4593. return this;
  4594. };
  4595. /**
  4596. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4597. * @param scale defines the scale factor
  4598. * @param result defines the Quaternion object where to store the result
  4599. * @returns the unmodified current quaternion
  4600. */
  4601. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4602. result.x += this.x * scale;
  4603. result.y += this.y * scale;
  4604. result.z += this.z * scale;
  4605. result.w += this.w * scale;
  4606. return this;
  4607. };
  4608. /**
  4609. * Multiplies two quaternions
  4610. * @param q1 defines the second operand
  4611. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4612. */
  4613. Quaternion.prototype.multiply = function (q1) {
  4614. var result = new Quaternion(0, 0, 0, 1.0);
  4615. this.multiplyToRef(q1, result);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4620. * @param q1 defines the second operand
  4621. * @param result defines the target quaternion
  4622. * @returns the current quaternion
  4623. */
  4624. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4625. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4626. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4627. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4628. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4629. result.copyFromFloats(x, y, z, w);
  4630. return this;
  4631. };
  4632. /**
  4633. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4634. * @param q1 defines the second operand
  4635. * @returns the currentupdated quaternion
  4636. */
  4637. Quaternion.prototype.multiplyInPlace = function (q1) {
  4638. this.multiplyToRef(q1, this);
  4639. return this;
  4640. };
  4641. /**
  4642. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4643. * @param ref defines the target quaternion
  4644. * @returns the current quaternion
  4645. */
  4646. Quaternion.prototype.conjugateToRef = function (ref) {
  4647. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4648. return this;
  4649. };
  4650. /**
  4651. * Conjugates in place (1-q) the current quaternion
  4652. * @returns the current updated quaternion
  4653. */
  4654. Quaternion.prototype.conjugateInPlace = function () {
  4655. this.x *= -1;
  4656. this.y *= -1;
  4657. this.z *= -1;
  4658. return this;
  4659. };
  4660. /**
  4661. * Conjugates in place (1-q) the current quaternion
  4662. * @returns a new quaternion
  4663. */
  4664. Quaternion.prototype.conjugate = function () {
  4665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4666. return result;
  4667. };
  4668. /**
  4669. * Gets length of current quaternion
  4670. * @returns the quaternion length (float)
  4671. */
  4672. Quaternion.prototype.length = function () {
  4673. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4674. };
  4675. /**
  4676. * Normalize in place the current quaternion
  4677. * @returns the current updated quaternion
  4678. */
  4679. Quaternion.prototype.normalize = function () {
  4680. var length = 1.0 / this.length();
  4681. this.x *= length;
  4682. this.y *= length;
  4683. this.z *= length;
  4684. this.w *= length;
  4685. return this;
  4686. };
  4687. /**
  4688. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4689. * @param order is a reserved parameter and is ignore for now
  4690. * @returns a new Vector3 containing the Euler angles
  4691. */
  4692. Quaternion.prototype.toEulerAngles = function (order) {
  4693. if (order === void 0) { order = "YZX"; }
  4694. var result = Vector3.Zero();
  4695. this.toEulerAnglesToRef(result, order);
  4696. return result;
  4697. };
  4698. /**
  4699. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4700. * @param result defines the vector which will be filled with the Euler angles
  4701. * @param order is a reserved parameter and is ignore for now
  4702. * @returns the current unchanged quaternion
  4703. */
  4704. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4705. if (order === void 0) { order = "YZX"; }
  4706. var qz = this.z;
  4707. var qx = this.x;
  4708. var qy = this.y;
  4709. var qw = this.w;
  4710. var sqw = qw * qw;
  4711. var sqz = qz * qz;
  4712. var sqx = qx * qx;
  4713. var sqy = qy * qy;
  4714. var zAxisY = qy * qz - qx * qw;
  4715. var limit = .4999999;
  4716. if (zAxisY < -limit) {
  4717. result.y = 2 * Math.atan2(qy, qw);
  4718. result.x = Math.PI / 2;
  4719. result.z = 0;
  4720. }
  4721. else if (zAxisY > limit) {
  4722. result.y = 2 * Math.atan2(qy, qw);
  4723. result.x = -Math.PI / 2;
  4724. result.z = 0;
  4725. }
  4726. else {
  4727. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4728. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4729. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4730. }
  4731. return this;
  4732. };
  4733. /**
  4734. * Updates the given rotation matrix with the current quaternion values
  4735. * @param result defines the target matrix
  4736. * @returns the current unchanged quaternion
  4737. */
  4738. Quaternion.prototype.toRotationMatrix = function (result) {
  4739. var xx = this.x * this.x;
  4740. var yy = this.y * this.y;
  4741. var zz = this.z * this.z;
  4742. var xy = this.x * this.y;
  4743. var zw = this.z * this.w;
  4744. var zx = this.z * this.x;
  4745. var yw = this.y * this.w;
  4746. var yz = this.y * this.z;
  4747. var xw = this.x * this.w;
  4748. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4749. result.m[1] = 2.0 * (xy + zw);
  4750. result.m[2] = 2.0 * (zx - yw);
  4751. result.m[3] = 0;
  4752. result.m[4] = 2.0 * (xy - zw);
  4753. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4754. result.m[6] = 2.0 * (yz + xw);
  4755. result.m[7] = 0;
  4756. result.m[8] = 2.0 * (zx + yw);
  4757. result.m[9] = 2.0 * (yz - xw);
  4758. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4759. result.m[11] = 0;
  4760. result.m[12] = 0;
  4761. result.m[13] = 0;
  4762. result.m[14] = 0;
  4763. result.m[15] = 1.0;
  4764. result._markAsUpdated();
  4765. return this;
  4766. };
  4767. /**
  4768. * Updates the current quaternion from the given rotation matrix values
  4769. * @param matrix defines the source matrix
  4770. * @returns the current updated quaternion
  4771. */
  4772. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4773. Quaternion.FromRotationMatrixToRef(matrix, this);
  4774. return this;
  4775. };
  4776. // Statics
  4777. /**
  4778. * Creates a new quaternion from a rotation matrix
  4779. * @param matrix defines the source matrix
  4780. * @returns a new quaternion created from the given rotation matrix values
  4781. */
  4782. Quaternion.FromRotationMatrix = function (matrix) {
  4783. var result = new Quaternion();
  4784. Quaternion.FromRotationMatrixToRef(matrix, result);
  4785. return result;
  4786. };
  4787. /**
  4788. * Updates the given quaternion with the given rotation matrix values
  4789. * @param matrix defines the source matrix
  4790. * @param result defines the target quaternion
  4791. */
  4792. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4793. var data = matrix.m;
  4794. var m11 = data[0], m12 = data[4], m13 = data[8];
  4795. var m21 = data[1], m22 = data[5], m23 = data[9];
  4796. var m31 = data[2], m32 = data[6], m33 = data[10];
  4797. var trace = m11 + m22 + m33;
  4798. var s;
  4799. if (trace > 0) {
  4800. s = 0.5 / Math.sqrt(trace + 1.0);
  4801. result.w = 0.25 / s;
  4802. result.x = (m32 - m23) * s;
  4803. result.y = (m13 - m31) * s;
  4804. result.z = (m21 - m12) * s;
  4805. }
  4806. else if (m11 > m22 && m11 > m33) {
  4807. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4808. result.w = (m32 - m23) / s;
  4809. result.x = 0.25 * s;
  4810. result.y = (m12 + m21) / s;
  4811. result.z = (m13 + m31) / s;
  4812. }
  4813. else if (m22 > m33) {
  4814. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4815. result.w = (m13 - m31) / s;
  4816. result.x = (m12 + m21) / s;
  4817. result.y = 0.25 * s;
  4818. result.z = (m23 + m32) / s;
  4819. }
  4820. else {
  4821. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4822. result.w = (m21 - m12) / s;
  4823. result.x = (m13 + m31) / s;
  4824. result.y = (m23 + m32) / s;
  4825. result.z = 0.25 * s;
  4826. }
  4827. };
  4828. /**
  4829. * Returns the dot product (float) between the quaternions "left" and "right"
  4830. * @param left defines the left operand
  4831. * @param right defines the right operand
  4832. * @returns the dot product
  4833. */
  4834. Quaternion.Dot = function (left, right) {
  4835. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4836. };
  4837. /**
  4838. * Checks if the two quaternions are close to each other
  4839. * @param quat0 defines the first quaternion to check
  4840. * @param quat1 defines the second quaternion to check
  4841. * @returns true if the two quaternions are close to each other
  4842. */
  4843. Quaternion.AreClose = function (quat0, quat1) {
  4844. var dot = Quaternion.Dot(quat0, quat1);
  4845. return dot >= 0;
  4846. };
  4847. /**
  4848. * Creates an empty quaternion
  4849. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4850. */
  4851. Quaternion.Zero = function () {
  4852. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4853. };
  4854. /**
  4855. * Inverse a given quaternion
  4856. * @param q defines the source quaternion
  4857. * @returns a new quaternion as the inverted current quaternion
  4858. */
  4859. Quaternion.Inverse = function (q) {
  4860. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4861. };
  4862. /**
  4863. * Creates an identity quaternion
  4864. * @returns the identity quaternion
  4865. */
  4866. Quaternion.Identity = function () {
  4867. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4868. };
  4869. /**
  4870. * Gets a boolean indicating if the given quaternion is identity
  4871. * @param quaternion defines the quaternion to check
  4872. * @returns true if the quaternion is identity
  4873. */
  4874. Quaternion.IsIdentity = function (quaternion) {
  4875. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4876. };
  4877. /**
  4878. * Creates a quaternion from a rotation around an axis
  4879. * @param axis defines the axis to use
  4880. * @param angle defines the angle to use
  4881. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4882. */
  4883. Quaternion.RotationAxis = function (axis, angle) {
  4884. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4885. };
  4886. /**
  4887. * Creates a rotation around an axis and stores it into the given quaternion
  4888. * @param axis defines the axis to use
  4889. * @param angle defines the angle to use
  4890. * @param result defines the target quaternion
  4891. * @returns the target quaternion
  4892. */
  4893. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4894. var sin = Math.sin(angle / 2);
  4895. axis.normalize();
  4896. result.w = Math.cos(angle / 2);
  4897. result.x = axis.x * sin;
  4898. result.y = axis.y * sin;
  4899. result.z = axis.z * sin;
  4900. return result;
  4901. };
  4902. /**
  4903. * Creates a new quaternion from data stored into an array
  4904. * @param array defines the data source
  4905. * @param offset defines the offset in the source array where the data starts
  4906. * @returns a new quaternion
  4907. */
  4908. Quaternion.FromArray = function (array, offset) {
  4909. if (!offset) {
  4910. offset = 0;
  4911. }
  4912. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4913. };
  4914. /**
  4915. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4916. * @param yaw defines the rotation around Y axis
  4917. * @param pitch defines the rotation around X axis
  4918. * @param roll defines the rotation around Z axis
  4919. * @returns the new quaternion
  4920. */
  4921. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4922. var q = new Quaternion();
  4923. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4924. return q;
  4925. };
  4926. /**
  4927. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4928. * @param yaw defines the rotation around Y axis
  4929. * @param pitch defines the rotation around X axis
  4930. * @param roll defines the rotation around Z axis
  4931. * @param result defines the target quaternion
  4932. */
  4933. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4934. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4935. var halfRoll = roll * 0.5;
  4936. var halfPitch = pitch * 0.5;
  4937. var halfYaw = yaw * 0.5;
  4938. var sinRoll = Math.sin(halfRoll);
  4939. var cosRoll = Math.cos(halfRoll);
  4940. var sinPitch = Math.sin(halfPitch);
  4941. var cosPitch = Math.cos(halfPitch);
  4942. var sinYaw = Math.sin(halfYaw);
  4943. var cosYaw = Math.cos(halfYaw);
  4944. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4945. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4946. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4947. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4948. };
  4949. /**
  4950. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4951. * @param alpha defines the rotation around first axis
  4952. * @param beta defines the rotation around second axis
  4953. * @param gamma defines the rotation around third axis
  4954. * @returns the new quaternion
  4955. */
  4956. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4957. var result = new Quaternion();
  4958. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4959. return result;
  4960. };
  4961. /**
  4962. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4963. * @param alpha defines the rotation around first axis
  4964. * @param beta defines the rotation around second axis
  4965. * @param gamma defines the rotation around third axis
  4966. * @param result defines the target quaternion
  4967. */
  4968. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4969. // Produces a quaternion from Euler angles in the z-x-z orientation
  4970. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4971. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4972. var halfBeta = beta * 0.5;
  4973. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4974. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4975. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4976. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4977. };
  4978. /**
  4979. * 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)
  4980. * @param axis1 defines the first axis
  4981. * @param axis2 defines the second axis
  4982. * @param axis3 defines the third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4986. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4987. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4988. return quat;
  4989. };
  4990. /**
  4991. * 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
  4992. * @param axis1 defines the first axis
  4993. * @param axis2 defines the second axis
  4994. * @param axis3 defines the third axis
  4995. * @param ref defines the target quaternion
  4996. */
  4997. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4998. var rotMat = MathTmp.Matrix[0];
  4999. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5000. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5001. };
  5002. /**
  5003. * Interpolates between two quaternions
  5004. * @param left defines first quaternion
  5005. * @param right defines second quaternion
  5006. * @param amount defines the gradient to use
  5007. * @returns the new interpolated quaternion
  5008. */
  5009. Quaternion.Slerp = function (left, right, amount) {
  5010. var result = Quaternion.Identity();
  5011. Quaternion.SlerpToRef(left, right, amount, result);
  5012. return result;
  5013. };
  5014. /**
  5015. * Interpolates between two quaternions and stores it into a target quaternion
  5016. * @param left defines first quaternion
  5017. * @param right defines second quaternion
  5018. * @param amount defines the gradient to use
  5019. * @param result defines the target quaternion
  5020. */
  5021. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5022. var num2;
  5023. var num3;
  5024. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5025. var flag = false;
  5026. if (num4 < 0) {
  5027. flag = true;
  5028. num4 = -num4;
  5029. }
  5030. if (num4 > 0.999999) {
  5031. num3 = 1 - amount;
  5032. num2 = flag ? -amount : amount;
  5033. }
  5034. else {
  5035. var num5 = Math.acos(num4);
  5036. var num6 = (1.0 / Math.sin(num5));
  5037. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5038. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5039. }
  5040. result.x = (num3 * left.x) + (num2 * right.x);
  5041. result.y = (num3 * left.y) + (num2 * right.y);
  5042. result.z = (num3 * left.z) + (num2 * right.z);
  5043. result.w = (num3 * left.w) + (num2 * right.w);
  5044. };
  5045. /**
  5046. * Interpolate between two quaternions using Hermite interpolation
  5047. * @param value1 defines first quaternion
  5048. * @param tangent1 defines the incoming tangent
  5049. * @param value2 defines second quaternion
  5050. * @param tangent2 defines the outgoing tangent
  5051. * @param amount defines the target quaternion
  5052. * @returns the new interpolated quaternion
  5053. */
  5054. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5055. var squared = amount * amount;
  5056. var cubed = amount * squared;
  5057. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5058. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5059. var part3 = (cubed - (2.0 * squared)) + amount;
  5060. var part4 = cubed - squared;
  5061. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5062. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5063. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5064. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5065. return new Quaternion(x, y, z, w);
  5066. };
  5067. return Quaternion;
  5068. }());
  5069. BABYLON.Quaternion = Quaternion;
  5070. /**
  5071. * Class used to store matrix data (4x4)
  5072. */
  5073. var Matrix = /** @class */ (function () {
  5074. /**
  5075. * Creates an empty matrix (filled with zeros)
  5076. */
  5077. function Matrix() {
  5078. this._isIdentity = false;
  5079. this._isIdentityDirty = true;
  5080. /**
  5081. * Gets or sets the internal data of the matrix
  5082. */
  5083. this.m = new Float32Array(16);
  5084. this._markAsUpdated();
  5085. }
  5086. /** @hidden */
  5087. Matrix.prototype._markAsUpdated = function () {
  5088. this.updateFlag = Matrix._updateFlagSeed++;
  5089. this._isIdentityDirty = true;
  5090. };
  5091. // Properties
  5092. /**
  5093. * Check if the current matrix is indentity
  5094. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5095. * @returns true is the matrix is the identity matrix
  5096. */
  5097. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5098. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5099. if (this._isIdentityDirty) {
  5100. this._isIdentityDirty = false;
  5101. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5102. this._isIdentity = false;
  5103. }
  5104. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5105. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5106. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5107. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5108. this._isIdentity = false;
  5109. }
  5110. else {
  5111. this._isIdentity = true;
  5112. }
  5113. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5114. this._isIdentity = false;
  5115. }
  5116. }
  5117. return this._isIdentity;
  5118. };
  5119. /**
  5120. * Gets the determinant of the matrix
  5121. * @returns the matrix determinant
  5122. */
  5123. Matrix.prototype.determinant = function () {
  5124. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5125. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5126. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5127. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5128. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5129. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5130. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5131. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5132. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5133. };
  5134. // Methods
  5135. /**
  5136. * Returns the matrix as a Float32Array
  5137. * @returns the matrix underlying array
  5138. */
  5139. Matrix.prototype.toArray = function () {
  5140. return this.m;
  5141. };
  5142. /**
  5143. * Returns the matrix as a Float32Array
  5144. * @returns the matrix underlying array.
  5145. */
  5146. Matrix.prototype.asArray = function () {
  5147. return this.toArray();
  5148. };
  5149. /**
  5150. * Inverts the current matrix in place
  5151. * @returns the current inverted matrix
  5152. */
  5153. Matrix.prototype.invert = function () {
  5154. this.invertToRef(this);
  5155. return this;
  5156. };
  5157. /**
  5158. * Sets all the matrix elements to zero
  5159. * @returns the current matrix
  5160. */
  5161. Matrix.prototype.reset = function () {
  5162. for (var index = 0; index < 16; index++) {
  5163. this.m[index] = 0.0;
  5164. }
  5165. this._markAsUpdated();
  5166. return this;
  5167. };
  5168. /**
  5169. * Adds the current matrix with a second one
  5170. * @param other defines the matrix to add
  5171. * @returns a new matrix as the addition of the current matrix and the given one
  5172. */
  5173. Matrix.prototype.add = function (other) {
  5174. var result = new Matrix();
  5175. this.addToRef(other, result);
  5176. return result;
  5177. };
  5178. /**
  5179. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5180. * @param other defines the matrix to add
  5181. * @param result defines the target matrix
  5182. * @returns the current matrix
  5183. */
  5184. Matrix.prototype.addToRef = function (other, result) {
  5185. for (var index = 0; index < 16; index++) {
  5186. result.m[index] = this.m[index] + other.m[index];
  5187. }
  5188. result._markAsUpdated();
  5189. return this;
  5190. };
  5191. /**
  5192. * Adds in place the given matrix to the current matrix
  5193. * @param other defines the second operand
  5194. * @returns the current updated matrix
  5195. */
  5196. Matrix.prototype.addToSelf = function (other) {
  5197. for (var index = 0; index < 16; index++) {
  5198. this.m[index] += other.m[index];
  5199. }
  5200. this._markAsUpdated();
  5201. return this;
  5202. };
  5203. /**
  5204. * Sets the given matrix to the current inverted Matrix
  5205. * @param other defines the target matrix
  5206. * @returns the unmodified current matrix
  5207. */
  5208. Matrix.prototype.invertToRef = function (other) {
  5209. var l1 = this.m[0];
  5210. var l2 = this.m[1];
  5211. var l3 = this.m[2];
  5212. var l4 = this.m[3];
  5213. var l5 = this.m[4];
  5214. var l6 = this.m[5];
  5215. var l7 = this.m[6];
  5216. var l8 = this.m[7];
  5217. var l9 = this.m[8];
  5218. var l10 = this.m[9];
  5219. var l11 = this.m[10];
  5220. var l12 = this.m[11];
  5221. var l13 = this.m[12];
  5222. var l14 = this.m[13];
  5223. var l15 = this.m[14];
  5224. var l16 = this.m[15];
  5225. var l17 = (l11 * l16) - (l12 * l15);
  5226. var l18 = (l10 * l16) - (l12 * l14);
  5227. var l19 = (l10 * l15) - (l11 * l14);
  5228. var l20 = (l9 * l16) - (l12 * l13);
  5229. var l21 = (l9 * l15) - (l11 * l13);
  5230. var l22 = (l9 * l14) - (l10 * l13);
  5231. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5232. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5233. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5234. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5235. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5236. var l28 = (l7 * l16) - (l8 * l15);
  5237. var l29 = (l6 * l16) - (l8 * l14);
  5238. var l30 = (l6 * l15) - (l7 * l14);
  5239. var l31 = (l5 * l16) - (l8 * l13);
  5240. var l32 = (l5 * l15) - (l7 * l13);
  5241. var l33 = (l5 * l14) - (l6 * l13);
  5242. var l34 = (l7 * l12) - (l8 * l11);
  5243. var l35 = (l6 * l12) - (l8 * l10);
  5244. var l36 = (l6 * l11) - (l7 * l10);
  5245. var l37 = (l5 * l12) - (l8 * l9);
  5246. var l38 = (l5 * l11) - (l7 * l9);
  5247. var l39 = (l5 * l10) - (l6 * l9);
  5248. other.m[0] = l23 * l27;
  5249. other.m[4] = l24 * l27;
  5250. other.m[8] = l25 * l27;
  5251. other.m[12] = l26 * l27;
  5252. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5253. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5254. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5255. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5256. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5257. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5258. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5259. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5260. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5261. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5262. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5263. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5264. other._markAsUpdated();
  5265. return this;
  5266. };
  5267. /**
  5268. * Inserts the translation vector (using 3 floats) in the current matrix
  5269. * @param x defines the 1st component of the translation
  5270. * @param y defines the 2nd component of the translation
  5271. * @param z defines the 3rd component of the translation
  5272. * @returns the current updated matrix
  5273. */
  5274. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5275. this.m[12] = x;
  5276. this.m[13] = y;
  5277. this.m[14] = z;
  5278. this._markAsUpdated();
  5279. return this;
  5280. };
  5281. /**
  5282. * Inserts the translation vector in the current matrix
  5283. * @param vector3 defines the translation to insert
  5284. * @returns the current updated matrix
  5285. */
  5286. Matrix.prototype.setTranslation = function (vector3) {
  5287. this.m[12] = vector3.x;
  5288. this.m[13] = vector3.y;
  5289. this.m[14] = vector3.z;
  5290. this._markAsUpdated();
  5291. return this;
  5292. };
  5293. /**
  5294. * Gets the translation value of the current matrix
  5295. * @returns a new Vector3 as the extracted translation from the matrix
  5296. */
  5297. Matrix.prototype.getTranslation = function () {
  5298. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5299. };
  5300. /**
  5301. * Fill a Vector3 with the extracted translation from the matrix
  5302. * @param result defines the Vector3 where to store the translation
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.getTranslationToRef = function (result) {
  5306. result.x = this.m[12];
  5307. result.y = this.m[13];
  5308. result.z = this.m[14];
  5309. return this;
  5310. };
  5311. /**
  5312. * Remove rotation and scaling part from the matrix
  5313. * @returns the updated matrix
  5314. */
  5315. Matrix.prototype.removeRotationAndScaling = function () {
  5316. this.setRowFromFloats(0, 1, 0, 0, 0);
  5317. this.setRowFromFloats(1, 0, 1, 0, 0);
  5318. this.setRowFromFloats(2, 0, 0, 1, 0);
  5319. return this;
  5320. };
  5321. /**
  5322. * Multiply two matrices
  5323. * @param other defines the second operand
  5324. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5325. */
  5326. Matrix.prototype.multiply = function (other) {
  5327. var result = new Matrix();
  5328. this.multiplyToRef(other, result);
  5329. return result;
  5330. };
  5331. /**
  5332. * Copy the current matrix from the given one
  5333. * @param other defines the source matrix
  5334. * @returns the current updated matrix
  5335. */
  5336. Matrix.prototype.copyFrom = function (other) {
  5337. for (var index = 0; index < 16; index++) {
  5338. this.m[index] = other.m[index];
  5339. }
  5340. this._markAsUpdated();
  5341. return this;
  5342. };
  5343. /**
  5344. * Populates the given array from the starting index with the current matrix values
  5345. * @param array defines the target array
  5346. * @param offset defines the offset in the target array where to start storing values
  5347. * @returns the current matrix
  5348. */
  5349. Matrix.prototype.copyToArray = function (array, offset) {
  5350. if (offset === void 0) { offset = 0; }
  5351. for (var index = 0; index < 16; index++) {
  5352. array[offset + index] = this.m[index];
  5353. }
  5354. return this;
  5355. };
  5356. /**
  5357. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5358. * @param other defines the second operand
  5359. * @param result defines the matrix where to store the multiplication
  5360. * @returns the current matrix
  5361. */
  5362. Matrix.prototype.multiplyToRef = function (other, result) {
  5363. this.multiplyToArray(other, result.m, 0);
  5364. result._markAsUpdated();
  5365. return this;
  5366. };
  5367. /**
  5368. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5369. * @param other defines the second operand
  5370. * @param result defines the array where to store the multiplication
  5371. * @param offset defines the offset in the target array where to start storing values
  5372. * @returns the current matrix
  5373. */
  5374. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5375. var tm0 = this.m[0];
  5376. var tm1 = this.m[1];
  5377. var tm2 = this.m[2];
  5378. var tm3 = this.m[3];
  5379. var tm4 = this.m[4];
  5380. var tm5 = this.m[5];
  5381. var tm6 = this.m[6];
  5382. var tm7 = this.m[7];
  5383. var tm8 = this.m[8];
  5384. var tm9 = this.m[9];
  5385. var tm10 = this.m[10];
  5386. var tm11 = this.m[11];
  5387. var tm12 = this.m[12];
  5388. var tm13 = this.m[13];
  5389. var tm14 = this.m[14];
  5390. var tm15 = this.m[15];
  5391. var om0 = other.m[0];
  5392. var om1 = other.m[1];
  5393. var om2 = other.m[2];
  5394. var om3 = other.m[3];
  5395. var om4 = other.m[4];
  5396. var om5 = other.m[5];
  5397. var om6 = other.m[6];
  5398. var om7 = other.m[7];
  5399. var om8 = other.m[8];
  5400. var om9 = other.m[9];
  5401. var om10 = other.m[10];
  5402. var om11 = other.m[11];
  5403. var om12 = other.m[12];
  5404. var om13 = other.m[13];
  5405. var om14 = other.m[14];
  5406. var om15 = other.m[15];
  5407. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5408. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5409. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5410. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5411. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5412. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5413. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5414. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5415. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5416. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5417. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5418. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5419. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5420. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5421. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5422. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5423. return this;
  5424. };
  5425. /**
  5426. * Check equality between this matrix and a second one
  5427. * @param value defines the second matrix to compare
  5428. * @returns true is the current matrix and the given one values are strictly equal
  5429. */
  5430. Matrix.prototype.equals = function (value) {
  5431. return value &&
  5432. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5433. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5434. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5435. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5436. };
  5437. /**
  5438. * Clone the current matrix
  5439. * @returns a new matrix from the current matrix
  5440. */
  5441. Matrix.prototype.clone = function () {
  5442. 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]);
  5443. };
  5444. /**
  5445. * Returns the name of the current matrix class
  5446. * @returns the string "Matrix"
  5447. */
  5448. Matrix.prototype.getClassName = function () {
  5449. return "Matrix";
  5450. };
  5451. /**
  5452. * Gets the hash code of the current matrix
  5453. * @returns the hash code
  5454. */
  5455. Matrix.prototype.getHashCode = function () {
  5456. var hash = this.m[0] || 0;
  5457. for (var i = 1; i < 16; i++) {
  5458. hash = (hash * 397) ^ (this.m[i] || 0);
  5459. }
  5460. return hash;
  5461. };
  5462. /**
  5463. * Decomposes the current Matrix into a translation, rotation and scaling components
  5464. * @param scale defines the scale vector3 given as a reference to update
  5465. * @param rotation defines the rotation quaternion given as a reference to update
  5466. * @param translation defines the translation vector3 given as a reference to update
  5467. * @returns true if operation was successful
  5468. */
  5469. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5470. if (translation) {
  5471. translation.x = this.m[12];
  5472. translation.y = this.m[13];
  5473. translation.z = this.m[14];
  5474. }
  5475. scale = scale || MathTmp.Vector3[0];
  5476. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5477. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5478. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5479. if (this.determinant() <= 0) {
  5480. scale.y *= -1;
  5481. }
  5482. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5483. if (rotation) {
  5484. rotation.x = 0;
  5485. rotation.y = 0;
  5486. rotation.z = 0;
  5487. rotation.w = 1;
  5488. }
  5489. return false;
  5490. }
  5491. if (rotation) {
  5492. 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]);
  5493. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5494. }
  5495. return true;
  5496. };
  5497. /**
  5498. * Gets specific row of the matrix
  5499. * @param index defines the number of the row to get
  5500. * @returns the index-th row of the current matrix as a new Vector4
  5501. */
  5502. Matrix.prototype.getRow = function (index) {
  5503. if (index < 0 || index > 3) {
  5504. return null;
  5505. }
  5506. var i = index * 4;
  5507. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5508. };
  5509. /**
  5510. * Sets the index-th row of the current matrix to the vector4 values
  5511. * @param index defines the number of the row to set
  5512. * @param row defines the target vector4
  5513. * @returns the updated current matrix
  5514. */
  5515. Matrix.prototype.setRow = function (index, row) {
  5516. if (index < 0 || index > 3) {
  5517. return this;
  5518. }
  5519. var i = index * 4;
  5520. this.m[i + 0] = row.x;
  5521. this.m[i + 1] = row.y;
  5522. this.m[i + 2] = row.z;
  5523. this.m[i + 3] = row.w;
  5524. this._markAsUpdated();
  5525. return this;
  5526. };
  5527. /**
  5528. * Compute the transpose of the matrix
  5529. * @returns the new transposed matrix
  5530. */
  5531. Matrix.prototype.transpose = function () {
  5532. return Matrix.Transpose(this);
  5533. };
  5534. /**
  5535. * Compute the transpose of the matrix and store it in a given matrix
  5536. * @param result defines the target matrix
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.transposeToRef = function (result) {
  5540. Matrix.TransposeToRef(this, result);
  5541. return this;
  5542. };
  5543. /**
  5544. * Sets the index-th row of the current matrix with the given 4 x float values
  5545. * @param index defines the row index
  5546. * @param x defines the x component to set
  5547. * @param y defines the y component to set
  5548. * @param z defines the z component to set
  5549. * @param w defines the w component to set
  5550. * @returns the updated current matrix
  5551. */
  5552. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5553. if (index < 0 || index > 3) {
  5554. return this;
  5555. }
  5556. var i = index * 4;
  5557. this.m[i + 0] = x;
  5558. this.m[i + 1] = y;
  5559. this.m[i + 2] = z;
  5560. this.m[i + 3] = w;
  5561. this._markAsUpdated();
  5562. return this;
  5563. };
  5564. /**
  5565. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5566. * @param scale defines the scale factor
  5567. * @returns a new matrix
  5568. */
  5569. Matrix.prototype.scale = function (scale) {
  5570. var result = new Matrix();
  5571. this.scaleToRef(scale, result);
  5572. return result;
  5573. };
  5574. /**
  5575. * Scale the current matrix values by a factor to a given result matrix
  5576. * @param scale defines the scale factor
  5577. * @param result defines the matrix to store the result
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.scaleToRef = function (scale, result) {
  5581. for (var index = 0; index < 16; index++) {
  5582. result.m[index] = this.m[index] * scale;
  5583. }
  5584. result._markAsUpdated();
  5585. return this;
  5586. };
  5587. /**
  5588. * Scale the current matrix values by a factor and add the result to a given matrix
  5589. * @param scale defines the scale factor
  5590. * @param result defines the Matrix to store the result
  5591. * @returns the current matrix
  5592. */
  5593. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] += this.m[index] * scale;
  5596. }
  5597. result._markAsUpdated();
  5598. return this;
  5599. };
  5600. /**
  5601. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5602. * @param ref matrix to store the result
  5603. */
  5604. Matrix.prototype.toNormalMatrix = function (ref) {
  5605. this.invertToRef(ref);
  5606. ref.transpose();
  5607. var m = ref.m;
  5608. 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);
  5609. };
  5610. /**
  5611. * Gets only rotation part of the current matrix
  5612. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5613. */
  5614. Matrix.prototype.getRotationMatrix = function () {
  5615. var result = Matrix.Identity();
  5616. this.getRotationMatrixToRef(result);
  5617. return result;
  5618. };
  5619. /**
  5620. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5621. * @param result defines the target matrix to store data to
  5622. * @returns the current matrix
  5623. */
  5624. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5625. var m = this.m;
  5626. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5627. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5628. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5629. if (this.determinant() <= 0) {
  5630. sy *= -1;
  5631. }
  5632. if (sx === 0 || sy === 0 || sz === 0) {
  5633. Matrix.IdentityToRef(result);
  5634. }
  5635. else {
  5636. 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);
  5637. }
  5638. return this;
  5639. };
  5640. // Statics
  5641. /**
  5642. * Creates a matrix from an array
  5643. * @param array defines the source array
  5644. * @param offset defines an offset in the source array
  5645. * @returns a new Matrix set from the starting index of the given array
  5646. */
  5647. Matrix.FromArray = function (array, offset) {
  5648. var result = new Matrix();
  5649. if (!offset) {
  5650. offset = 0;
  5651. }
  5652. Matrix.FromArrayToRef(array, offset, result);
  5653. return result;
  5654. };
  5655. /**
  5656. * Copy the content of an array into a given matrix
  5657. * @param array defines the source array
  5658. * @param offset defines an offset in the source array
  5659. * @param result defines the target matrix
  5660. */
  5661. Matrix.FromArrayToRef = function (array, offset, result) {
  5662. for (var index = 0; index < 16; index++) {
  5663. result.m[index] = array[index + offset];
  5664. }
  5665. result._markAsUpdated();
  5666. };
  5667. /**
  5668. * Stores an array into a matrix after having multiplied each component by a given factor
  5669. * @param array defines the source array
  5670. * @param offset defines the offset in the source array
  5671. * @param scale defines the scaling factor
  5672. * @param result defines the target matrix
  5673. */
  5674. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5675. for (var index = 0; index < 16; index++) {
  5676. result.m[index] = array[index + offset] * scale;
  5677. }
  5678. result._markAsUpdated();
  5679. };
  5680. /**
  5681. * Stores a list of values (16) inside a given matrix
  5682. * @param initialM11 defines 1st value of 1st row
  5683. * @param initialM12 defines 2nd value of 1st row
  5684. * @param initialM13 defines 3rd value of 1st row
  5685. * @param initialM14 defines 4th value of 1st row
  5686. * @param initialM21 defines 1st value of 2nd row
  5687. * @param initialM22 defines 2nd value of 2nd row
  5688. * @param initialM23 defines 3rd value of 2nd row
  5689. * @param initialM24 defines 4th value of 2nd row
  5690. * @param initialM31 defines 1st value of 3rd row
  5691. * @param initialM32 defines 2nd value of 3rd row
  5692. * @param initialM33 defines 3rd value of 3rd row
  5693. * @param initialM34 defines 4th value of 3rd row
  5694. * @param initialM41 defines 1st value of 4th row
  5695. * @param initialM42 defines 2nd value of 4th row
  5696. * @param initialM43 defines 3rd value of 4th row
  5697. * @param initialM44 defines 4th value of 4th row
  5698. * @param result defines the target matrix
  5699. */
  5700. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5701. result.m[0] = initialM11;
  5702. result.m[1] = initialM12;
  5703. result.m[2] = initialM13;
  5704. result.m[3] = initialM14;
  5705. result.m[4] = initialM21;
  5706. result.m[5] = initialM22;
  5707. result.m[6] = initialM23;
  5708. result.m[7] = initialM24;
  5709. result.m[8] = initialM31;
  5710. result.m[9] = initialM32;
  5711. result.m[10] = initialM33;
  5712. result.m[11] = initialM34;
  5713. result.m[12] = initialM41;
  5714. result.m[13] = initialM42;
  5715. result.m[14] = initialM43;
  5716. result.m[15] = initialM44;
  5717. result._markAsUpdated();
  5718. };
  5719. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5720. /**
  5721. * Gets an identity matrix that must not be updated
  5722. */
  5723. get: function () {
  5724. return Matrix._identityReadOnly;
  5725. },
  5726. enumerable: true,
  5727. configurable: true
  5728. });
  5729. /**
  5730. * Creates new matrix from a list of values (16)
  5731. * @param initialM11 defines 1st value of 1st row
  5732. * @param initialM12 defines 2nd value of 1st row
  5733. * @param initialM13 defines 3rd value of 1st row
  5734. * @param initialM14 defines 4th value of 1st row
  5735. * @param initialM21 defines 1st value of 2nd row
  5736. * @param initialM22 defines 2nd value of 2nd row
  5737. * @param initialM23 defines 3rd value of 2nd row
  5738. * @param initialM24 defines 4th value of 2nd row
  5739. * @param initialM31 defines 1st value of 3rd row
  5740. * @param initialM32 defines 2nd value of 3rd row
  5741. * @param initialM33 defines 3rd value of 3rd row
  5742. * @param initialM34 defines 4th value of 3rd row
  5743. * @param initialM41 defines 1st value of 4th row
  5744. * @param initialM42 defines 2nd value of 4th row
  5745. * @param initialM43 defines 3rd value of 4th row
  5746. * @param initialM44 defines 4th value of 4th row
  5747. * @returns the new matrix
  5748. */
  5749. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5750. var result = new Matrix();
  5751. result.m[0] = initialM11;
  5752. result.m[1] = initialM12;
  5753. result.m[2] = initialM13;
  5754. result.m[3] = initialM14;
  5755. result.m[4] = initialM21;
  5756. result.m[5] = initialM22;
  5757. result.m[6] = initialM23;
  5758. result.m[7] = initialM24;
  5759. result.m[8] = initialM31;
  5760. result.m[9] = initialM32;
  5761. result.m[10] = initialM33;
  5762. result.m[11] = initialM34;
  5763. result.m[12] = initialM41;
  5764. result.m[13] = initialM42;
  5765. result.m[14] = initialM43;
  5766. result.m[15] = initialM44;
  5767. return result;
  5768. };
  5769. /**
  5770. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5771. * @param scale defines the scale vector3
  5772. * @param rotation defines the rotation quaternion
  5773. * @param translation defines the translation vector3
  5774. * @returns a new matrix
  5775. */
  5776. Matrix.Compose = function (scale, rotation, translation) {
  5777. var result = Matrix.Identity();
  5778. Matrix.ComposeToRef(scale, rotation, translation, result);
  5779. return result;
  5780. };
  5781. /**
  5782. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5783. * @param scale defines the scale vector3
  5784. * @param rotation defines the rotation quaternion
  5785. * @param translation defines the translation vector3
  5786. * @param result defines the target matrix
  5787. */
  5788. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5789. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5790. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5791. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5792. result.setTranslation(translation);
  5793. };
  5794. /**
  5795. * Creates a new identity matrix
  5796. * @returns a new identity matrix
  5797. */
  5798. Matrix.Identity = function () {
  5799. 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);
  5800. };
  5801. /**
  5802. * Creates a new identity matrix and stores the result in a given matrix
  5803. * @param result defines the target matrix
  5804. */
  5805. Matrix.IdentityToRef = function (result) {
  5806. 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);
  5807. };
  5808. /**
  5809. * Creates a new zero matrix
  5810. * @returns a new zero matrix
  5811. */
  5812. Matrix.Zero = function () {
  5813. 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);
  5814. };
  5815. /**
  5816. * Creates a new rotation matrix for "angle" radians around the X axis
  5817. * @param angle defines the angle (in radians) to use
  5818. * @return the new matrix
  5819. */
  5820. Matrix.RotationX = function (angle) {
  5821. var result = new Matrix();
  5822. Matrix.RotationXToRef(angle, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Creates a new matrix as the invert of a given matrix
  5827. * @param source defines the source matrix
  5828. * @returns the new matrix
  5829. */
  5830. Matrix.Invert = function (source) {
  5831. var result = new Matrix();
  5832. source.invertToRef(result);
  5833. return result;
  5834. };
  5835. /**
  5836. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5837. * @param angle defines the angle (in radians) to use
  5838. * @param result defines the target matrix
  5839. */
  5840. Matrix.RotationXToRef = function (angle, result) {
  5841. var s = Math.sin(angle);
  5842. var c = Math.cos(angle);
  5843. result.m[0] = 1.0;
  5844. result.m[15] = 1.0;
  5845. result.m[5] = c;
  5846. result.m[10] = c;
  5847. result.m[9] = -s;
  5848. result.m[6] = s;
  5849. result.m[1] = 0.0;
  5850. result.m[2] = 0.0;
  5851. result.m[3] = 0.0;
  5852. result.m[4] = 0.0;
  5853. result.m[7] = 0.0;
  5854. result.m[8] = 0.0;
  5855. result.m[11] = 0.0;
  5856. result.m[12] = 0.0;
  5857. result.m[13] = 0.0;
  5858. result.m[14] = 0.0;
  5859. result._markAsUpdated();
  5860. };
  5861. /**
  5862. * Creates a new rotation matrix for "angle" radians around the Y axis
  5863. * @param angle defines the angle (in radians) to use
  5864. * @return the new matrix
  5865. */
  5866. Matrix.RotationY = function (angle) {
  5867. var result = new Matrix();
  5868. Matrix.RotationYToRef(angle, result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5873. * @param angle defines the angle (in radians) to use
  5874. * @param result defines the target matrix
  5875. */
  5876. Matrix.RotationYToRef = function (angle, result) {
  5877. var s = Math.sin(angle);
  5878. var c = Math.cos(angle);
  5879. result.m[5] = 1.0;
  5880. result.m[15] = 1.0;
  5881. result.m[0] = c;
  5882. result.m[2] = -s;
  5883. result.m[8] = s;
  5884. result.m[10] = c;
  5885. result.m[1] = 0.0;
  5886. result.m[3] = 0.0;
  5887. result.m[4] = 0.0;
  5888. result.m[6] = 0.0;
  5889. result.m[7] = 0.0;
  5890. result.m[9] = 0.0;
  5891. result.m[11] = 0.0;
  5892. result.m[12] = 0.0;
  5893. result.m[13] = 0.0;
  5894. result.m[14] = 0.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a new rotation matrix for "angle" radians around the Z axis
  5899. * @param angle defines the angle (in radians) to use
  5900. * @return the new matrix
  5901. */
  5902. Matrix.RotationZ = function (angle) {
  5903. var result = new Matrix();
  5904. Matrix.RotationZToRef(angle, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5909. * @param angle defines the angle (in radians) to use
  5910. * @param result defines the target matrix
  5911. */
  5912. Matrix.RotationZToRef = function (angle, result) {
  5913. var s = Math.sin(angle);
  5914. var c = Math.cos(angle);
  5915. result.m[10] = 1.0;
  5916. result.m[15] = 1.0;
  5917. result.m[0] = c;
  5918. result.m[1] = s;
  5919. result.m[4] = -s;
  5920. result.m[5] = c;
  5921. result.m[2] = 0.0;
  5922. result.m[3] = 0.0;
  5923. result.m[6] = 0.0;
  5924. result.m[7] = 0.0;
  5925. result.m[8] = 0.0;
  5926. result.m[9] = 0.0;
  5927. result.m[11] = 0.0;
  5928. result.m[12] = 0.0;
  5929. result.m[13] = 0.0;
  5930. result.m[14] = 0.0;
  5931. result._markAsUpdated();
  5932. };
  5933. /**
  5934. * Creates a new rotation matrix for "angle" radians around the given axis
  5935. * @param axis defines the axis to use
  5936. * @param angle defines the angle (in radians) to use
  5937. * @return the new matrix
  5938. */
  5939. Matrix.RotationAxis = function (axis, angle) {
  5940. var result = Matrix.Zero();
  5941. Matrix.RotationAxisToRef(axis, angle, result);
  5942. return result;
  5943. };
  5944. /**
  5945. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5946. * @param axis defines the axis to use
  5947. * @param angle defines the angle (in radians) to use
  5948. * @param result defines the target matrix
  5949. */
  5950. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5951. var s = Math.sin(-angle);
  5952. var c = Math.cos(-angle);
  5953. var c1 = 1 - c;
  5954. axis.normalize();
  5955. result.m[0] = (axis.x * axis.x) * c1 + c;
  5956. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5957. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5958. result.m[3] = 0.0;
  5959. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5960. result.m[5] = (axis.y * axis.y) * c1 + c;
  5961. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5962. result.m[7] = 0.0;
  5963. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5964. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5965. result.m[10] = (axis.z * axis.z) * c1 + c;
  5966. result.m[11] = 0.0;
  5967. result.m[15] = 1.0;
  5968. result._markAsUpdated();
  5969. };
  5970. /**
  5971. * Creates a rotation matrix
  5972. * @param yaw defines the yaw angle in radians (Y axis)
  5973. * @param pitch defines the pitch angle in radians (X axis)
  5974. * @param roll defines the roll angle in radians (X axis)
  5975. * @returns the new rotation matrix
  5976. */
  5977. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5978. var result = new Matrix();
  5979. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5980. return result;
  5981. };
  5982. /**
  5983. * Creates a rotation matrix and stores it in a given matrix
  5984. * @param yaw defines the yaw angle in radians (Y axis)
  5985. * @param pitch defines the pitch angle in radians (X axis)
  5986. * @param roll defines the roll angle in radians (X axis)
  5987. * @param result defines the target matrix
  5988. */
  5989. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5990. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5991. this._tempQuaternion.toRotationMatrix(result);
  5992. };
  5993. /**
  5994. * Creates a scaling matrix
  5995. * @param x defines the scale factor on X axis
  5996. * @param y defines the scale factor on Y axis
  5997. * @param z defines the scale factor on Z axis
  5998. * @returns the new matrix
  5999. */
  6000. Matrix.Scaling = function (x, y, z) {
  6001. var result = Matrix.Zero();
  6002. Matrix.ScalingToRef(x, y, z, result);
  6003. return result;
  6004. };
  6005. /**
  6006. * Creates a scaling matrix and stores it in a given matrix
  6007. * @param x defines the scale factor on X axis
  6008. * @param y defines the scale factor on Y axis
  6009. * @param z defines the scale factor on Z axis
  6010. * @param result defines the target matrix
  6011. */
  6012. Matrix.ScalingToRef = function (x, y, z, result) {
  6013. result.m[0] = x;
  6014. result.m[1] = 0.0;
  6015. result.m[2] = 0.0;
  6016. result.m[3] = 0.0;
  6017. result.m[4] = 0.0;
  6018. result.m[5] = y;
  6019. result.m[6] = 0.0;
  6020. result.m[7] = 0.0;
  6021. result.m[8] = 0.0;
  6022. result.m[9] = 0.0;
  6023. result.m[10] = z;
  6024. result.m[11] = 0.0;
  6025. result.m[12] = 0.0;
  6026. result.m[13] = 0.0;
  6027. result.m[14] = 0.0;
  6028. result.m[15] = 1.0;
  6029. result._markAsUpdated();
  6030. };
  6031. /**
  6032. * Creates a translation matrix
  6033. * @param x defines the translation on X axis
  6034. * @param y defines the translation on Y axis
  6035. * @param z defines the translationon Z axis
  6036. * @returns the new matrix
  6037. */
  6038. Matrix.Translation = function (x, y, z) {
  6039. var result = Matrix.Identity();
  6040. Matrix.TranslationToRef(x, y, z, result);
  6041. return result;
  6042. };
  6043. /**
  6044. * Creates a translation matrix and stores it in a given matrix
  6045. * @param x defines the translation on X axis
  6046. * @param y defines the translation on Y axis
  6047. * @param z defines the translationon Z axis
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.TranslationToRef = function (x, y, z, result) {
  6051. 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);
  6052. };
  6053. /**
  6054. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6055. * @param startValue defines the start value
  6056. * @param endValue defines the end value
  6057. * @param gradient defines the gradient factor
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.Lerp = function (startValue, endValue, gradient) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6067. * @param startValue defines the start value
  6068. * @param endValue defines the end value
  6069. * @param gradient defines the gradient factor
  6070. * @param result defines the Matrix object where to store data
  6071. */
  6072. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6073. for (var index = 0; index < 16; index++) {
  6074. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6075. }
  6076. result._markAsUpdated();
  6077. };
  6078. /**
  6079. * Builds a new matrix whose values are computed by:
  6080. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6081. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6082. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6083. * @param startValue defines the first matrix
  6084. * @param endValue defines the second matrix
  6085. * @param gradient defines the gradient between the two matrices
  6086. * @returns the new matrix
  6087. */
  6088. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6089. var result = Matrix.Zero();
  6090. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6091. return result;
  6092. };
  6093. /**
  6094. * Update a matrix to values which are computed by:
  6095. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6096. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6097. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6098. * @param startValue defines the first matrix
  6099. * @param endValue defines the second matrix
  6100. * @param gradient defines the gradient between the two matrices
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6104. var startScale = MathTmp.Vector3[0];
  6105. var startRotation = MathTmp.Quaternion[0];
  6106. var startTranslation = MathTmp.Vector3[1];
  6107. startValue.decompose(startScale, startRotation, startTranslation);
  6108. var endScale = MathTmp.Vector3[2];
  6109. var endRotation = MathTmp.Quaternion[1];
  6110. var endTranslation = MathTmp.Vector3[3];
  6111. endValue.decompose(endScale, endRotation, endTranslation);
  6112. var resultScale = MathTmp.Vector3[4];
  6113. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6114. var resultRotation = MathTmp.Quaternion[2];
  6115. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6116. var resultTranslation = MathTmp.Vector3[5];
  6117. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6118. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6119. };
  6120. /**
  6121. * 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"
  6122. * This function works in left handed mode
  6123. * @param eye defines the final position of the entity
  6124. * @param target defines where the entity should look at
  6125. * @param up defines the up vector for the entity
  6126. * @returns the new matrix
  6127. */
  6128. Matrix.LookAtLH = function (eye, target, up) {
  6129. var result = Matrix.Zero();
  6130. Matrix.LookAtLHToRef(eye, target, up, result);
  6131. return result;
  6132. };
  6133. /**
  6134. * 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".
  6135. * This function works in left handed mode
  6136. * @param eye defines the final position of the entity
  6137. * @param target defines where the entity should look at
  6138. * @param up defines the up vector for the entity
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6142. // Z axis
  6143. target.subtractToRef(eye, this._zAxis);
  6144. this._zAxis.normalize();
  6145. // X axis
  6146. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6147. if (this._xAxis.lengthSquared() === 0) {
  6148. this._xAxis.x = 1.0;
  6149. }
  6150. else {
  6151. this._xAxis.normalize();
  6152. }
  6153. // Y axis
  6154. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6155. this._yAxis.normalize();
  6156. // Eye angles
  6157. var ex = -Vector3.Dot(this._xAxis, eye);
  6158. var ey = -Vector3.Dot(this._yAxis, eye);
  6159. var ez = -Vector3.Dot(this._zAxis, eye);
  6160. 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);
  6161. };
  6162. /**
  6163. * 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"
  6164. * This function works in right handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @returns the new matrix
  6169. */
  6170. Matrix.LookAtRH = function (eye, target, up) {
  6171. var result = Matrix.Zero();
  6172. Matrix.LookAtRHToRef(eye, target, up, result);
  6173. return result;
  6174. };
  6175. /**
  6176. * 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".
  6177. * This function works in right handed mode
  6178. * @param eye defines the final position of the entity
  6179. * @param target defines where the entity should look at
  6180. * @param up defines the up vector for the entity
  6181. * @param result defines the target matrix
  6182. */
  6183. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6184. // Z axis
  6185. eye.subtractToRef(target, this._zAxis);
  6186. this._zAxis.normalize();
  6187. // X axis
  6188. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6189. if (this._xAxis.lengthSquared() === 0) {
  6190. this._xAxis.x = 1.0;
  6191. }
  6192. else {
  6193. this._xAxis.normalize();
  6194. }
  6195. // Y axis
  6196. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6197. this._yAxis.normalize();
  6198. // Eye angles
  6199. var ex = -Vector3.Dot(this._xAxis, eye);
  6200. var ey = -Vector3.Dot(this._yAxis, eye);
  6201. var ez = -Vector3.Dot(this._zAxis, eye);
  6202. 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);
  6203. };
  6204. /**
  6205. * Create a left-handed orthographic projection matrix
  6206. * @param width defines the viewport width
  6207. * @param height defines the viewport height
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a left-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Store a left-handed orthographic projection to a given matrix
  6219. * @param width defines the viewport width
  6220. * @param height defines the viewport height
  6221. * @param znear defines the near clip plane
  6222. * @param zfar defines the far clip plane
  6223. * @param result defines the target matrix
  6224. */
  6225. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6226. var n = znear;
  6227. var f = zfar;
  6228. var a = 2.0 / width;
  6229. var b = 2.0 / height;
  6230. var c = 2.0 / (f - n);
  6231. var d = -(f + n) / (f - n);
  6232. 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);
  6233. };
  6234. /**
  6235. * Create a left-handed orthographic projection matrix
  6236. * @param left defines the viewport left coordinate
  6237. * @param right defines the viewport right coordinate
  6238. * @param bottom defines the viewport bottom coordinate
  6239. * @param top defines the viewport top coordinate
  6240. * @param znear defines the near clip plane
  6241. * @param zfar defines the far clip plane
  6242. * @returns a new matrix as a left-handed orthographic projection matrix
  6243. */
  6244. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6245. var matrix = Matrix.Zero();
  6246. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6247. return matrix;
  6248. };
  6249. /**
  6250. * Stores a left-handed orthographic projection into a given matrix
  6251. * @param left defines the viewport left coordinate
  6252. * @param right defines the viewport right coordinate
  6253. * @param bottom defines the viewport bottom coordinate
  6254. * @param top defines the viewport top coordinate
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. */
  6259. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6260. var n = znear;
  6261. var f = zfar;
  6262. var a = 2.0 / (right - left);
  6263. var b = 2.0 / (top - bottom);
  6264. var c = 2.0 / (f - n);
  6265. var d = -(f + n) / (f - n);
  6266. var i0 = (left + right) / (left - right);
  6267. var i1 = (top + bottom) / (bottom - top);
  6268. 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);
  6269. };
  6270. /**
  6271. * Creates a right-handed orthographic projection matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a right-handed orthographic projection matrix
  6279. */
  6280. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a right-handed orthographic projection into a given matrix
  6287. * @param left defines the viewport left coordinate
  6288. * @param right defines the viewport right coordinate
  6289. * @param bottom defines the viewport bottom coordinate
  6290. * @param top defines the viewport top coordinate
  6291. * @param znear defines the near clip plane
  6292. * @param zfar defines the far clip plane
  6293. * @param result defines the target matrix
  6294. */
  6295. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6297. result.m[10] *= -1.0;
  6298. };
  6299. /**
  6300. * Creates a left-handed perspective projection matrix
  6301. * @param width defines the viewport width
  6302. * @param height defines the viewport height
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a left-handed perspective projection matrix
  6306. */
  6307. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. var n = znear;
  6310. var f = zfar;
  6311. var a = 2.0 * n / width;
  6312. var b = 2.0 * n / height;
  6313. var c = (f + n) / (f - n);
  6314. var d = -2.0 * f * n / (f - n);
  6315. 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);
  6316. return matrix;
  6317. };
  6318. /**
  6319. * Creates a left-handed perspective projection matrix
  6320. * @param fov defines the horizontal field of view
  6321. * @param aspect defines the aspect ratio
  6322. * @param znear defines the near clip plane
  6323. * @param zfar defines the far clip plane
  6324. * @returns a new matrix as a left-handed perspective projection matrix
  6325. */
  6326. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6327. var matrix = Matrix.Zero();
  6328. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6329. return matrix;
  6330. };
  6331. /**
  6332. * Stores a left-handed perspective projection into a given matrix
  6333. * @param fov defines the horizontal field of view
  6334. * @param aspect defines the aspect ratio
  6335. * @param znear defines the near clip plane
  6336. * @param zfar defines the far clip plane
  6337. * @param result defines the target matrix
  6338. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6339. */
  6340. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6341. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6342. var n = znear;
  6343. var f = zfar;
  6344. var t = 1.0 / (Math.tan(fov * 0.5));
  6345. var a = isVerticalFovFixed ? (t / aspect) : t;
  6346. var b = isVerticalFovFixed ? t : (t * aspect);
  6347. var c = (f + n) / (f - n);
  6348. var d = -2.0 * f * n / (f - n);
  6349. 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);
  6350. };
  6351. /**
  6352. * Creates a right-handed perspective projection matrix
  6353. * @param fov defines the horizontal field of view
  6354. * @param aspect defines the aspect ratio
  6355. * @param znear defines the near clip plane
  6356. * @param zfar defines the far clip plane
  6357. * @returns a new matrix as a right-handed perspective projection matrix
  6358. */
  6359. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6360. var matrix = Matrix.Zero();
  6361. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6362. return matrix;
  6363. };
  6364. /**
  6365. * Stores a right-handed perspective projection into a given matrix
  6366. * @param fov defines the horizontal field of view
  6367. * @param aspect defines the aspect ratio
  6368. * @param znear defines the near clip plane
  6369. * @param zfar defines the far clip plane
  6370. * @param result defines the target matrix
  6371. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6372. */
  6373. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6374. //alternatively this could be expressed as:
  6375. // m = PerspectiveFovLHToRef
  6376. // m[10] *= -1.0;
  6377. // m[11] *= -1.0;
  6378. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6379. var n = znear;
  6380. var f = zfar;
  6381. var t = 1.0 / (Math.tan(fov * 0.5));
  6382. var a = isVerticalFovFixed ? (t / aspect) : t;
  6383. var b = isVerticalFovFixed ? t : (t * aspect);
  6384. var c = -(f + n) / (f - n);
  6385. var d = -2 * f * n / (f - n);
  6386. 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);
  6387. };
  6388. /**
  6389. * Stores a perspective projection for WebVR info a given matrix
  6390. * @param fov defines the field of view
  6391. * @param znear defines the near clip plane
  6392. * @param zfar defines the far clip plane
  6393. * @param result defines the target matrix
  6394. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6395. */
  6396. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6397. if (rightHanded === void 0) { rightHanded = false; }
  6398. var rightHandedFactor = rightHanded ? -1 : 1;
  6399. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6400. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6401. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6402. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6403. var xScale = 2.0 / (leftTan + rightTan);
  6404. var yScale = 2.0 / (upTan + downTan);
  6405. result.m[0] = xScale;
  6406. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6407. result.m[5] = yScale;
  6408. result.m[6] = result.m[7] = 0.0;
  6409. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6410. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6411. result.m[10] = -zfar / (znear - zfar);
  6412. result.m[11] = 1.0 * rightHandedFactor;
  6413. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6414. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6415. result._markAsUpdated();
  6416. };
  6417. /**
  6418. * Computes a complete transformation matrix
  6419. * @param viewport defines the viewport to use
  6420. * @param world defines the world matrix
  6421. * @param view defines the view matrix
  6422. * @param projection defines the projection matrix
  6423. * @param zmin defines the near clip plane
  6424. * @param zmax defines the far clip plane
  6425. * @returns the transformation matrix
  6426. */
  6427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6428. var cw = viewport.width;
  6429. var ch = viewport.height;
  6430. var cx = viewport.x;
  6431. var cy = viewport.y;
  6432. 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);
  6433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6434. };
  6435. /**
  6436. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6437. * @param matrix defines the matrix to use
  6438. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6439. */
  6440. Matrix.GetAsMatrix2x2 = function (matrix) {
  6441. return new Float32Array([
  6442. matrix.m[0], matrix.m[1],
  6443. matrix.m[4], matrix.m[5]
  6444. ]);
  6445. };
  6446. /**
  6447. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6448. * @param matrix defines the matrix to use
  6449. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6450. */
  6451. Matrix.GetAsMatrix3x3 = function (matrix) {
  6452. return new Float32Array([
  6453. matrix.m[0], matrix.m[1], matrix.m[2],
  6454. matrix.m[4], matrix.m[5], matrix.m[6],
  6455. matrix.m[8], matrix.m[9], matrix.m[10]
  6456. ]);
  6457. };
  6458. /**
  6459. * Compute the transpose of a given matrix
  6460. * @param matrix defines the matrix to transpose
  6461. * @returns the new matrix
  6462. */
  6463. Matrix.Transpose = function (matrix) {
  6464. var result = new Matrix();
  6465. Matrix.TransposeToRef(matrix, result);
  6466. return result;
  6467. };
  6468. /**
  6469. * Compute the transpose of a matrix and store it in a target matrix
  6470. * @param matrix defines the matrix to transpose
  6471. * @param result defines the target matrix
  6472. */
  6473. Matrix.TransposeToRef = function (matrix, result) {
  6474. result.m[0] = matrix.m[0];
  6475. result.m[1] = matrix.m[4];
  6476. result.m[2] = matrix.m[8];
  6477. result.m[3] = matrix.m[12];
  6478. result.m[4] = matrix.m[1];
  6479. result.m[5] = matrix.m[5];
  6480. result.m[6] = matrix.m[9];
  6481. result.m[7] = matrix.m[13];
  6482. result.m[8] = matrix.m[2];
  6483. result.m[9] = matrix.m[6];
  6484. result.m[10] = matrix.m[10];
  6485. result.m[11] = matrix.m[14];
  6486. result.m[12] = matrix.m[3];
  6487. result.m[13] = matrix.m[7];
  6488. result.m[14] = matrix.m[11];
  6489. result.m[15] = matrix.m[15];
  6490. };
  6491. /**
  6492. * Computes a reflection matrix from a plane
  6493. * @param plane defines the reflection plane
  6494. * @returns a new matrix
  6495. */
  6496. Matrix.Reflection = function (plane) {
  6497. var matrix = new Matrix();
  6498. Matrix.ReflectionToRef(plane, matrix);
  6499. return matrix;
  6500. };
  6501. /**
  6502. * Computes a reflection matrix from a plane
  6503. * @param plane defines the reflection plane
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.ReflectionToRef = function (plane, result) {
  6507. plane.normalize();
  6508. var x = plane.normal.x;
  6509. var y = plane.normal.y;
  6510. var z = plane.normal.z;
  6511. var temp = -2 * x;
  6512. var temp2 = -2 * y;
  6513. var temp3 = -2 * z;
  6514. result.m[0] = (temp * x) + 1;
  6515. result.m[1] = temp2 * x;
  6516. result.m[2] = temp3 * x;
  6517. result.m[3] = 0.0;
  6518. result.m[4] = temp * y;
  6519. result.m[5] = (temp2 * y) + 1;
  6520. result.m[6] = temp3 * y;
  6521. result.m[7] = 0.0;
  6522. result.m[8] = temp * z;
  6523. result.m[9] = temp2 * z;
  6524. result.m[10] = (temp3 * z) + 1;
  6525. result.m[11] = 0.0;
  6526. result.m[12] = temp * plane.d;
  6527. result.m[13] = temp2 * plane.d;
  6528. result.m[14] = temp3 * plane.d;
  6529. result.m[15] = 1.0;
  6530. result._markAsUpdated();
  6531. };
  6532. /**
  6533. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6534. * @param xaxis defines the value of the 1st axis
  6535. * @param yaxis defines the value of the 2nd axis
  6536. * @param zaxis defines the value of the 3rd axis
  6537. * @param result defines the target matrix
  6538. */
  6539. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6540. result.m[0] = xaxis.x;
  6541. result.m[1] = xaxis.y;
  6542. result.m[2] = xaxis.z;
  6543. result.m[3] = 0.0;
  6544. result.m[4] = yaxis.x;
  6545. result.m[5] = yaxis.y;
  6546. result.m[6] = yaxis.z;
  6547. result.m[7] = 0.0;
  6548. result.m[8] = zaxis.x;
  6549. result.m[9] = zaxis.y;
  6550. result.m[10] = zaxis.z;
  6551. result.m[11] = 0.0;
  6552. result.m[12] = 0.0;
  6553. result.m[13] = 0.0;
  6554. result.m[14] = 0.0;
  6555. result.m[15] = 1.0;
  6556. result._markAsUpdated();
  6557. };
  6558. /**
  6559. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6560. * @param quat defines the quaternion to use
  6561. * @param result defines the target matrix
  6562. */
  6563. Matrix.FromQuaternionToRef = function (quat, result) {
  6564. var xx = quat.x * quat.x;
  6565. var yy = quat.y * quat.y;
  6566. var zz = quat.z * quat.z;
  6567. var xy = quat.x * quat.y;
  6568. var zw = quat.z * quat.w;
  6569. var zx = quat.z * quat.x;
  6570. var yw = quat.y * quat.w;
  6571. var yz = quat.y * quat.z;
  6572. var xw = quat.x * quat.w;
  6573. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6574. result.m[1] = 2.0 * (xy + zw);
  6575. result.m[2] = 2.0 * (zx - yw);
  6576. result.m[3] = 0.0;
  6577. result.m[4] = 2.0 * (xy - zw);
  6578. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6579. result.m[6] = 2.0 * (yz + xw);
  6580. result.m[7] = 0.0;
  6581. result.m[8] = 2.0 * (zx + yw);
  6582. result.m[9] = 2.0 * (yz - xw);
  6583. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6584. result.m[11] = 0.0;
  6585. result.m[12] = 0.0;
  6586. result.m[13] = 0.0;
  6587. result.m[14] = 0.0;
  6588. result.m[15] = 1.0;
  6589. result._markAsUpdated();
  6590. };
  6591. Matrix._tempQuaternion = new Quaternion();
  6592. Matrix._xAxis = Vector3.Zero();
  6593. Matrix._yAxis = Vector3.Zero();
  6594. Matrix._zAxis = Vector3.Zero();
  6595. Matrix._updateFlagSeed = 0;
  6596. Matrix._identityReadOnly = Matrix.Identity();
  6597. return Matrix;
  6598. }());
  6599. BABYLON.Matrix = Matrix;
  6600. var Plane = /** @class */ (function () {
  6601. /**
  6602. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6603. */
  6604. function Plane(a, b, c, d) {
  6605. this.normal = new Vector3(a, b, c);
  6606. this.d = d;
  6607. }
  6608. /**
  6609. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6610. */
  6611. Plane.prototype.asArray = function () {
  6612. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6613. };
  6614. // Methods
  6615. /**
  6616. * Returns a new plane copied from the current Plane.
  6617. */
  6618. Plane.prototype.clone = function () {
  6619. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6620. };
  6621. /**
  6622. * Returns the string "Plane".
  6623. */
  6624. Plane.prototype.getClassName = function () {
  6625. return "Plane";
  6626. };
  6627. /**
  6628. * Returns the Plane hash code.
  6629. */
  6630. Plane.prototype.getHashCode = function () {
  6631. var hash = this.normal.getHashCode();
  6632. hash = (hash * 397) ^ (this.d || 0);
  6633. return hash;
  6634. };
  6635. /**
  6636. * Normalize the current Plane in place.
  6637. * Returns the updated Plane.
  6638. */
  6639. Plane.prototype.normalize = function () {
  6640. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6641. var magnitude = 0.0;
  6642. if (norm !== 0) {
  6643. magnitude = 1.0 / norm;
  6644. }
  6645. this.normal.x *= magnitude;
  6646. this.normal.y *= magnitude;
  6647. this.normal.z *= magnitude;
  6648. this.d *= magnitude;
  6649. return this;
  6650. };
  6651. /**
  6652. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6653. */
  6654. Plane.prototype.transform = function (transformation) {
  6655. var transposedMatrix = Matrix.Transpose(transformation);
  6656. var x = this.normal.x;
  6657. var y = this.normal.y;
  6658. var z = this.normal.z;
  6659. var d = this.d;
  6660. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6661. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6662. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6663. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6664. return new Plane(normalX, normalY, normalZ, finalD);
  6665. };
  6666. /**
  6667. * Returns the dot product (float) of the point coordinates and the plane normal.
  6668. */
  6669. Plane.prototype.dotCoordinate = function (point) {
  6670. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6671. };
  6672. /**
  6673. * Updates the current Plane from the plane defined by the three given points.
  6674. * Returns the updated Plane.
  6675. */
  6676. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6677. var x1 = point2.x - point1.x;
  6678. var y1 = point2.y - point1.y;
  6679. var z1 = point2.z - point1.z;
  6680. var x2 = point3.x - point1.x;
  6681. var y2 = point3.y - point1.y;
  6682. var z2 = point3.z - point1.z;
  6683. var yz = (y1 * z2) - (z1 * y2);
  6684. var xz = (z1 * x2) - (x1 * z2);
  6685. var xy = (x1 * y2) - (y1 * x2);
  6686. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6687. var invPyth;
  6688. if (pyth !== 0) {
  6689. invPyth = 1.0 / pyth;
  6690. }
  6691. else {
  6692. invPyth = 0.0;
  6693. }
  6694. this.normal.x = yz * invPyth;
  6695. this.normal.y = xz * invPyth;
  6696. this.normal.z = xy * invPyth;
  6697. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6698. return this;
  6699. };
  6700. /**
  6701. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6702. */
  6703. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6704. var dot = Vector3.Dot(this.normal, direction);
  6705. return (dot <= epsilon);
  6706. };
  6707. /**
  6708. * Returns the signed distance (float) from the given point to the Plane.
  6709. */
  6710. Plane.prototype.signedDistanceTo = function (point) {
  6711. return Vector3.Dot(point, this.normal) + this.d;
  6712. };
  6713. // Statics
  6714. /**
  6715. * Returns a new Plane from the given array.
  6716. */
  6717. Plane.FromArray = function (array) {
  6718. return new Plane(array[0], array[1], array[2], array[3]);
  6719. };
  6720. /**
  6721. * Returns a new Plane defined by the three given points.
  6722. */
  6723. Plane.FromPoints = function (point1, point2, point3) {
  6724. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6725. result.copyFromPoints(point1, point2, point3);
  6726. return result;
  6727. };
  6728. /**
  6729. * Returns a new Plane the normal vector to this plane at the given origin point.
  6730. * Note : the vector "normal" is updated because normalized.
  6731. */
  6732. Plane.FromPositionAndNormal = function (origin, normal) {
  6733. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6734. normal.normalize();
  6735. result.normal = normal;
  6736. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6737. return result;
  6738. };
  6739. /**
  6740. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6741. */
  6742. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6743. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6744. return Vector3.Dot(point, normal) + d;
  6745. };
  6746. return Plane;
  6747. }());
  6748. BABYLON.Plane = Plane;
  6749. var Viewport = /** @class */ (function () {
  6750. /**
  6751. * Creates a Viewport object located at (x, y) and sized (width, height).
  6752. */
  6753. function Viewport(x, y, width, height) {
  6754. this.x = x;
  6755. this.y = y;
  6756. this.width = width;
  6757. this.height = height;
  6758. }
  6759. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6760. if (renderWidthOrEngine.getRenderWidth) {
  6761. var engine = renderWidthOrEngine;
  6762. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6763. }
  6764. var renderWidth = renderWidthOrEngine;
  6765. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6766. };
  6767. /**
  6768. * Returns a new Viewport copied from the current one.
  6769. */
  6770. Viewport.prototype.clone = function () {
  6771. return new Viewport(this.x, this.y, this.width, this.height);
  6772. };
  6773. return Viewport;
  6774. }());
  6775. BABYLON.Viewport = Viewport;
  6776. var Frustum = /** @class */ (function () {
  6777. function Frustum() {
  6778. }
  6779. /**
  6780. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6781. */
  6782. Frustum.GetPlanes = function (transform) {
  6783. var frustumPlanes = [];
  6784. for (var index = 0; index < 6; index++) {
  6785. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6786. }
  6787. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6788. return frustumPlanes;
  6789. };
  6790. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6791. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6792. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6793. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6794. frustumPlane.d = transform.m[15] + transform.m[14];
  6795. frustumPlane.normalize();
  6796. };
  6797. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6798. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6799. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6800. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6801. frustumPlane.d = transform.m[15] - transform.m[14];
  6802. frustumPlane.normalize();
  6803. };
  6804. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6805. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6806. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6807. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6808. frustumPlane.d = transform.m[15] + transform.m[12];
  6809. frustumPlane.normalize();
  6810. };
  6811. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6813. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6814. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6815. frustumPlane.d = transform.m[15] - transform.m[12];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6820. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6821. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6822. frustumPlane.d = transform.m[15] - transform.m[13];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6827. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6828. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6829. frustumPlane.d = transform.m[15] + transform.m[13];
  6830. frustumPlane.normalize();
  6831. };
  6832. /**
  6833. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6834. */
  6835. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6836. // Near
  6837. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6838. // Far
  6839. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6840. // Left
  6841. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6842. // Right
  6843. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6844. // Top
  6845. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6846. // Bottom
  6847. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6848. };
  6849. return Frustum;
  6850. }());
  6851. BABYLON.Frustum = Frustum;
  6852. /** Defines supported spaces */
  6853. var Space;
  6854. (function (Space) {
  6855. /** Local (object) space */
  6856. Space[Space["LOCAL"] = 0] = "LOCAL";
  6857. /** World space */
  6858. Space[Space["WORLD"] = 1] = "WORLD";
  6859. /** Bone space */
  6860. Space[Space["BONE"] = 2] = "BONE";
  6861. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6862. /** Defines the 3 main axes */
  6863. var Axis = /** @class */ (function () {
  6864. function Axis() {
  6865. }
  6866. /** X axis */
  6867. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6868. /** Y axis */
  6869. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6870. /** Z axis */
  6871. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6872. return Axis;
  6873. }());
  6874. BABYLON.Axis = Axis;
  6875. ;
  6876. var BezierCurve = /** @class */ (function () {
  6877. function BezierCurve() {
  6878. }
  6879. /**
  6880. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6881. */
  6882. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6883. // Extract X (which is equal to time here)
  6884. var f0 = 1 - 3 * x2 + 3 * x1;
  6885. var f1 = 3 * x2 - 6 * x1;
  6886. var f2 = 3 * x1;
  6887. var refinedT = t;
  6888. for (var i = 0; i < 5; i++) {
  6889. var refinedT2 = refinedT * refinedT;
  6890. var refinedT3 = refinedT2 * refinedT;
  6891. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6892. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6893. refinedT -= (x - t) * slope;
  6894. refinedT = Math.min(1, Math.max(0, refinedT));
  6895. }
  6896. // Resolve cubic bezier for the given x
  6897. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6898. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6899. Math.pow(refinedT, 3);
  6900. };
  6901. return BezierCurve;
  6902. }());
  6903. BABYLON.BezierCurve = BezierCurve;
  6904. /**
  6905. * Defines potential orientation for back face culling
  6906. */
  6907. var Orientation;
  6908. (function (Orientation) {
  6909. /**
  6910. * Clockwise
  6911. */
  6912. Orientation[Orientation["CW"] = 0] = "CW";
  6913. /** Counter clockwise */
  6914. Orientation[Orientation["CCW"] = 1] = "CCW";
  6915. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6916. /**
  6917. * Defines angle representation
  6918. */
  6919. var Angle = /** @class */ (function () {
  6920. /**
  6921. * Creates an Angle object of "radians" radians (float).
  6922. */
  6923. function Angle(radians) {
  6924. this._radians = radians;
  6925. if (this._radians < 0.0)
  6926. this._radians += (2.0 * Math.PI);
  6927. }
  6928. /**
  6929. * Get value in degrees
  6930. * @returns the Angle value in degrees (float)
  6931. */
  6932. Angle.prototype.degrees = function () {
  6933. return this._radians * 180.0 / Math.PI;
  6934. };
  6935. /**
  6936. * Get value in radians
  6937. * @returns the Angle value in radians (float)
  6938. */
  6939. Angle.prototype.radians = function () {
  6940. return this._radians;
  6941. };
  6942. /**
  6943. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6944. * @param a defines first vector
  6945. * @param b defines second vector
  6946. * @returns a new Angle
  6947. */
  6948. Angle.BetweenTwoPoints = function (a, b) {
  6949. var delta = b.subtract(a);
  6950. var theta = Math.atan2(delta.y, delta.x);
  6951. return new Angle(theta);
  6952. };
  6953. /**
  6954. * Gets a new Angle object from the given float in radians
  6955. * @param radians defines the angle value in radians
  6956. * @returns a new Angle
  6957. */
  6958. Angle.FromRadians = function (radians) {
  6959. return new Angle(radians);
  6960. };
  6961. /**
  6962. * Gets a new Angle object from the given float in degrees
  6963. * @param degrees defines the angle value in degrees
  6964. * @returns a new Angle
  6965. */
  6966. Angle.FromDegrees = function (degrees) {
  6967. return new Angle(degrees * Math.PI / 180.0);
  6968. };
  6969. return Angle;
  6970. }());
  6971. BABYLON.Angle = Angle;
  6972. var Arc2 = /** @class */ (function () {
  6973. /**
  6974. * Creates an Arc object from the three given points : start, middle and end.
  6975. */
  6976. function Arc2(startPoint, midPoint, endPoint) {
  6977. this.startPoint = startPoint;
  6978. this.midPoint = midPoint;
  6979. this.endPoint = endPoint;
  6980. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6981. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6982. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6983. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6984. 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);
  6985. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6986. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6987. var a1 = this.startAngle.degrees();
  6988. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6989. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6990. // angles correction
  6991. if (a2 - a1 > +180.0)
  6992. a2 -= 360.0;
  6993. if (a2 - a1 < -180.0)
  6994. a2 += 360.0;
  6995. if (a3 - a2 > +180.0)
  6996. a3 -= 360.0;
  6997. if (a3 - a2 < -180.0)
  6998. a3 += 360.0;
  6999. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7000. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7001. }
  7002. return Arc2;
  7003. }());
  7004. BABYLON.Arc2 = Arc2;
  7005. var Path2 = /** @class */ (function () {
  7006. /**
  7007. * Creates a Path2 object from the starting 2D coordinates x and y.
  7008. */
  7009. function Path2(x, y) {
  7010. this._points = new Array();
  7011. this._length = 0.0;
  7012. this.closed = false;
  7013. this._points.push(new Vector2(x, y));
  7014. }
  7015. /**
  7016. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7017. * Returns the updated Path2.
  7018. */
  7019. Path2.prototype.addLineTo = function (x, y) {
  7020. if (this.closed) {
  7021. return this;
  7022. }
  7023. var newPoint = new Vector2(x, y);
  7024. var previousPoint = this._points[this._points.length - 1];
  7025. this._points.push(newPoint);
  7026. this._length += newPoint.subtract(previousPoint).length();
  7027. return this;
  7028. };
  7029. /**
  7030. * 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.
  7031. * Returns the updated Path2.
  7032. */
  7033. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7034. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7035. if (this.closed) {
  7036. return this;
  7037. }
  7038. var startPoint = this._points[this._points.length - 1];
  7039. var midPoint = new Vector2(midX, midY);
  7040. var endPoint = new Vector2(endX, endY);
  7041. var arc = new Arc2(startPoint, midPoint, endPoint);
  7042. var increment = arc.angle.radians() / numberOfSegments;
  7043. if (arc.orientation === Orientation.CW)
  7044. increment *= -1;
  7045. var currentAngle = arc.startAngle.radians() + increment;
  7046. for (var i = 0; i < numberOfSegments; i++) {
  7047. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7048. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7049. this.addLineTo(x, y);
  7050. currentAngle += increment;
  7051. }
  7052. return this;
  7053. };
  7054. /**
  7055. * Closes the Path2.
  7056. * Returns the Path2.
  7057. */
  7058. Path2.prototype.close = function () {
  7059. this.closed = true;
  7060. return this;
  7061. };
  7062. /**
  7063. * Returns the Path2 total length (float).
  7064. */
  7065. Path2.prototype.length = function () {
  7066. var result = this._length;
  7067. if (!this.closed) {
  7068. var lastPoint = this._points[this._points.length - 1];
  7069. var firstPoint = this._points[0];
  7070. result += (firstPoint.subtract(lastPoint).length());
  7071. }
  7072. return result;
  7073. };
  7074. /**
  7075. * Returns the Path2 internal array of points.
  7076. */
  7077. Path2.prototype.getPoints = function () {
  7078. return this._points;
  7079. };
  7080. /**
  7081. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7082. */
  7083. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7084. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7085. return Vector2.Zero();
  7086. }
  7087. var lengthPosition = normalizedLengthPosition * this.length();
  7088. var previousOffset = 0;
  7089. for (var i = 0; i < this._points.length; i++) {
  7090. var j = (i + 1) % this._points.length;
  7091. var a = this._points[i];
  7092. var b = this._points[j];
  7093. var bToA = b.subtract(a);
  7094. var nextOffset = (bToA.length() + previousOffset);
  7095. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7096. var dir = bToA.normalize();
  7097. var localOffset = lengthPosition - previousOffset;
  7098. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7099. }
  7100. previousOffset = nextOffset;
  7101. }
  7102. return Vector2.Zero();
  7103. };
  7104. /**
  7105. * Returns a new Path2 starting at the coordinates (x, y).
  7106. */
  7107. Path2.StartingAt = function (x, y) {
  7108. return new Path2(x, y);
  7109. };
  7110. return Path2;
  7111. }());
  7112. BABYLON.Path2 = Path2;
  7113. var Path3D = /** @class */ (function () {
  7114. /**
  7115. * new Path3D(path, normal, raw)
  7116. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7117. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7118. * path : an array of Vector3, the curve axis of the Path3D
  7119. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7120. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7121. */
  7122. function Path3D(path, firstNormal, raw) {
  7123. if (firstNormal === void 0) { firstNormal = null; }
  7124. this.path = path;
  7125. this._curve = new Array();
  7126. this._distances = new Array();
  7127. this._tangents = new Array();
  7128. this._normals = new Array();
  7129. this._binormals = new Array();
  7130. for (var p = 0; p < path.length; p++) {
  7131. this._curve[p] = path[p].clone(); // hard copy
  7132. }
  7133. this._raw = raw || false;
  7134. this._compute(firstNormal);
  7135. }
  7136. /**
  7137. * Returns the Path3D array of successive Vector3 designing its curve.
  7138. */
  7139. Path3D.prototype.getCurve = function () {
  7140. return this._curve;
  7141. };
  7142. /**
  7143. * Returns an array populated with tangent vectors on each Path3D curve point.
  7144. */
  7145. Path3D.prototype.getTangents = function () {
  7146. return this._tangents;
  7147. };
  7148. /**
  7149. * Returns an array populated with normal vectors on each Path3D curve point.
  7150. */
  7151. Path3D.prototype.getNormals = function () {
  7152. return this._normals;
  7153. };
  7154. /**
  7155. * Returns an array populated with binormal vectors on each Path3D curve point.
  7156. */
  7157. Path3D.prototype.getBinormals = function () {
  7158. return this._binormals;
  7159. };
  7160. /**
  7161. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7162. */
  7163. Path3D.prototype.getDistances = function () {
  7164. return this._distances;
  7165. };
  7166. /**
  7167. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7168. * Returns the same object updated.
  7169. */
  7170. Path3D.prototype.update = function (path, firstNormal) {
  7171. if (firstNormal === void 0) { firstNormal = null; }
  7172. for (var p = 0; p < path.length; p++) {
  7173. this._curve[p].x = path[p].x;
  7174. this._curve[p].y = path[p].y;
  7175. this._curve[p].z = path[p].z;
  7176. }
  7177. this._compute(firstNormal);
  7178. return this;
  7179. };
  7180. // private function compute() : computes tangents, normals and binormals
  7181. Path3D.prototype._compute = function (firstNormal) {
  7182. var l = this._curve.length;
  7183. // first and last tangents
  7184. this._tangents[0] = this._getFirstNonNullVector(0);
  7185. if (!this._raw) {
  7186. this._tangents[0].normalize();
  7187. }
  7188. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7189. if (!this._raw) {
  7190. this._tangents[l - 1].normalize();
  7191. }
  7192. // normals and binormals at first point : arbitrary vector with _normalVector()
  7193. var tg0 = this._tangents[0];
  7194. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7195. this._normals[0] = pp0;
  7196. if (!this._raw) {
  7197. this._normals[0].normalize();
  7198. }
  7199. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7200. if (!this._raw) {
  7201. this._binormals[0].normalize();
  7202. }
  7203. this._distances[0] = 0.0;
  7204. // normals and binormals : next points
  7205. var prev; // previous vector (segment)
  7206. var cur; // current vector (segment)
  7207. var curTang; // current tangent
  7208. // previous normal
  7209. var prevBinor; // previous binormal
  7210. for (var i = 1; i < l; i++) {
  7211. // tangents
  7212. prev = this._getLastNonNullVector(i);
  7213. if (i < l - 1) {
  7214. cur = this._getFirstNonNullVector(i);
  7215. this._tangents[i] = prev.add(cur);
  7216. this._tangents[i].normalize();
  7217. }
  7218. this._distances[i] = this._distances[i - 1] + prev.length();
  7219. // normals and binormals
  7220. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7221. curTang = this._tangents[i];
  7222. prevBinor = this._binormals[i - 1];
  7223. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7224. if (!this._raw) {
  7225. this._normals[i].normalize();
  7226. }
  7227. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7228. if (!this._raw) {
  7229. this._binormals[i].normalize();
  7230. }
  7231. }
  7232. };
  7233. // private function getFirstNonNullVector(index)
  7234. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7235. Path3D.prototype._getFirstNonNullVector = function (index) {
  7236. var i = 1;
  7237. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7238. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7239. i++;
  7240. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7241. }
  7242. return nNVector;
  7243. };
  7244. // private function getLastNonNullVector(index)
  7245. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7246. Path3D.prototype._getLastNonNullVector = function (index) {
  7247. var i = 1;
  7248. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7249. while (nLVector.length() === 0 && index > i + 1) {
  7250. i++;
  7251. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7252. }
  7253. return nLVector;
  7254. };
  7255. // private function normalVector(v0, vt, va) :
  7256. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7257. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7258. Path3D.prototype._normalVector = function (v0, vt, va) {
  7259. var normal0;
  7260. var tgl = vt.length();
  7261. if (tgl === 0.0) {
  7262. tgl = 1.0;
  7263. }
  7264. if (va === undefined || va === null) {
  7265. var point;
  7266. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7267. point = new Vector3(0.0, -1.0, 0.0);
  7268. }
  7269. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7270. point = new Vector3(1.0, 0.0, 0.0);
  7271. }
  7272. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7273. point = new Vector3(0.0, 0.0, 1.0);
  7274. }
  7275. else {
  7276. point = Vector3.Zero();
  7277. }
  7278. normal0 = Vector3.Cross(vt, point);
  7279. }
  7280. else {
  7281. normal0 = Vector3.Cross(vt, va);
  7282. Vector3.CrossToRef(normal0, vt, normal0);
  7283. }
  7284. normal0.normalize();
  7285. return normal0;
  7286. };
  7287. return Path3D;
  7288. }());
  7289. BABYLON.Path3D = Path3D;
  7290. var Curve3 = /** @class */ (function () {
  7291. /**
  7292. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7293. * A Curve3 is designed from a series of successive Vector3.
  7294. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7295. */
  7296. function Curve3(points) {
  7297. this._length = 0.0;
  7298. this._points = points;
  7299. this._length = this._computeLength(points);
  7300. }
  7301. /**
  7302. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7303. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7304. * @param v1 (Vector3) the control point
  7305. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7306. * @param nbPoints (integer) the wanted number of points in the curve
  7307. */
  7308. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7309. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7310. var bez = new Array();
  7311. var equation = function (t, val0, val1, val2) {
  7312. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7313. return res;
  7314. };
  7315. for (var i = 0; i <= nbPoints; i++) {
  7316. 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)));
  7317. }
  7318. return new Curve3(bez);
  7319. };
  7320. /**
  7321. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7322. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7323. * @param v1 (Vector3) the first control point
  7324. * @param v2 (Vector3) the second control point
  7325. * @param v3 (Vector3) the end point of the Cubic Bezier
  7326. * @param nbPoints (integer) the wanted number of points in the curve
  7327. */
  7328. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7329. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7330. var bez = new Array();
  7331. var equation = function (t, val0, val1, val2, val3) {
  7332. 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;
  7333. return res;
  7334. };
  7335. for (var i = 0; i <= nbPoints; i++) {
  7336. 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)));
  7337. }
  7338. return new Curve3(bez);
  7339. };
  7340. /**
  7341. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7342. * @param p1 (Vector3) the origin point of the Hermite Spline
  7343. * @param t1 (Vector3) the tangent vector at the origin point
  7344. * @param p2 (Vector3) the end point of the Hermite Spline
  7345. * @param t2 (Vector3) the tangent vector at the end point
  7346. * @param nbPoints (integer) the wanted number of points in the curve
  7347. */
  7348. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7349. var hermite = new Array();
  7350. var step = 1.0 / nbPoints;
  7351. for (var i = 0; i <= nbPoints; i++) {
  7352. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7353. }
  7354. return new Curve3(hermite);
  7355. };
  7356. /**
  7357. * Returns a Curve3 object along a CatmullRom Spline curve :
  7358. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7359. * @param nbPoints (integer) the wanted number of points between each curve control points
  7360. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7361. */
  7362. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7363. var catmullRom = new Array();
  7364. var step = 1.0 / nbPoints;
  7365. var amount = 0.0;
  7366. if (closed) {
  7367. var pointsCount = points.length;
  7368. for (var i = 0; i < pointsCount; i++) {
  7369. amount = 0;
  7370. for (var c = 0; c < nbPoints; c++) {
  7371. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7372. amount += step;
  7373. }
  7374. }
  7375. catmullRom.push(catmullRom[0]);
  7376. }
  7377. else {
  7378. var totalPoints = new Array();
  7379. totalPoints.push(points[0].clone());
  7380. Array.prototype.push.apply(totalPoints, points);
  7381. totalPoints.push(points[points.length - 1].clone());
  7382. for (var i = 0; i < totalPoints.length - 3; i++) {
  7383. amount = 0;
  7384. for (var c = 0; c < nbPoints; c++) {
  7385. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7386. amount += step;
  7387. }
  7388. }
  7389. i--;
  7390. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7391. }
  7392. return new Curve3(catmullRom);
  7393. };
  7394. /**
  7395. * Returns the Curve3 stored array of successive Vector3
  7396. */
  7397. Curve3.prototype.getPoints = function () {
  7398. return this._points;
  7399. };
  7400. /**
  7401. * Returns the computed length (float) of the curve.
  7402. */
  7403. Curve3.prototype.length = function () {
  7404. return this._length;
  7405. };
  7406. /**
  7407. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7408. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7409. * curveA and curveB keep unchanged.
  7410. */
  7411. Curve3.prototype.continue = function (curve) {
  7412. var lastPoint = this._points[this._points.length - 1];
  7413. var continuedPoints = this._points.slice();
  7414. var curvePoints = curve.getPoints();
  7415. for (var i = 1; i < curvePoints.length; i++) {
  7416. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7417. }
  7418. var continuedCurve = new Curve3(continuedPoints);
  7419. return continuedCurve;
  7420. };
  7421. Curve3.prototype._computeLength = function (path) {
  7422. var l = 0;
  7423. for (var i = 1; i < path.length; i++) {
  7424. l += (path[i].subtract(path[i - 1])).length();
  7425. }
  7426. return l;
  7427. };
  7428. return Curve3;
  7429. }());
  7430. BABYLON.Curve3 = Curve3;
  7431. // Vertex formats
  7432. var PositionNormalVertex = /** @class */ (function () {
  7433. function PositionNormalVertex(position, normal) {
  7434. if (position === void 0) { position = Vector3.Zero(); }
  7435. if (normal === void 0) { normal = Vector3.Up(); }
  7436. this.position = position;
  7437. this.normal = normal;
  7438. }
  7439. PositionNormalVertex.prototype.clone = function () {
  7440. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7441. };
  7442. return PositionNormalVertex;
  7443. }());
  7444. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7445. var PositionNormalTextureVertex = /** @class */ (function () {
  7446. function PositionNormalTextureVertex(position, normal, uv) {
  7447. if (position === void 0) { position = Vector3.Zero(); }
  7448. if (normal === void 0) { normal = Vector3.Up(); }
  7449. if (uv === void 0) { uv = Vector2.Zero(); }
  7450. this.position = position;
  7451. this.normal = normal;
  7452. this.uv = uv;
  7453. }
  7454. PositionNormalTextureVertex.prototype.clone = function () {
  7455. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7456. };
  7457. return PositionNormalTextureVertex;
  7458. }());
  7459. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7460. // Temporary pre-allocated objects for engine internal use
  7461. // usage in any internal function :
  7462. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7463. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7464. var Tmp = /** @class */ (function () {
  7465. function Tmp() {
  7466. }
  7467. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7468. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7469. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7470. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7471. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7472. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7473. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7474. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7475. Matrix.Zero(), Matrix.Zero(),
  7476. Matrix.Zero(), Matrix.Zero(),
  7477. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7478. return Tmp;
  7479. }());
  7480. BABYLON.Tmp = Tmp;
  7481. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7482. var MathTmp = /** @class */ (function () {
  7483. function MathTmp() {
  7484. }
  7485. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7486. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7487. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7488. return MathTmp;
  7489. }());
  7490. })(BABYLON || (BABYLON = {}));
  7491. //# sourceMappingURL=babylon.math.js.map
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var Scalar = /** @class */ (function () {
  7495. function Scalar() {
  7496. }
  7497. /**
  7498. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7499. */
  7500. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7501. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7502. var num = a - b;
  7503. return -epsilon <= num && num <= epsilon;
  7504. };
  7505. /**
  7506. * Returns a string : the upper case translation of the number i to hexadecimal.
  7507. */
  7508. Scalar.ToHex = function (i) {
  7509. var str = i.toString(16);
  7510. if (i <= 15) {
  7511. return ("0" + str).toUpperCase();
  7512. }
  7513. return str.toUpperCase();
  7514. };
  7515. /**
  7516. * Returns -1 if value is negative and +1 is value is positive.
  7517. * Returns the value itself if it's equal to zero.
  7518. */
  7519. Scalar.Sign = function (value) {
  7520. value = +value; // convert to a number
  7521. if (value === 0 || isNaN(value))
  7522. return value;
  7523. return value > 0 ? 1 : -1;
  7524. };
  7525. /**
  7526. * Returns the value itself if it's between min and max.
  7527. * Returns min if the value is lower than min.
  7528. * Returns max if the value is greater than max.
  7529. */
  7530. Scalar.Clamp = function (value, min, max) {
  7531. if (min === void 0) { min = 0; }
  7532. if (max === void 0) { max = 1; }
  7533. return Math.min(max, Math.max(min, value));
  7534. };
  7535. /**
  7536. * Returns the log2 of value.
  7537. */
  7538. Scalar.Log2 = function (value) {
  7539. return Math.log(value) * Math.LOG2E;
  7540. };
  7541. /**
  7542. * Loops the value, so that it is never larger than length and never smaller than 0.
  7543. *
  7544. * This is similar to the modulo operator but it works with floating point numbers.
  7545. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7546. * With t = 5 and length = 2.5, the result would be 0.0.
  7547. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7548. */
  7549. Scalar.Repeat = function (value, length) {
  7550. return value - Math.floor(value / length) * length;
  7551. };
  7552. /**
  7553. * Normalize the value between 0.0 and 1.0 using min and max values
  7554. */
  7555. Scalar.Normalize = function (value, min, max) {
  7556. return (value - min) / (max - min);
  7557. };
  7558. /**
  7559. * Denormalize the value from 0.0 and 1.0 using min and max values
  7560. */
  7561. Scalar.Denormalize = function (normalized, min, max) {
  7562. return (normalized * (max - min) + min);
  7563. };
  7564. /**
  7565. * Calculates the shortest difference between two given angles given in degrees.
  7566. */
  7567. Scalar.DeltaAngle = function (current, target) {
  7568. var num = Scalar.Repeat(target - current, 360.0);
  7569. if (num > 180.0) {
  7570. num -= 360.0;
  7571. }
  7572. return num;
  7573. };
  7574. /**
  7575. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7576. *
  7577. * The returned value will move back and forth between 0 and length
  7578. */
  7579. Scalar.PingPong = function (tx, length) {
  7580. var t = Scalar.Repeat(tx, length * 2.0);
  7581. return length - Math.abs(t - length);
  7582. };
  7583. /**
  7584. * Interpolates between min and max with smoothing at the limits.
  7585. *
  7586. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7587. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7588. */
  7589. Scalar.SmoothStep = function (from, to, tx) {
  7590. var t = Scalar.Clamp(tx);
  7591. t = -2.0 * t * t * t + 3.0 * t * t;
  7592. return to * t + from * (1.0 - t);
  7593. };
  7594. /**
  7595. * Moves a value current towards target.
  7596. *
  7597. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7598. * Negative values of maxDelta pushes the value away from target.
  7599. */
  7600. Scalar.MoveTowards = function (current, target, maxDelta) {
  7601. var result = 0;
  7602. if (Math.abs(target - current) <= maxDelta) {
  7603. result = target;
  7604. }
  7605. else {
  7606. result = current + Scalar.Sign(target - current) * maxDelta;
  7607. }
  7608. return result;
  7609. };
  7610. /**
  7611. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7612. *
  7613. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7614. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7615. */
  7616. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7617. var num = Scalar.DeltaAngle(current, target);
  7618. var result = 0;
  7619. if (-maxDelta < num && num < maxDelta) {
  7620. result = target;
  7621. }
  7622. else {
  7623. target = current + num;
  7624. result = Scalar.MoveTowards(current, target, maxDelta);
  7625. }
  7626. return result;
  7627. };
  7628. /**
  7629. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7630. */
  7631. Scalar.Lerp = function (start, end, amount) {
  7632. return start + ((end - start) * amount);
  7633. };
  7634. /**
  7635. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7637. */
  7638. Scalar.LerpAngle = function (start, end, amount) {
  7639. var num = Scalar.Repeat(end - start, 360.0);
  7640. if (num > 180.0) {
  7641. num -= 360.0;
  7642. }
  7643. return start + num * Scalar.Clamp(amount);
  7644. };
  7645. /**
  7646. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7647. */
  7648. Scalar.InverseLerp = function (a, b, value) {
  7649. var result = 0;
  7650. if (a != b) {
  7651. result = Scalar.Clamp((value - a) / (b - a));
  7652. }
  7653. else {
  7654. result = 0.0;
  7655. }
  7656. return result;
  7657. };
  7658. /**
  7659. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7660. */
  7661. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7662. var squared = amount * amount;
  7663. var cubed = amount * squared;
  7664. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7665. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7666. var part3 = (cubed - (2.0 * squared)) + amount;
  7667. var part4 = cubed - squared;
  7668. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7669. };
  7670. /**
  7671. * Returns a random float number between and min and max values
  7672. */
  7673. Scalar.RandomRange = function (min, max) {
  7674. if (min === max)
  7675. return min;
  7676. return ((Math.random() * (max - min)) + min);
  7677. };
  7678. /**
  7679. * This function returns percentage of a number in a given range.
  7680. *
  7681. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7682. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7683. */
  7684. Scalar.RangeToPercent = function (number, min, max) {
  7685. return ((number - min) / (max - min));
  7686. };
  7687. /**
  7688. * This function returns number that corresponds to the percentage in a given range.
  7689. *
  7690. * PercentToRange(0.34,0,100) will return 34.
  7691. */
  7692. Scalar.PercentToRange = function (percent, min, max) {
  7693. return ((max - min) * percent + min);
  7694. };
  7695. /**
  7696. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7697. * @param angle The angle to normalize in radian.
  7698. * @return The converted angle.
  7699. */
  7700. Scalar.NormalizeRadians = function (angle) {
  7701. // More precise but slower version kept for reference.
  7702. // angle = angle % Tools.TwoPi;
  7703. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7704. //if (angle > Math.PI) {
  7705. // angle -= Tools.TwoPi;
  7706. //}
  7707. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7708. return angle;
  7709. };
  7710. /**
  7711. * Two pi constants convenient for computation.
  7712. */
  7713. Scalar.TwoPi = Math.PI * 2;
  7714. return Scalar;
  7715. }());
  7716. BABYLON.Scalar = Scalar;
  7717. })(BABYLON || (BABYLON = {}));
  7718. //# sourceMappingURL=babylon.math.scalar.js.map
  7719. //# sourceMappingURL=babylon.mixins.js.map
  7720. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7721. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7722. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7723. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7724. //# sourceMappingURL=babylon.webgl2.js.map
  7725. var BABYLON;
  7726. (function (BABYLON) {
  7727. var __decoratorInitialStore = {};
  7728. var __mergedStore = {};
  7729. var _copySource = function (creationFunction, source, instanciate) {
  7730. var destination = creationFunction();
  7731. // Tags
  7732. if (BABYLON.Tags) {
  7733. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7734. }
  7735. var classStore = getMergedStore(destination);
  7736. // Properties
  7737. for (var property in classStore) {
  7738. var propertyDescriptor = classStore[property];
  7739. var sourceProperty = source[property];
  7740. var propertyType = propertyDescriptor.type;
  7741. if (sourceProperty !== undefined && sourceProperty !== null) {
  7742. switch (propertyType) {
  7743. case 0: // Value
  7744. case 6: // Mesh reference
  7745. case 11: // Camera reference
  7746. destination[property] = sourceProperty;
  7747. break;
  7748. case 1: // Texture
  7749. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7750. break;
  7751. case 2: // Color3
  7752. case 3: // FresnelParameters
  7753. case 4: // Vector2
  7754. case 5: // Vector3
  7755. case 7: // Color Curves
  7756. case 10: // Quaternion
  7757. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7758. break;
  7759. }
  7760. }
  7761. }
  7762. return destination;
  7763. };
  7764. function getDirectStore(target) {
  7765. var classKey = target.getClassName();
  7766. if (!__decoratorInitialStore[classKey]) {
  7767. __decoratorInitialStore[classKey] = {};
  7768. }
  7769. return __decoratorInitialStore[classKey];
  7770. }
  7771. /**
  7772. * Return the list of properties flagged as serializable
  7773. * @param target: host object
  7774. */
  7775. function getMergedStore(target) {
  7776. var classKey = target.getClassName();
  7777. if (__mergedStore[classKey]) {
  7778. return __mergedStore[classKey];
  7779. }
  7780. __mergedStore[classKey] = {};
  7781. var store = __mergedStore[classKey];
  7782. var currentTarget = target;
  7783. var currentKey = classKey;
  7784. while (currentKey) {
  7785. var initialStore = __decoratorInitialStore[currentKey];
  7786. for (var property in initialStore) {
  7787. store[property] = initialStore[property];
  7788. }
  7789. var parent_1 = void 0;
  7790. var done = false;
  7791. do {
  7792. parent_1 = Object.getPrototypeOf(currentTarget);
  7793. if (!parent_1.getClassName) {
  7794. done = true;
  7795. break;
  7796. }
  7797. if (parent_1.getClassName() !== currentKey) {
  7798. break;
  7799. }
  7800. currentTarget = parent_1;
  7801. } while (parent_1);
  7802. if (done) {
  7803. break;
  7804. }
  7805. currentKey = parent_1.getClassName();
  7806. currentTarget = parent_1;
  7807. }
  7808. return store;
  7809. }
  7810. function generateSerializableMember(type, sourceName) {
  7811. return function (target, propertyKey) {
  7812. var classStore = getDirectStore(target);
  7813. if (!classStore[propertyKey]) {
  7814. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7815. }
  7816. };
  7817. }
  7818. function generateExpandMember(setCallback, targetKey) {
  7819. if (targetKey === void 0) { targetKey = null; }
  7820. return function (target, propertyKey) {
  7821. var key = targetKey || ("_" + propertyKey);
  7822. Object.defineProperty(target, propertyKey, {
  7823. get: function () {
  7824. return this[key];
  7825. },
  7826. set: function (value) {
  7827. if (this[key] === value) {
  7828. return;
  7829. }
  7830. this[key] = value;
  7831. target[setCallback].apply(this);
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. };
  7837. }
  7838. function expandToProperty(callback, targetKey) {
  7839. if (targetKey === void 0) { targetKey = null; }
  7840. return generateExpandMember(callback, targetKey);
  7841. }
  7842. BABYLON.expandToProperty = expandToProperty;
  7843. function serialize(sourceName) {
  7844. return generateSerializableMember(0, sourceName); // value member
  7845. }
  7846. BABYLON.serialize = serialize;
  7847. function serializeAsTexture(sourceName) {
  7848. return generateSerializableMember(1, sourceName); // texture member
  7849. }
  7850. BABYLON.serializeAsTexture = serializeAsTexture;
  7851. function serializeAsColor3(sourceName) {
  7852. return generateSerializableMember(2, sourceName); // color3 member
  7853. }
  7854. BABYLON.serializeAsColor3 = serializeAsColor3;
  7855. function serializeAsFresnelParameters(sourceName) {
  7856. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7857. }
  7858. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7859. function serializeAsVector2(sourceName) {
  7860. return generateSerializableMember(4, sourceName); // vector2 member
  7861. }
  7862. BABYLON.serializeAsVector2 = serializeAsVector2;
  7863. function serializeAsVector3(sourceName) {
  7864. return generateSerializableMember(5, sourceName); // vector3 member
  7865. }
  7866. BABYLON.serializeAsVector3 = serializeAsVector3;
  7867. function serializeAsMeshReference(sourceName) {
  7868. return generateSerializableMember(6, sourceName); // mesh reference member
  7869. }
  7870. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7871. function serializeAsColorCurves(sourceName) {
  7872. return generateSerializableMember(7, sourceName); // color curves
  7873. }
  7874. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7875. function serializeAsColor4(sourceName) {
  7876. return generateSerializableMember(8, sourceName); // color 4
  7877. }
  7878. BABYLON.serializeAsColor4 = serializeAsColor4;
  7879. function serializeAsImageProcessingConfiguration(sourceName) {
  7880. return generateSerializableMember(9, sourceName); // image processing
  7881. }
  7882. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7883. function serializeAsQuaternion(sourceName) {
  7884. return generateSerializableMember(10, sourceName); // quaternion member
  7885. }
  7886. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7887. /**
  7888. * Decorator used to define property that can be serialized as reference to a camera
  7889. * @param sourceName defines the name of the property to decorate
  7890. */
  7891. function serializeAsCameraReference(sourceName) {
  7892. return generateSerializableMember(11, sourceName); // camera reference member
  7893. }
  7894. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7895. var SerializationHelper = /** @class */ (function () {
  7896. function SerializationHelper() {
  7897. }
  7898. SerializationHelper.Serialize = function (entity, serializationObject) {
  7899. if (!serializationObject) {
  7900. serializationObject = {};
  7901. }
  7902. // Tags
  7903. if (BABYLON.Tags) {
  7904. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7905. }
  7906. var serializedProperties = getMergedStore(entity);
  7907. // Properties
  7908. for (var property in serializedProperties) {
  7909. var propertyDescriptor = serializedProperties[property];
  7910. var targetPropertyName = propertyDescriptor.sourceName || property;
  7911. var propertyType = propertyDescriptor.type;
  7912. var sourceProperty = entity[property];
  7913. if (sourceProperty !== undefined && sourceProperty !== null) {
  7914. switch (propertyType) {
  7915. case 0: // Value
  7916. serializationObject[targetPropertyName] = sourceProperty;
  7917. break;
  7918. case 1: // Texture
  7919. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7920. break;
  7921. case 2: // Color3
  7922. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7923. break;
  7924. case 3: // FresnelParameters
  7925. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7926. break;
  7927. case 4: // Vector2
  7928. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7929. break;
  7930. case 5: // Vector3
  7931. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7932. break;
  7933. case 6: // Mesh reference
  7934. serializationObject[targetPropertyName] = sourceProperty.id;
  7935. break;
  7936. case 7: // Color Curves
  7937. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7938. break;
  7939. case 8: // Color 4
  7940. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7941. break;
  7942. case 9: // Image Processing
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 10: // Quaternion
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 11: // Camera reference
  7949. serializationObject[targetPropertyName] = sourceProperty.id;
  7950. break;
  7951. }
  7952. }
  7953. }
  7954. return serializationObject;
  7955. };
  7956. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7957. if (rootUrl === void 0) { rootUrl = null; }
  7958. var destination = creationFunction();
  7959. if (!rootUrl) {
  7960. rootUrl = "";
  7961. }
  7962. // Tags
  7963. if (BABYLON.Tags) {
  7964. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7965. }
  7966. var classStore = getMergedStore(destination);
  7967. // Properties
  7968. for (var property in classStore) {
  7969. var propertyDescriptor = classStore[property];
  7970. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7971. var propertyType = propertyDescriptor.type;
  7972. if (sourceProperty !== undefined && sourceProperty !== null) {
  7973. var dest = destination;
  7974. switch (propertyType) {
  7975. case 0: // Value
  7976. dest[property] = sourceProperty;
  7977. break;
  7978. case 1: // Texture
  7979. if (scene) {
  7980. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7981. }
  7982. break;
  7983. case 2: // Color3
  7984. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7985. break;
  7986. case 3: // FresnelParameters
  7987. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7988. break;
  7989. case 4: // Vector2
  7990. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7991. break;
  7992. case 5: // Vector3
  7993. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7994. break;
  7995. case 6: // Mesh reference
  7996. if (scene) {
  7997. dest[property] = scene.getLastMeshByID(sourceProperty);
  7998. }
  7999. break;
  8000. case 7: // Color Curves
  8001. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8002. break;
  8003. case 8: // Color 4
  8004. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8005. break;
  8006. case 9: // Image Processing
  8007. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8008. break;
  8009. case 10: // Quaternion
  8010. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8011. break;
  8012. case 11: // Camera reference
  8013. if (scene) {
  8014. dest[property] = scene.getCameraByID(sourceProperty);
  8015. }
  8016. break;
  8017. }
  8018. }
  8019. }
  8020. return destination;
  8021. };
  8022. SerializationHelper.Clone = function (creationFunction, source) {
  8023. return _copySource(creationFunction, source, false);
  8024. };
  8025. SerializationHelper.Instanciate = function (creationFunction, source) {
  8026. return _copySource(creationFunction, source, true);
  8027. };
  8028. return SerializationHelper;
  8029. }());
  8030. BABYLON.SerializationHelper = SerializationHelper;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.decorators.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * Wrapper class for promise with external resolve and reject.
  8037. */
  8038. var Deferred = /** @class */ (function () {
  8039. /**
  8040. * Constructor for this deferred object.
  8041. */
  8042. function Deferred() {
  8043. var _this = this;
  8044. this.promise = new Promise(function (resolve, reject) {
  8045. _this._resolve = resolve;
  8046. _this._reject = reject;
  8047. });
  8048. }
  8049. Object.defineProperty(Deferred.prototype, "resolve", {
  8050. /**
  8051. * The resolve method of the promise associated with this deferred object.
  8052. */
  8053. get: function () {
  8054. return this._resolve;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Deferred.prototype, "reject", {
  8060. /**
  8061. * The reject method of the promise associated with this deferred object.
  8062. */
  8063. get: function () {
  8064. return this._reject;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. return Deferred;
  8070. }());
  8071. BABYLON.Deferred = Deferred;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.deferred.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * A class serves as a medium between the observable and its observers
  8078. */
  8079. var EventState = /** @class */ (function () {
  8080. /**
  8081. * Create a new EventState
  8082. * @param mask defines the mask associated with this state
  8083. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8084. * @param target defines the original target of the state
  8085. * @param currentTarget defines the current target of the state
  8086. */
  8087. function EventState(mask, skipNextObservers, target, currentTarget) {
  8088. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8089. this.initalize(mask, skipNextObservers, target, currentTarget);
  8090. }
  8091. /**
  8092. * Initialize the current event state
  8093. * @param mask defines the mask associated with this state
  8094. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8095. * @param target defines the original target of the state
  8096. * @param currentTarget defines the current target of the state
  8097. * @returns the current event state
  8098. */
  8099. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8100. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8101. this.mask = mask;
  8102. this.skipNextObservers = skipNextObservers;
  8103. this.target = target;
  8104. this.currentTarget = currentTarget;
  8105. return this;
  8106. };
  8107. return EventState;
  8108. }());
  8109. BABYLON.EventState = EventState;
  8110. /**
  8111. * Represent an Observer registered to a given Observable object.
  8112. */
  8113. var Observer = /** @class */ (function () {
  8114. /**
  8115. * Creates a new observer
  8116. * @param callback defines the callback to call when the observer is notified
  8117. * @param mask defines the mask of the observer (used to filter notifications)
  8118. * @param scope defines the current scope used to restore the JS context
  8119. */
  8120. function Observer(
  8121. /**
  8122. * Defines the callback to call when the observer is notified
  8123. */
  8124. callback,
  8125. /**
  8126. * Defines the mask of the observer (used to filter notifications)
  8127. */
  8128. mask,
  8129. /**
  8130. * Defines the current scope used to restore the JS context
  8131. */
  8132. scope) {
  8133. if (scope === void 0) { scope = null; }
  8134. this.callback = callback;
  8135. this.mask = mask;
  8136. this.scope = scope;
  8137. /** @hidden */
  8138. this._willBeUnregistered = false;
  8139. /**
  8140. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8141. */
  8142. this.unregisterOnNextCall = false;
  8143. }
  8144. return Observer;
  8145. }());
  8146. BABYLON.Observer = Observer;
  8147. /**
  8148. * Represent a list of observers registered to multiple Observables object.
  8149. */
  8150. var MultiObserver = /** @class */ (function () {
  8151. function MultiObserver() {
  8152. }
  8153. /**
  8154. * Release associated resources
  8155. */
  8156. MultiObserver.prototype.dispose = function () {
  8157. if (this._observers && this._observables) {
  8158. for (var index = 0; index < this._observers.length; index++) {
  8159. this._observables[index].remove(this._observers[index]);
  8160. }
  8161. }
  8162. this._observers = null;
  8163. this._observables = null;
  8164. };
  8165. /**
  8166. * Raise a callback when one of the observable will notify
  8167. * @param observables defines a list of observables to watch
  8168. * @param callback defines the callback to call on notification
  8169. * @param mask defines the mask used to filter notifications
  8170. * @param scope defines the current scope used to restore the JS context
  8171. * @returns the new MultiObserver
  8172. */
  8173. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8174. if (mask === void 0) { mask = -1; }
  8175. if (scope === void 0) { scope = null; }
  8176. var result = new MultiObserver();
  8177. result._observers = new Array();
  8178. result._observables = observables;
  8179. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8180. var observable = observables_1[_i];
  8181. var observer = observable.add(callback, mask, false, scope);
  8182. if (observer) {
  8183. result._observers.push(observer);
  8184. }
  8185. }
  8186. return result;
  8187. };
  8188. return MultiObserver;
  8189. }());
  8190. BABYLON.MultiObserver = MultiObserver;
  8191. /**
  8192. * The Observable class is a simple implementation of the Observable pattern.
  8193. *
  8194. * 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.
  8195. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8196. * 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).
  8197. * 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.
  8198. */
  8199. var Observable = /** @class */ (function () {
  8200. /**
  8201. * Creates a new observable
  8202. * @param onObserverAdded defines a callback to call when a new observer is added
  8203. */
  8204. function Observable(onObserverAdded) {
  8205. this._observers = new Array();
  8206. this._eventState = new EventState(0);
  8207. if (onObserverAdded) {
  8208. this._onObserverAdded = onObserverAdded;
  8209. }
  8210. }
  8211. /**
  8212. * Create a new Observer with the specified callback
  8213. * @param callback the callback that will be executed for that Observer
  8214. * @param mask the mask used to filter observers
  8215. * @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.
  8216. * @param scope optional scope for the callback to be called from
  8217. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8218. * @returns the new observer created for the callback
  8219. */
  8220. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8221. if (mask === void 0) { mask = -1; }
  8222. if (insertFirst === void 0) { insertFirst = false; }
  8223. if (scope === void 0) { scope = null; }
  8224. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8225. if (!callback) {
  8226. return null;
  8227. }
  8228. var observer = new Observer(callback, mask, scope);
  8229. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8230. if (insertFirst) {
  8231. this._observers.unshift(observer);
  8232. }
  8233. else {
  8234. this._observers.push(observer);
  8235. }
  8236. if (this._onObserverAdded) {
  8237. this._onObserverAdded(observer);
  8238. }
  8239. return observer;
  8240. };
  8241. /**
  8242. * Create a new Observer with the specified callback and unregisters after the next notification
  8243. * @param callback the callback that will be executed for that Observer
  8244. * @returns the new observer created for the callback
  8245. */
  8246. Observable.prototype.addOnce = function (callback) {
  8247. return this.add(callback, undefined, undefined, undefined, true);
  8248. };
  8249. /**
  8250. * Remove an Observer from the Observable object
  8251. * @param observer the instance of the Observer to remove
  8252. * @returns false if it doesn't belong to this Observable
  8253. */
  8254. Observable.prototype.remove = function (observer) {
  8255. if (!observer) {
  8256. return false;
  8257. }
  8258. var index = this._observers.indexOf(observer);
  8259. if (index !== -1) {
  8260. this._deferUnregister(observer);
  8261. return true;
  8262. }
  8263. return false;
  8264. };
  8265. /**
  8266. * Remove a callback from the Observable object
  8267. * @param callback the callback to remove
  8268. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8269. * @returns false if it doesn't belong to this Observable
  8270. */
  8271. Observable.prototype.removeCallback = function (callback, scope) {
  8272. for (var index = 0; index < this._observers.length; index++) {
  8273. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8274. this._deferUnregister(this._observers[index]);
  8275. return true;
  8276. }
  8277. }
  8278. return false;
  8279. };
  8280. Observable.prototype._deferUnregister = function (observer) {
  8281. var _this = this;
  8282. observer.unregisterOnNextCall = false;
  8283. observer._willBeUnregistered = true;
  8284. BABYLON.Tools.SetImmediate(function () {
  8285. _this._remove(observer);
  8286. });
  8287. };
  8288. // This should only be called when not iterating over _observers to avoid callback skipping.
  8289. // Removes an observer from the _observer Array.
  8290. Observable.prototype._remove = function (observer) {
  8291. if (!observer) {
  8292. return false;
  8293. }
  8294. var index = this._observers.indexOf(observer);
  8295. if (index !== -1) {
  8296. this._observers.splice(index, 1);
  8297. return true;
  8298. }
  8299. return false;
  8300. };
  8301. /**
  8302. * Notify all Observers by calling their respective callback with the given data
  8303. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8304. * @param eventData defines the data to send to all observers
  8305. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8306. * @param target defines the original target of the state
  8307. * @param currentTarget defines the current target of the state
  8308. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8309. */
  8310. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8311. if (mask === void 0) { mask = -1; }
  8312. if (!this._observers.length) {
  8313. return true;
  8314. }
  8315. var state = this._eventState;
  8316. state.mask = mask;
  8317. state.target = target;
  8318. state.currentTarget = currentTarget;
  8319. state.skipNextObservers = false;
  8320. state.lastReturnValue = eventData;
  8321. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8322. var obs = _a[_i];
  8323. if (obs._willBeUnregistered) {
  8324. continue;
  8325. }
  8326. if (obs.mask & mask) {
  8327. if (obs.scope) {
  8328. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8329. }
  8330. else {
  8331. state.lastReturnValue = obs.callback(eventData, state);
  8332. }
  8333. if (obs.unregisterOnNextCall) {
  8334. this._deferUnregister(obs);
  8335. }
  8336. }
  8337. if (state.skipNextObservers) {
  8338. return false;
  8339. }
  8340. }
  8341. return true;
  8342. };
  8343. /**
  8344. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8345. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8346. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8347. * and it is crucial that all callbacks will be executed.
  8348. * The order of the callbacks is kept, callbacks are not executed parallel.
  8349. *
  8350. * @param eventData The data to be sent to each callback
  8351. * @param mask is used to filter observers defaults to -1
  8352. * @param target defines the callback target (see EventState)
  8353. * @param currentTarget defines he current object in the bubbling phase
  8354. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8355. */
  8356. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8357. var _this = this;
  8358. if (mask === void 0) { mask = -1; }
  8359. // create an empty promise
  8360. var p = Promise.resolve(eventData);
  8361. // no observers? return this promise.
  8362. if (!this._observers.length) {
  8363. return p;
  8364. }
  8365. var state = this._eventState;
  8366. state.mask = mask;
  8367. state.target = target;
  8368. state.currentTarget = currentTarget;
  8369. state.skipNextObservers = false;
  8370. // execute one callback after another (not using Promise.all, the order is important)
  8371. this._observers.forEach(function (obs) {
  8372. if (state.skipNextObservers) {
  8373. return;
  8374. }
  8375. if (obs._willBeUnregistered) {
  8376. return;
  8377. }
  8378. if (obs.mask & mask) {
  8379. if (obs.scope) {
  8380. p = p.then(function (lastReturnedValue) {
  8381. state.lastReturnValue = lastReturnedValue;
  8382. return obs.callback.apply(obs.scope, [eventData, state]);
  8383. });
  8384. }
  8385. else {
  8386. p = p.then(function (lastReturnedValue) {
  8387. state.lastReturnValue = lastReturnedValue;
  8388. return obs.callback(eventData, state);
  8389. });
  8390. }
  8391. if (obs.unregisterOnNextCall) {
  8392. _this._deferUnregister(obs);
  8393. }
  8394. }
  8395. });
  8396. // return the eventData
  8397. return p.then(function () { return eventData; });
  8398. };
  8399. /**
  8400. * Notify a specific observer
  8401. * @param observer defines the observer to notify
  8402. * @param eventData defines the data to be sent to each callback
  8403. * @param mask is used to filter observers defaults to -1
  8404. */
  8405. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8406. if (mask === void 0) { mask = -1; }
  8407. var state = this._eventState;
  8408. state.mask = mask;
  8409. state.skipNextObservers = false;
  8410. observer.callback(eventData, state);
  8411. };
  8412. /**
  8413. * Gets a boolean indicating if the observable has at least one observer
  8414. * @returns true is the Observable has at least one Observer registered
  8415. */
  8416. Observable.prototype.hasObservers = function () {
  8417. return this._observers.length > 0;
  8418. };
  8419. /**
  8420. * Clear the list of observers
  8421. */
  8422. Observable.prototype.clear = function () {
  8423. this._observers = new Array();
  8424. this._onObserverAdded = null;
  8425. };
  8426. /**
  8427. * Clone the current observable
  8428. * @returns a new observable
  8429. */
  8430. Observable.prototype.clone = function () {
  8431. var result = new Observable();
  8432. result._observers = this._observers.slice(0);
  8433. return result;
  8434. };
  8435. /**
  8436. * Does this observable handles observer registered with a given mask
  8437. * @param mask defines the mask to be tested
  8438. * @return whether or not one observer registered with the given mask is handeled
  8439. **/
  8440. Observable.prototype.hasSpecificMask = function (mask) {
  8441. if (mask === void 0) { mask = -1; }
  8442. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8443. var obs = _a[_i];
  8444. if (obs.mask & mask || obs.mask === mask) {
  8445. return true;
  8446. }
  8447. }
  8448. return false;
  8449. };
  8450. return Observable;
  8451. }());
  8452. BABYLON.Observable = Observable;
  8453. })(BABYLON || (BABYLON = {}));
  8454. //# sourceMappingURL=babylon.observable.js.map
  8455. var BABYLON;
  8456. (function (BABYLON) {
  8457. var SmartArray = /** @class */ (function () {
  8458. function SmartArray(capacity) {
  8459. this.length = 0;
  8460. this.data = new Array(capacity);
  8461. this._id = SmartArray._GlobalId++;
  8462. }
  8463. SmartArray.prototype.push = function (value) {
  8464. this.data[this.length++] = value;
  8465. if (this.length > this.data.length) {
  8466. this.data.length *= 2;
  8467. }
  8468. };
  8469. SmartArray.prototype.forEach = function (func) {
  8470. for (var index = 0; index < this.length; index++) {
  8471. func(this.data[index]);
  8472. }
  8473. };
  8474. SmartArray.prototype.sort = function (compareFn) {
  8475. this.data.sort(compareFn);
  8476. };
  8477. SmartArray.prototype.reset = function () {
  8478. this.length = 0;
  8479. };
  8480. SmartArray.prototype.dispose = function () {
  8481. this.reset();
  8482. if (this.data) {
  8483. this.data.length = 0;
  8484. this.data = [];
  8485. }
  8486. };
  8487. SmartArray.prototype.concat = function (array) {
  8488. if (array.length === 0) {
  8489. return;
  8490. }
  8491. if (this.length + array.length > this.data.length) {
  8492. this.data.length = (this.length + array.length) * 2;
  8493. }
  8494. for (var index = 0; index < array.length; index++) {
  8495. this.data[this.length++] = (array.data || array)[index];
  8496. }
  8497. };
  8498. SmartArray.prototype.indexOf = function (value) {
  8499. var position = this.data.indexOf(value);
  8500. if (position >= this.length) {
  8501. return -1;
  8502. }
  8503. return position;
  8504. };
  8505. SmartArray.prototype.contains = function (value) {
  8506. return this.data.indexOf(value) !== -1;
  8507. };
  8508. // Statics
  8509. SmartArray._GlobalId = 0;
  8510. return SmartArray;
  8511. }());
  8512. BABYLON.SmartArray = SmartArray;
  8513. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8514. __extends(SmartArrayNoDuplicate, _super);
  8515. function SmartArrayNoDuplicate() {
  8516. var _this = _super !== null && _super.apply(this, arguments) || this;
  8517. _this._duplicateId = 0;
  8518. return _this;
  8519. }
  8520. SmartArrayNoDuplicate.prototype.push = function (value) {
  8521. _super.prototype.push.call(this, value);
  8522. if (!value.__smartArrayFlags) {
  8523. value.__smartArrayFlags = {};
  8524. }
  8525. value.__smartArrayFlags[this._id] = this._duplicateId;
  8526. };
  8527. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8528. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8529. return false;
  8530. }
  8531. this.push(value);
  8532. return true;
  8533. };
  8534. SmartArrayNoDuplicate.prototype.reset = function () {
  8535. _super.prototype.reset.call(this);
  8536. this._duplicateId++;
  8537. };
  8538. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8539. if (array.length === 0) {
  8540. return;
  8541. }
  8542. if (this.length + array.length > this.data.length) {
  8543. this.data.length = (this.length + array.length) * 2;
  8544. }
  8545. for (var index = 0; index < array.length; index++) {
  8546. var item = (array.data || array)[index];
  8547. this.pushNoDuplicate(item);
  8548. }
  8549. };
  8550. return SmartArrayNoDuplicate;
  8551. }(SmartArray));
  8552. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8553. })(BABYLON || (BABYLON = {}));
  8554. //# sourceMappingURL=babylon.smartArray.js.map
  8555. var BABYLON;
  8556. (function (BABYLON) {
  8557. /** Class used to store color gradient */
  8558. var ColorGradient = /** @class */ (function () {
  8559. function ColorGradient() {
  8560. }
  8561. /**
  8562. * Will get a color picked randomly between color1 and color2.
  8563. * If color2 is undefined then color1 will be used
  8564. * @param result defines the target Color4 to store the result in
  8565. */
  8566. ColorGradient.prototype.getColorToRef = function (result) {
  8567. if (!this.color2) {
  8568. result.copyFrom(this.color1);
  8569. return;
  8570. }
  8571. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8572. };
  8573. return ColorGradient;
  8574. }());
  8575. BABYLON.ColorGradient = ColorGradient;
  8576. /** Class used to store factor gradient */
  8577. var FactorGradient = /** @class */ (function () {
  8578. function FactorGradient() {
  8579. }
  8580. /**
  8581. * Will get a number picked randomly between factor1 and factor2.
  8582. * If factor2 is undefined then factor1 will be used
  8583. * @returns the picked number
  8584. */
  8585. FactorGradient.prototype.getFactor = function () {
  8586. if (this.factor2 === undefined) {
  8587. return this.factor1;
  8588. }
  8589. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8590. };
  8591. return FactorGradient;
  8592. }());
  8593. BABYLON.FactorGradient = FactorGradient;
  8594. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8595. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8596. var LoadFileError = /** @class */ (function (_super) {
  8597. __extends(LoadFileError, _super);
  8598. function LoadFileError(message, request) {
  8599. var _this = _super.call(this, message) || this;
  8600. _this.request = request;
  8601. _this.name = "LoadFileError";
  8602. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8603. return _this;
  8604. }
  8605. // Polyfill for Object.setPrototypeOf if necessary.
  8606. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8607. return LoadFileError;
  8608. }(Error));
  8609. BABYLON.LoadFileError = LoadFileError;
  8610. var RetryStrategy = /** @class */ (function () {
  8611. function RetryStrategy() {
  8612. }
  8613. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8614. if (maxRetries === void 0) { maxRetries = 3; }
  8615. if (baseInterval === void 0) { baseInterval = 500; }
  8616. return function (url, request, retryIndex) {
  8617. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8618. return -1;
  8619. }
  8620. return Math.pow(2, retryIndex) * baseInterval;
  8621. };
  8622. };
  8623. return RetryStrategy;
  8624. }());
  8625. BABYLON.RetryStrategy = RetryStrategy;
  8626. // Screenshots
  8627. var screenshotCanvas;
  8628. var cloneValue = function (source, destinationObject) {
  8629. if (!source)
  8630. return null;
  8631. if (source instanceof BABYLON.Mesh) {
  8632. return null;
  8633. }
  8634. if (source instanceof BABYLON.SubMesh) {
  8635. return source.clone(destinationObject);
  8636. }
  8637. else if (source.clone) {
  8638. return source.clone();
  8639. }
  8640. return null;
  8641. };
  8642. var Tools = /** @class */ (function () {
  8643. function Tools() {
  8644. }
  8645. /**
  8646. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8647. * @param u defines the coordinate on X axis
  8648. * @param v defines the coordinate on Y axis
  8649. * @param width defines the width of the source data
  8650. * @param height defines the height of the source data
  8651. * @param pixels defines the source byte array
  8652. * @param color defines the output color
  8653. */
  8654. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8655. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8656. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8657. var position = (wrappedU + wrappedV * width) * 4;
  8658. color.r = pixels[position] / 255;
  8659. color.g = pixels[position + 1] / 255;
  8660. color.b = pixels[position + 2] / 255;
  8661. color.a = pixels[position + 3] / 255;
  8662. };
  8663. /**
  8664. * Interpolates between a and b via alpha
  8665. * @param a The lower value (returned when alpha = 0)
  8666. * @param b The upper value (returned when alpha = 1)
  8667. * @param alpha The interpolation-factor
  8668. * @return The mixed value
  8669. */
  8670. Tools.Mix = function (a, b, alpha) {
  8671. return a * (1 - alpha) + b * alpha;
  8672. };
  8673. Tools.Instantiate = function (className) {
  8674. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8675. return Tools.RegisteredExternalClasses[className];
  8676. }
  8677. var arr = className.split(".");
  8678. var fn = (window || this);
  8679. for (var i = 0, len = arr.length; i < len; i++) {
  8680. fn = fn[arr[i]];
  8681. }
  8682. if (typeof fn !== "function") {
  8683. return null;
  8684. }
  8685. return fn;
  8686. };
  8687. /**
  8688. * Provides a slice function that will work even on IE
  8689. * @param data defines the array to slice
  8690. * @param start defines the start of the data (optional)
  8691. * @param end defines the end of the data (optional)
  8692. * @returns the new sliced array
  8693. */
  8694. Tools.Slice = function (data, start, end) {
  8695. if (data.slice) {
  8696. return data.slice(start, end);
  8697. }
  8698. return Array.prototype.slice.call(data, start, end);
  8699. };
  8700. Tools.SetImmediate = function (action) {
  8701. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8702. window.setImmediate(action);
  8703. }
  8704. else {
  8705. setTimeout(action, 1);
  8706. }
  8707. };
  8708. Tools.IsExponentOfTwo = function (value) {
  8709. var count = 1;
  8710. do {
  8711. count *= 2;
  8712. } while (count < value);
  8713. return count === value;
  8714. };
  8715. /**
  8716. * Returns the nearest 32-bit single precision float representation of a Number
  8717. * @param value A Number. If the parameter is of a different type, it will get converted
  8718. * to a number or to NaN if it cannot be converted
  8719. * @returns number
  8720. */
  8721. Tools.FloatRound = function (value) {
  8722. if (Math.fround) {
  8723. return Math.fround(value);
  8724. }
  8725. return (Tools._tmpFloatArray[0] = value);
  8726. };
  8727. /**
  8728. * Find the next highest power of two.
  8729. * @param x Number to start search from.
  8730. * @return Next highest power of two.
  8731. */
  8732. Tools.CeilingPOT = function (x) {
  8733. x--;
  8734. x |= x >> 1;
  8735. x |= x >> 2;
  8736. x |= x >> 4;
  8737. x |= x >> 8;
  8738. x |= x >> 16;
  8739. x++;
  8740. return x;
  8741. };
  8742. /**
  8743. * Find the next lowest power of two.
  8744. * @param x Number to start search from.
  8745. * @return Next lowest power of two.
  8746. */
  8747. Tools.FloorPOT = function (x) {
  8748. x = x | (x >> 1);
  8749. x = x | (x >> 2);
  8750. x = x | (x >> 4);
  8751. x = x | (x >> 8);
  8752. x = x | (x >> 16);
  8753. return x - (x >> 1);
  8754. };
  8755. /**
  8756. * Find the nearest power of two.
  8757. * @param x Number to start search from.
  8758. * @return Next nearest power of two.
  8759. */
  8760. Tools.NearestPOT = function (x) {
  8761. var c = Tools.CeilingPOT(x);
  8762. var f = Tools.FloorPOT(x);
  8763. return (c - x) > (x - f) ? f : c;
  8764. };
  8765. Tools.GetExponentOfTwo = function (value, max, mode) {
  8766. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8767. var pot;
  8768. switch (mode) {
  8769. case BABYLON.Engine.SCALEMODE_FLOOR:
  8770. pot = Tools.FloorPOT(value);
  8771. break;
  8772. case BABYLON.Engine.SCALEMODE_NEAREST:
  8773. pot = Tools.NearestPOT(value);
  8774. break;
  8775. case BABYLON.Engine.SCALEMODE_CEILING:
  8776. default:
  8777. pot = Tools.CeilingPOT(value);
  8778. break;
  8779. }
  8780. return Math.min(pot, max);
  8781. };
  8782. Tools.GetFilename = function (path) {
  8783. var index = path.lastIndexOf("/");
  8784. if (index < 0)
  8785. return path;
  8786. return path.substring(index + 1);
  8787. };
  8788. /**
  8789. * Extracts the "folder" part of a path (everything before the filename).
  8790. * @param uri The URI to extract the info from
  8791. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8792. * @returns The "folder" part of the path
  8793. */
  8794. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8795. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8796. var index = uri.lastIndexOf("/");
  8797. if (index < 0) {
  8798. if (returnUnchangedIfNoSlash) {
  8799. return uri;
  8800. }
  8801. return "";
  8802. }
  8803. return uri.substring(0, index + 1);
  8804. };
  8805. Tools.GetDOMTextContent = function (element) {
  8806. var result = "";
  8807. var child = element.firstChild;
  8808. while (child) {
  8809. if (child.nodeType === 3) {
  8810. result += child.textContent;
  8811. }
  8812. child = child.nextSibling;
  8813. }
  8814. return result;
  8815. };
  8816. Tools.ToDegrees = function (angle) {
  8817. return angle * 180 / Math.PI;
  8818. };
  8819. Tools.ToRadians = function (angle) {
  8820. return angle * Math.PI / 180;
  8821. };
  8822. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8823. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8824. var output = "";
  8825. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8826. var i = 0;
  8827. var bytes = new Uint8Array(buffer);
  8828. while (i < bytes.length) {
  8829. chr1 = bytes[i++];
  8830. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8831. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8832. enc1 = chr1 >> 2;
  8833. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8834. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8835. enc4 = chr3 & 63;
  8836. if (isNaN(chr2)) {
  8837. enc3 = enc4 = 64;
  8838. }
  8839. else if (isNaN(chr3)) {
  8840. enc4 = 64;
  8841. }
  8842. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8843. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8844. }
  8845. return "data:image/png;base64," + output;
  8846. };
  8847. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8848. if (bias === void 0) { bias = null; }
  8849. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8850. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8851. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8852. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8853. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8854. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8855. }
  8856. if (bias) {
  8857. minimum.x -= minimum.x * bias.x + bias.y;
  8858. minimum.y -= minimum.y * bias.x + bias.y;
  8859. minimum.z -= minimum.z * bias.x + bias.y;
  8860. maximum.x += maximum.x * bias.x + bias.y;
  8861. maximum.y += maximum.y * bias.x + bias.y;
  8862. maximum.z += maximum.z * bias.x + bias.y;
  8863. }
  8864. return {
  8865. minimum: minimum,
  8866. maximum: maximum
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. if (!stride) {
  8874. stride = 3;
  8875. }
  8876. for (var index = start; index < start + count; index++) {
  8877. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8878. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8879. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8880. }
  8881. if (bias) {
  8882. minimum.x -= minimum.x * bias.x + bias.y;
  8883. minimum.y -= minimum.y * bias.x + bias.y;
  8884. minimum.z -= minimum.z * bias.x + bias.y;
  8885. maximum.x += maximum.x * bias.x + bias.y;
  8886. maximum.y += maximum.y * bias.x + bias.y;
  8887. maximum.z += maximum.z * bias.x + bias.y;
  8888. }
  8889. return {
  8890. minimum: minimum,
  8891. maximum: maximum
  8892. };
  8893. };
  8894. Tools.Vector2ArrayFeeder = function (array) {
  8895. return function (index) {
  8896. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8897. var length = isFloatArray ? array.length / 2 : array.length;
  8898. if (index >= length) {
  8899. return null;
  8900. }
  8901. if (isFloatArray) {
  8902. var fa = array;
  8903. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8904. }
  8905. var a = array;
  8906. return a[index];
  8907. };
  8908. };
  8909. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8910. if (bias === void 0) { bias = null; }
  8911. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8912. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8913. var i = 0;
  8914. var cur = feeder(i++);
  8915. while (cur) {
  8916. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8917. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8918. cur = feeder(i++);
  8919. }
  8920. if (bias) {
  8921. minimum.x -= minimum.x * bias.x + bias.y;
  8922. minimum.y -= minimum.y * bias.x + bias.y;
  8923. maximum.x += maximum.x * bias.x + bias.y;
  8924. maximum.y += maximum.y * bias.x + bias.y;
  8925. }
  8926. return {
  8927. minimum: minimum,
  8928. maximum: maximum
  8929. };
  8930. };
  8931. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8932. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8933. return null;
  8934. return Array.isArray(obj) ? obj : [obj];
  8935. };
  8936. // Misc.
  8937. Tools.GetPointerPrefix = function () {
  8938. var eventPrefix = "pointer";
  8939. // Check if pointer events are supported
  8940. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8941. eventPrefix = "mouse";
  8942. }
  8943. return eventPrefix;
  8944. };
  8945. /**
  8946. * @param func - the function to be called
  8947. * @param requester - the object that will request the next frame. Falls back to window.
  8948. */
  8949. Tools.QueueNewFrame = function (func, requester) {
  8950. if (!Tools.IsWindowObjectExist()) {
  8951. return setTimeout(func, 16);
  8952. }
  8953. if (!requester) {
  8954. requester = window;
  8955. }
  8956. if (requester.requestAnimationFrame) {
  8957. return requester.requestAnimationFrame(func);
  8958. }
  8959. else if (requester.msRequestAnimationFrame) {
  8960. return requester.msRequestAnimationFrame(func);
  8961. }
  8962. else if (requester.webkitRequestAnimationFrame) {
  8963. return requester.webkitRequestAnimationFrame(func);
  8964. }
  8965. else if (requester.mozRequestAnimationFrame) {
  8966. return requester.mozRequestAnimationFrame(func);
  8967. }
  8968. else if (requester.oRequestAnimationFrame) {
  8969. return requester.oRequestAnimationFrame(func);
  8970. }
  8971. else {
  8972. return window.setTimeout(func, 16);
  8973. }
  8974. };
  8975. Tools.RequestFullscreen = function (element) {
  8976. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8977. if (!requestFunction)
  8978. return;
  8979. requestFunction.call(element);
  8980. };
  8981. Tools.ExitFullscreen = function () {
  8982. if (document.exitFullscreen) {
  8983. document.exitFullscreen();
  8984. }
  8985. else if (document.mozCancelFullScreen) {
  8986. document.mozCancelFullScreen();
  8987. }
  8988. else if (document.webkitCancelFullScreen) {
  8989. document.webkitCancelFullScreen();
  8990. }
  8991. else if (document.msCancelFullScreen) {
  8992. document.msCancelFullScreen();
  8993. }
  8994. };
  8995. Tools.SetCorsBehavior = function (url, element) {
  8996. if (url && url.indexOf("data:") === 0) {
  8997. return;
  8998. }
  8999. if (Tools.CorsBehavior) {
  9000. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9001. element.crossOrigin = Tools.CorsBehavior;
  9002. }
  9003. else {
  9004. var result = Tools.CorsBehavior(url);
  9005. if (result) {
  9006. element.crossOrigin = result;
  9007. }
  9008. }
  9009. }
  9010. };
  9011. // External files
  9012. Tools.CleanUrl = function (url) {
  9013. url = url.replace(/#/mg, "%23");
  9014. return url;
  9015. };
  9016. /**
  9017. * Loads an image as an HTMLImageElement.
  9018. * @param input url string, ArrayBuffer, or Blob to load
  9019. * @param onLoad callback called when the image successfully loads
  9020. * @param onError callback called when the image fails to load
  9021. * @param database database for caching
  9022. * @returns the HTMLImageElement of the loaded image
  9023. */
  9024. Tools.LoadImage = function (input, onLoad, onError, database) {
  9025. var url;
  9026. var usingObjectURL = false;
  9027. if (input instanceof ArrayBuffer) {
  9028. url = URL.createObjectURL(new Blob([input]));
  9029. usingObjectURL = true;
  9030. }
  9031. else if (input instanceof Blob) {
  9032. url = URL.createObjectURL(input);
  9033. usingObjectURL = true;
  9034. }
  9035. else {
  9036. url = Tools.CleanUrl(input);
  9037. url = Tools.PreprocessUrl(input);
  9038. }
  9039. var img = new Image();
  9040. Tools.SetCorsBehavior(url, img);
  9041. var loadHandler = function () {
  9042. if (usingObjectURL && img.src) {
  9043. URL.revokeObjectURL(img.src);
  9044. }
  9045. img.removeEventListener("load", loadHandler);
  9046. img.removeEventListener("error", errorHandler);
  9047. onLoad(img);
  9048. };
  9049. var errorHandler = function (err) {
  9050. if (usingObjectURL && img.src) {
  9051. URL.revokeObjectURL(img.src);
  9052. }
  9053. img.removeEventListener("load", loadHandler);
  9054. img.removeEventListener("error", errorHandler);
  9055. Tools.Error("Error while trying to load image: " + input);
  9056. if (onError) {
  9057. onError("Error while trying to load image: " + input, err);
  9058. }
  9059. };
  9060. img.addEventListener("load", loadHandler);
  9061. img.addEventListener("error", errorHandler);
  9062. var noIndexedDB = function () {
  9063. img.src = url;
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. if (database) {
  9067. database.loadImageFromDB(url, img);
  9068. }
  9069. };
  9070. //ANY database to do!
  9071. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9072. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9073. }
  9074. else {
  9075. if (url.indexOf("file:") !== -1) {
  9076. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9077. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9078. try {
  9079. var blobURL;
  9080. try {
  9081. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9082. }
  9083. catch (ex) {
  9084. // Chrome doesn't support oneTimeOnly parameter
  9085. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9086. }
  9087. img.src = blobURL;
  9088. usingObjectURL = true;
  9089. }
  9090. catch (e) {
  9091. img.src = "";
  9092. }
  9093. return img;
  9094. }
  9095. }
  9096. noIndexedDB();
  9097. }
  9098. return img;
  9099. };
  9100. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9101. url = Tools.CleanUrl(url);
  9102. url = Tools.PreprocessUrl(url);
  9103. // If file and file input are set
  9104. if (url.indexOf("file:") !== -1) {
  9105. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9106. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9107. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9108. }
  9109. }
  9110. var loadUrl = Tools.BaseUrl + url;
  9111. var aborted = false;
  9112. var fileRequest = {
  9113. onCompleteObservable: new BABYLON.Observable(),
  9114. abort: function () { return aborted = true; },
  9115. };
  9116. var requestFile = function () {
  9117. var request = new XMLHttpRequest();
  9118. var retryHandle = null;
  9119. fileRequest.abort = function () {
  9120. aborted = true;
  9121. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9122. request.abort();
  9123. }
  9124. if (retryHandle !== null) {
  9125. clearTimeout(retryHandle);
  9126. retryHandle = null;
  9127. }
  9128. };
  9129. var retryLoop = function (retryIndex) {
  9130. request.open('GET', loadUrl, true);
  9131. if (useArrayBuffer) {
  9132. request.responseType = "arraybuffer";
  9133. }
  9134. if (onProgress) {
  9135. request.addEventListener("progress", onProgress);
  9136. }
  9137. var onLoadEnd = function () {
  9138. request.removeEventListener("loadend", onLoadEnd);
  9139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9140. fileRequest.onCompleteObservable.clear();
  9141. };
  9142. request.addEventListener("loadend", onLoadEnd);
  9143. var onReadyStateChange = function () {
  9144. if (aborted) {
  9145. return;
  9146. }
  9147. // In case of undefined state in some browsers.
  9148. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9149. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9150. request.removeEventListener("readystatechange", onReadyStateChange);
  9151. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9152. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9153. return;
  9154. }
  9155. var retryStrategy = Tools.DefaultRetryStrategy;
  9156. if (retryStrategy) {
  9157. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9158. if (waitTime !== -1) {
  9159. // Prevent the request from completing for retry.
  9160. request.removeEventListener("loadend", onLoadEnd);
  9161. request = new XMLHttpRequest();
  9162. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9163. return;
  9164. }
  9165. }
  9166. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9167. if (onError) {
  9168. onError(request, e);
  9169. }
  9170. else {
  9171. throw e;
  9172. }
  9173. }
  9174. };
  9175. request.addEventListener("readystatechange", onReadyStateChange);
  9176. request.send();
  9177. };
  9178. retryLoop(0);
  9179. };
  9180. // Caching all files
  9181. if (database && database.enableSceneOffline) {
  9182. var noIndexedDB_1 = function (request) {
  9183. if (request && request.status > 400) {
  9184. if (onError) {
  9185. onError(request);
  9186. }
  9187. }
  9188. else {
  9189. if (!aborted) {
  9190. requestFile();
  9191. }
  9192. }
  9193. };
  9194. var loadFromIndexedDB = function () {
  9195. // TODO: database needs to support aborting and should return a IFileRequest
  9196. if (aborted) {
  9197. return;
  9198. }
  9199. if (database) {
  9200. database.loadFileFromDB(url, function (data) {
  9201. if (!aborted) {
  9202. onSuccess(data);
  9203. }
  9204. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9205. }, onProgress ? function (event) {
  9206. if (!aborted) {
  9207. onProgress(event);
  9208. }
  9209. } : undefined, noIndexedDB_1, useArrayBuffer);
  9210. }
  9211. };
  9212. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9213. }
  9214. else {
  9215. requestFile();
  9216. }
  9217. return fileRequest;
  9218. };
  9219. /**
  9220. * Load a script (identified by an url). When the url returns, the
  9221. * content of this file is added into a new script element, attached to the DOM (body element)
  9222. */
  9223. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9224. if (!Tools.IsWindowObjectExist()) {
  9225. return;
  9226. }
  9227. var head = document.getElementsByTagName('head')[0];
  9228. var script = document.createElement('script');
  9229. script.type = 'text/javascript';
  9230. script.src = scriptUrl;
  9231. script.onload = function () {
  9232. if (onSuccess) {
  9233. onSuccess();
  9234. }
  9235. };
  9236. script.onerror = function (e) {
  9237. if (onError) {
  9238. onError("Unable to load script '" + scriptUrl + "'", e);
  9239. }
  9240. };
  9241. head.appendChild(script);
  9242. };
  9243. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9244. var reader = new FileReader();
  9245. var request = {
  9246. onCompleteObservable: new BABYLON.Observable(),
  9247. abort: function () { return reader.abort(); },
  9248. };
  9249. reader.onloadend = function (e) {
  9250. request.onCompleteObservable.notifyObservers(request);
  9251. };
  9252. reader.onload = function (e) {
  9253. //target doesn't have result from ts 1.3
  9254. callback(e.target['result']);
  9255. };
  9256. reader.onprogress = progressCallback;
  9257. reader.readAsDataURL(fileToLoad);
  9258. return request;
  9259. };
  9260. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9261. var reader = new FileReader();
  9262. var request = {
  9263. onCompleteObservable: new BABYLON.Observable(),
  9264. abort: function () { return reader.abort(); },
  9265. };
  9266. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9267. reader.onerror = function (e) {
  9268. Tools.Log("Error while reading file: " + fileToLoad.name);
  9269. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9270. };
  9271. reader.onload = function (e) {
  9272. //target doesn't have result from ts 1.3
  9273. callback(e.target['result']);
  9274. };
  9275. if (progressCallBack) {
  9276. reader.onprogress = progressCallBack;
  9277. }
  9278. if (!useArrayBuffer) {
  9279. // Asynchronous read
  9280. reader.readAsText(fileToLoad);
  9281. }
  9282. else {
  9283. reader.readAsArrayBuffer(fileToLoad);
  9284. }
  9285. return request;
  9286. };
  9287. //returns a downloadable url to a file content.
  9288. Tools.FileAsURL = function (content) {
  9289. var fileBlob = new Blob([content]);
  9290. var url = window.URL || window.webkitURL;
  9291. var link = url.createObjectURL(fileBlob);
  9292. return link;
  9293. };
  9294. // Misc.
  9295. Tools.Format = function (value, decimals) {
  9296. if (decimals === void 0) { decimals = 2; }
  9297. return value.toFixed(decimals);
  9298. };
  9299. Tools.CheckExtends = function (v, min, max) {
  9300. if (v.x < min.x)
  9301. min.x = v.x;
  9302. if (v.y < min.y)
  9303. min.y = v.y;
  9304. if (v.z < min.z)
  9305. min.z = v.z;
  9306. if (v.x > max.x)
  9307. max.x = v.x;
  9308. if (v.y > max.y)
  9309. max.y = v.y;
  9310. if (v.z > max.z)
  9311. max.z = v.z;
  9312. };
  9313. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9314. for (var prop in source) {
  9315. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9316. continue;
  9317. }
  9318. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9319. continue;
  9320. }
  9321. var sourceValue = source[prop];
  9322. var typeOfSourceValue = typeof sourceValue;
  9323. if (typeOfSourceValue === "function") {
  9324. continue;
  9325. }
  9326. try {
  9327. if (typeOfSourceValue === "object") {
  9328. if (sourceValue instanceof Array) {
  9329. destination[prop] = [];
  9330. if (sourceValue.length > 0) {
  9331. if (typeof sourceValue[0] == "object") {
  9332. for (var index = 0; index < sourceValue.length; index++) {
  9333. var clonedValue = cloneValue(sourceValue[index], destination);
  9334. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9335. destination[prop].push(clonedValue);
  9336. }
  9337. }
  9338. }
  9339. else {
  9340. destination[prop] = sourceValue.slice(0);
  9341. }
  9342. }
  9343. }
  9344. else {
  9345. destination[prop] = cloneValue(sourceValue, destination);
  9346. }
  9347. }
  9348. else {
  9349. destination[prop] = sourceValue;
  9350. }
  9351. }
  9352. catch (e) {
  9353. // Just ignore error (it could be because of a read-only property)
  9354. }
  9355. }
  9356. };
  9357. Tools.IsEmpty = function (obj) {
  9358. for (var i in obj) {
  9359. if (obj.hasOwnProperty(i)) {
  9360. return false;
  9361. }
  9362. }
  9363. return true;
  9364. };
  9365. Tools.RegisterTopRootEvents = function (events) {
  9366. for (var index = 0; index < events.length; index++) {
  9367. var event = events[index];
  9368. window.addEventListener(event.name, event.handler, false);
  9369. try {
  9370. if (window.parent) {
  9371. window.parent.addEventListener(event.name, event.handler, false);
  9372. }
  9373. }
  9374. catch (e) {
  9375. // Silently fails...
  9376. }
  9377. }
  9378. };
  9379. Tools.UnregisterTopRootEvents = function (events) {
  9380. for (var index = 0; index < events.length; index++) {
  9381. var event = events[index];
  9382. window.removeEventListener(event.name, event.handler);
  9383. try {
  9384. if (window.parent) {
  9385. window.parent.removeEventListener(event.name, event.handler);
  9386. }
  9387. }
  9388. catch (e) {
  9389. // Silently fails...
  9390. }
  9391. }
  9392. };
  9393. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9394. if (mimeType === void 0) { mimeType = "image/png"; }
  9395. // Read the contents of the framebuffer
  9396. var numberOfChannelsByLine = width * 4;
  9397. var halfHeight = height / 2;
  9398. //Reading datas from WebGL
  9399. var data = engine.readPixels(0, 0, width, height);
  9400. //To flip image on Y axis.
  9401. for (var i = 0; i < halfHeight; i++) {
  9402. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9403. var currentCell = j + i * numberOfChannelsByLine;
  9404. var targetLine = height - i - 1;
  9405. var targetCell = j + targetLine * numberOfChannelsByLine;
  9406. var temp = data[currentCell];
  9407. data[currentCell] = data[targetCell];
  9408. data[targetCell] = temp;
  9409. }
  9410. }
  9411. // Create a 2D canvas to store the result
  9412. if (!screenshotCanvas) {
  9413. screenshotCanvas = document.createElement('canvas');
  9414. }
  9415. screenshotCanvas.width = width;
  9416. screenshotCanvas.height = height;
  9417. var context = screenshotCanvas.getContext('2d');
  9418. if (context) {
  9419. // Copy the pixels to a 2D canvas
  9420. var imageData = context.createImageData(width, height);
  9421. var castData = (imageData.data);
  9422. castData.set(data);
  9423. context.putImageData(imageData, 0, 0);
  9424. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9425. }
  9426. };
  9427. /**
  9428. * Converts the canvas data to blob.
  9429. * This acts as a polyfill for browsers not supporting the to blob function.
  9430. * @param canvas Defines the canvas to extract the data from
  9431. * @param successCallback Defines the callback triggered once the data are available
  9432. * @param mimeType Defines the mime type of the result
  9433. */
  9434. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9435. if (mimeType === void 0) { mimeType = "image/png"; }
  9436. // We need HTMLCanvasElement.toBlob for HD screenshots
  9437. if (!canvas.toBlob) {
  9438. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9439. canvas.toBlob = function (callback, type, quality) {
  9440. var _this = this;
  9441. setTimeout(function () {
  9442. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9443. for (var i = 0; i < len; i++) {
  9444. arr[i] = binStr.charCodeAt(i);
  9445. }
  9446. callback(new Blob([arr]));
  9447. });
  9448. };
  9449. }
  9450. canvas.toBlob(function (blob) {
  9451. successCallback(blob);
  9452. }, mimeType);
  9453. };
  9454. /**
  9455. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9456. * @param successCallback Defines the callback triggered once the data are available
  9457. * @param mimeType Defines the mime type of the result
  9458. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9459. */
  9460. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9461. if (mimeType === void 0) { mimeType = "image/png"; }
  9462. if (successCallback) {
  9463. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9464. successCallback(base64Image);
  9465. }
  9466. else {
  9467. this.ToBlob(screenshotCanvas, function (blob) {
  9468. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9469. if (("download" in document.createElement("a"))) {
  9470. if (!fileName) {
  9471. var date = new Date();
  9472. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9473. fileName = "screenshot_" + stringDate + ".png";
  9474. }
  9475. Tools.Download(blob, fileName);
  9476. }
  9477. else {
  9478. var url = URL.createObjectURL(blob);
  9479. var newWindow = window.open("");
  9480. if (!newWindow)
  9481. return;
  9482. var img = newWindow.document.createElement("img");
  9483. img.onload = function () {
  9484. // no longer need to read the blob so it's revoked
  9485. URL.revokeObjectURL(url);
  9486. };
  9487. img.src = url;
  9488. newWindow.document.body.appendChild(img);
  9489. }
  9490. }, mimeType);
  9491. }
  9492. };
  9493. /**
  9494. * Downloads a blob in the browser
  9495. * @param blob defines the blob to download
  9496. * @param fileName defines the name of the downloaded file
  9497. */
  9498. Tools.Download = function (blob, fileName) {
  9499. if (navigator && navigator.msSaveBlob) {
  9500. navigator.msSaveBlob(blob, fileName);
  9501. return;
  9502. }
  9503. var url = window.URL.createObjectURL(blob);
  9504. var a = document.createElement("a");
  9505. document.body.appendChild(a);
  9506. a.style.display = "none";
  9507. a.href = url;
  9508. a.download = fileName;
  9509. a.addEventListener("click", function () {
  9510. if (a.parentElement) {
  9511. a.parentElement.removeChild(a);
  9512. }
  9513. });
  9514. a.click();
  9515. window.URL.revokeObjectURL(url);
  9516. };
  9517. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9518. if (mimeType === void 0) { mimeType = "image/png"; }
  9519. var width;
  9520. var height;
  9521. // If a precision value is specified
  9522. if (size.precision) {
  9523. width = Math.round(engine.getRenderWidth() * size.precision);
  9524. height = Math.round(width / engine.getAspectRatio(camera));
  9525. }
  9526. else if (size.width && size.height) {
  9527. width = size.width;
  9528. height = size.height;
  9529. }
  9530. //If passing only width, computing height to keep display canvas ratio.
  9531. else if (size.width && !size.height) {
  9532. width = size.width;
  9533. height = Math.round(width / engine.getAspectRatio(camera));
  9534. }
  9535. //If passing only height, computing width to keep display canvas ratio.
  9536. else if (size.height && !size.width) {
  9537. height = size.height;
  9538. width = Math.round(height * engine.getAspectRatio(camera));
  9539. }
  9540. //Assuming here that "size" parameter is a number
  9541. else if (!isNaN(size)) {
  9542. height = size;
  9543. width = size;
  9544. }
  9545. else {
  9546. Tools.Error("Invalid 'size' parameter !");
  9547. return;
  9548. }
  9549. if (!screenshotCanvas) {
  9550. screenshotCanvas = document.createElement('canvas');
  9551. }
  9552. screenshotCanvas.width = width;
  9553. screenshotCanvas.height = height;
  9554. var renderContext = screenshotCanvas.getContext("2d");
  9555. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9556. var newWidth = width;
  9557. var newHeight = newWidth / ratio;
  9558. if (newHeight > height) {
  9559. newHeight = height;
  9560. newWidth = newHeight * ratio;
  9561. }
  9562. var offsetX = Math.max(0, width - newWidth) / 2;
  9563. var offsetY = Math.max(0, height - newHeight) / 2;
  9564. var renderingCanvas = engine.getRenderingCanvas();
  9565. if (renderContext && renderingCanvas) {
  9566. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9567. }
  9568. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9569. };
  9570. /**
  9571. * Generates an image screenshot from the specified camera.
  9572. *
  9573. * @param engine The engine to use for rendering
  9574. * @param camera The camera to use for rendering
  9575. * @param size This parameter can be set to a single number or to an object with the
  9576. * following (optional) properties: precision, width, height. If a single number is passed,
  9577. * it will be used for both width and height. If an object is passed, the screenshot size
  9578. * will be derived from the parameters. The precision property is a multiplier allowing
  9579. * rendering at a higher or lower resolution.
  9580. * @param successCallback The callback receives a single parameter which contains the
  9581. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9582. * src parameter of an <img> to display it.
  9583. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9584. * Check your browser for supported MIME types.
  9585. * @param samples Texture samples (default: 1)
  9586. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9587. * @param fileName A name for for the downloaded file.
  9588. * @constructor
  9589. */
  9590. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9591. if (mimeType === void 0) { mimeType = "image/png"; }
  9592. if (samples === void 0) { samples = 1; }
  9593. if (antialiasing === void 0) { antialiasing = false; }
  9594. var width;
  9595. var height;
  9596. //If a precision value is specified
  9597. if (size.precision) {
  9598. width = Math.round(engine.getRenderWidth() * size.precision);
  9599. height = Math.round(width / engine.getAspectRatio(camera));
  9600. size = { width: width, height: height };
  9601. }
  9602. else if (size.width && size.height) {
  9603. width = size.width;
  9604. height = size.height;
  9605. }
  9606. //If passing only width, computing height to keep display canvas ratio.
  9607. else if (size.width && !size.height) {
  9608. width = size.width;
  9609. height = Math.round(width / engine.getAspectRatio(camera));
  9610. size = { width: width, height: height };
  9611. }
  9612. //If passing only height, computing width to keep display canvas ratio.
  9613. else if (size.height && !size.width) {
  9614. height = size.height;
  9615. width = Math.round(height * engine.getAspectRatio(camera));
  9616. size = { width: width, height: height };
  9617. }
  9618. //Assuming here that "size" parameter is a number
  9619. else if (!isNaN(size)) {
  9620. height = size;
  9621. width = size;
  9622. }
  9623. else {
  9624. Tools.Error("Invalid 'size' parameter !");
  9625. return;
  9626. }
  9627. var scene = camera.getScene();
  9628. var previousCamera = null;
  9629. if (scene.activeCamera !== camera) {
  9630. previousCamera = scene.activeCamera;
  9631. scene.activeCamera = camera;
  9632. }
  9633. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9634. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9635. texture.renderList = null;
  9636. texture.samples = samples;
  9637. if (antialiasing) {
  9638. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9639. }
  9640. texture.onAfterRenderObservable.add(function () {
  9641. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9642. });
  9643. scene.incrementRenderId();
  9644. scene.resetCachedMaterial();
  9645. texture.render(true);
  9646. texture.dispose();
  9647. if (previousCamera) {
  9648. scene.activeCamera = previousCamera;
  9649. }
  9650. camera.getProjectionMatrix(true); // Force cache refresh;
  9651. };
  9652. // XHR response validator for local file scenario
  9653. Tools.ValidateXHRData = function (xhr, dataType) {
  9654. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9655. if (dataType === void 0) { dataType = 7; }
  9656. try {
  9657. if (dataType & 1) {
  9658. if (xhr.responseText && xhr.responseText.length > 0) {
  9659. return true;
  9660. }
  9661. else if (dataType === 1) {
  9662. return false;
  9663. }
  9664. }
  9665. if (dataType & 2) {
  9666. // Check header width and height since there is no "TGA" magic number
  9667. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9668. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9669. return true;
  9670. }
  9671. else if (dataType === 2) {
  9672. return false;
  9673. }
  9674. }
  9675. if (dataType & 4) {
  9676. // Check for the "DDS" magic number
  9677. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9678. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9679. return true;
  9680. }
  9681. else {
  9682. return false;
  9683. }
  9684. }
  9685. }
  9686. catch (e) {
  9687. // Global protection
  9688. }
  9689. return false;
  9690. };
  9691. /**
  9692. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9693. * Be aware Math.random() could cause collisions, but:
  9694. * "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"
  9695. */
  9696. Tools.RandomId = function () {
  9697. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9698. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9699. return v.toString(16);
  9700. });
  9701. };
  9702. /**
  9703. * Test if the given uri is a base64 string.
  9704. * @param uri The uri to test
  9705. * @return True if the uri is a base64 string or false otherwise.
  9706. */
  9707. Tools.IsBase64 = function (uri) {
  9708. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9709. };
  9710. /**
  9711. * Decode the given base64 uri.
  9712. * @param uri The uri to decode
  9713. * @return The decoded base64 data.
  9714. */
  9715. Tools.DecodeBase64 = function (uri) {
  9716. var decodedString = atob(uri.split(",")[1]);
  9717. var bufferLength = decodedString.length;
  9718. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9719. for (var i = 0; i < bufferLength; i++) {
  9720. bufferView[i] = decodedString.charCodeAt(i);
  9721. }
  9722. return bufferView.buffer;
  9723. };
  9724. Object.defineProperty(Tools, "NoneLogLevel", {
  9725. get: function () {
  9726. return Tools._NoneLogLevel;
  9727. },
  9728. enumerable: true,
  9729. configurable: true
  9730. });
  9731. Object.defineProperty(Tools, "MessageLogLevel", {
  9732. get: function () {
  9733. return Tools._MessageLogLevel;
  9734. },
  9735. enumerable: true,
  9736. configurable: true
  9737. });
  9738. Object.defineProperty(Tools, "WarningLogLevel", {
  9739. get: function () {
  9740. return Tools._WarningLogLevel;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Object.defineProperty(Tools, "ErrorLogLevel", {
  9746. get: function () {
  9747. return Tools._ErrorLogLevel;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. Object.defineProperty(Tools, "AllLogLevel", {
  9753. get: function () {
  9754. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Tools._AddLogEntry = function (entry) {
  9760. Tools._LogCache = entry + Tools._LogCache;
  9761. if (Tools.OnNewCacheEntry) {
  9762. Tools.OnNewCacheEntry(entry);
  9763. }
  9764. };
  9765. Tools._FormatMessage = function (message) {
  9766. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9767. var date = new Date();
  9768. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9769. };
  9770. Tools._LogDisabled = function (message) {
  9771. // nothing to do
  9772. };
  9773. Tools._LogEnabled = function (message) {
  9774. var formattedMessage = Tools._FormatMessage(message);
  9775. console.log("BJS - " + formattedMessage);
  9776. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9777. Tools._AddLogEntry(entry);
  9778. };
  9779. Tools._WarnDisabled = function (message) {
  9780. // nothing to do
  9781. };
  9782. Tools._WarnEnabled = function (message) {
  9783. var formattedMessage = Tools._FormatMessage(message);
  9784. console.warn("BJS - " + formattedMessage);
  9785. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9786. Tools._AddLogEntry(entry);
  9787. };
  9788. Tools._ErrorDisabled = function (message) {
  9789. // nothing to do
  9790. };
  9791. Tools._ErrorEnabled = function (message) {
  9792. Tools.errorsCount++;
  9793. var formattedMessage = Tools._FormatMessage(message);
  9794. console.error("BJS - " + formattedMessage);
  9795. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9796. Tools._AddLogEntry(entry);
  9797. };
  9798. Object.defineProperty(Tools, "LogCache", {
  9799. get: function () {
  9800. return Tools._LogCache;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Tools.ClearLogCache = function () {
  9806. Tools._LogCache = "";
  9807. Tools.errorsCount = 0;
  9808. };
  9809. Object.defineProperty(Tools, "LogLevels", {
  9810. set: function (level) {
  9811. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9812. Tools.Log = Tools._LogEnabled;
  9813. }
  9814. else {
  9815. Tools.Log = Tools._LogDisabled;
  9816. }
  9817. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9818. Tools.Warn = Tools._WarnEnabled;
  9819. }
  9820. else {
  9821. Tools.Warn = Tools._WarnDisabled;
  9822. }
  9823. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9824. Tools.Error = Tools._ErrorEnabled;
  9825. }
  9826. else {
  9827. Tools.Error = Tools._ErrorDisabled;
  9828. }
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. /**
  9834. * Check if the loaded document was accessed via `file:`-Protocol.
  9835. * @returns boolean
  9836. */
  9837. Tools.IsFileURL = function () {
  9838. return location.protocol === "file:";
  9839. };
  9840. Tools.IsWindowObjectExist = function () {
  9841. return (typeof window) !== "undefined";
  9842. };
  9843. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9844. get: function () {
  9845. return Tools._PerformanceNoneLogLevel;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9851. get: function () {
  9852. return Tools._PerformanceUserMarkLogLevel;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9858. get: function () {
  9859. return Tools._PerformanceConsoleLogLevel;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9865. set: function (level) {
  9866. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9867. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9868. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9869. return;
  9870. }
  9871. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9872. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9873. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9874. return;
  9875. }
  9876. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9877. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9878. },
  9879. enumerable: true,
  9880. configurable: true
  9881. });
  9882. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9883. };
  9884. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9885. };
  9886. Tools._StartUserMark = function (counterName, condition) {
  9887. if (condition === void 0) { condition = true; }
  9888. if (!Tools._performance) {
  9889. if (!Tools.IsWindowObjectExist()) {
  9890. return;
  9891. }
  9892. Tools._performance = window.performance;
  9893. }
  9894. if (!condition || !Tools._performance.mark) {
  9895. return;
  9896. }
  9897. Tools._performance.mark(counterName + "-Begin");
  9898. };
  9899. Tools._EndUserMark = function (counterName, condition) {
  9900. if (condition === void 0) { condition = true; }
  9901. if (!condition || !Tools._performance.mark) {
  9902. return;
  9903. }
  9904. Tools._performance.mark(counterName + "-End");
  9905. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9906. };
  9907. Tools._StartPerformanceConsole = function (counterName, condition) {
  9908. if (condition === void 0) { condition = true; }
  9909. if (!condition) {
  9910. return;
  9911. }
  9912. Tools._StartUserMark(counterName, condition);
  9913. if (console.time) {
  9914. console.time(counterName);
  9915. }
  9916. };
  9917. Tools._EndPerformanceConsole = function (counterName, condition) {
  9918. if (condition === void 0) { condition = true; }
  9919. if (!condition) {
  9920. return;
  9921. }
  9922. Tools._EndUserMark(counterName, condition);
  9923. if (console.time) {
  9924. console.timeEnd(counterName);
  9925. }
  9926. };
  9927. Object.defineProperty(Tools, "Now", {
  9928. get: function () {
  9929. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9930. return window.performance.now();
  9931. }
  9932. return Date.now();
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. /**
  9938. * This method will return the name of the class used to create the instance of the given object.
  9939. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9940. * @param object the object to get the class name from
  9941. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9942. */
  9943. Tools.GetClassName = function (object, isType) {
  9944. if (isType === void 0) { isType = false; }
  9945. var name = null;
  9946. if (!isType && object.getClassName) {
  9947. name = object.getClassName();
  9948. }
  9949. else {
  9950. if (object instanceof Object) {
  9951. var classObj = isType ? object : Object.getPrototypeOf(object);
  9952. name = classObj.constructor["__bjsclassName__"];
  9953. }
  9954. if (!name) {
  9955. name = typeof object;
  9956. }
  9957. }
  9958. return name;
  9959. };
  9960. Tools.First = function (array, predicate) {
  9961. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9962. var el = array_1[_i];
  9963. if (predicate(el)) {
  9964. return el;
  9965. }
  9966. }
  9967. return null;
  9968. };
  9969. /**
  9970. * This method will return the name of the full name of the class, including its owning module (if any).
  9971. * 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).
  9972. * @param object the object to get the class name from
  9973. * @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.
  9974. */
  9975. Tools.getFullClassName = function (object, isType) {
  9976. if (isType === void 0) { isType = false; }
  9977. var className = null;
  9978. var moduleName = null;
  9979. if (!isType && object.getClassName) {
  9980. className = object.getClassName();
  9981. }
  9982. else {
  9983. if (object instanceof Object) {
  9984. var classObj = isType ? object : Object.getPrototypeOf(object);
  9985. className = classObj.constructor["__bjsclassName__"];
  9986. moduleName = classObj.constructor["__bjsmoduleName__"];
  9987. }
  9988. if (!className) {
  9989. className = typeof object;
  9990. }
  9991. }
  9992. if (!className) {
  9993. return null;
  9994. }
  9995. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9996. };
  9997. /**
  9998. * 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.
  9999. * @param array
  10000. */
  10001. Tools.arrayOrStringFeeder = function (array) {
  10002. return function (index) {
  10003. if (index >= array.length) {
  10004. return null;
  10005. }
  10006. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10007. if (val && val.getHashCode) {
  10008. val = val.getHashCode();
  10009. }
  10010. if (typeof val === "string") {
  10011. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10012. }
  10013. return val;
  10014. };
  10015. };
  10016. /**
  10017. * Compute the hashCode of a stream of number
  10018. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10019. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10020. * @return the hash code computed
  10021. */
  10022. Tools.hashCodeFromStream = function (feeder) {
  10023. // Based from here: http://stackoverflow.com/a/7616484/802124
  10024. var hash = 0;
  10025. var index = 0;
  10026. var chr = feeder(index++);
  10027. while (chr != null) {
  10028. hash = ((hash << 5) - hash) + chr;
  10029. hash |= 0; // Convert to 32bit integer
  10030. chr = feeder(index++);
  10031. }
  10032. return hash;
  10033. };
  10034. /**
  10035. * Returns a promise that resolves after the given amount of time.
  10036. * @param delay Number of milliseconds to delay
  10037. * @returns Promise that resolves after the given amount of time
  10038. */
  10039. Tools.DelayAsync = function (delay) {
  10040. return new Promise(function (resolve) {
  10041. setTimeout(function () {
  10042. resolve();
  10043. }, delay);
  10044. });
  10045. };
  10046. /**
  10047. * Gets the current gradient from an array of IValueGradient
  10048. * @param ratio defines the current ratio to get
  10049. * @param gradients defines the array of IValueGradient
  10050. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10051. */
  10052. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10053. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10054. var currentGradient = gradients[gradientIndex];
  10055. var nextGradient = gradients[gradientIndex + 1];
  10056. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10057. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10058. updateFunc(currentGradient, nextGradient, scale);
  10059. }
  10060. }
  10061. };
  10062. Tools.BaseUrl = "";
  10063. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10064. /**
  10065. * Default behaviour for cors in the application.
  10066. * It can be a string if the expected behavior is identical in the entire app.
  10067. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10068. */
  10069. Tools.CorsBehavior = "anonymous";
  10070. Tools.UseFallbackTexture = true;
  10071. /**
  10072. * Use this object to register external classes like custom textures or material
  10073. * to allow the laoders to instantiate them
  10074. */
  10075. Tools.RegisteredExternalClasses = {};
  10076. // Used in case of a texture loading problem
  10077. 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";
  10078. Tools._tmpFloatArray = new Float32Array(1);
  10079. Tools.PreprocessUrl = function (url) {
  10080. return url;
  10081. };
  10082. // Logs
  10083. Tools._NoneLogLevel = 0;
  10084. Tools._MessageLogLevel = 1;
  10085. Tools._WarningLogLevel = 2;
  10086. Tools._ErrorLogLevel = 4;
  10087. Tools._LogCache = "";
  10088. Tools.errorsCount = 0;
  10089. Tools.Log = Tools._LogEnabled;
  10090. Tools.Warn = Tools._WarnEnabled;
  10091. Tools.Error = Tools._ErrorEnabled;
  10092. // Performances
  10093. Tools._PerformanceNoneLogLevel = 0;
  10094. Tools._PerformanceUserMarkLogLevel = 1;
  10095. Tools._PerformanceConsoleLogLevel = 2;
  10096. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10097. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10098. return Tools;
  10099. }());
  10100. BABYLON.Tools = Tools;
  10101. /**
  10102. * This class is used to track a performance counter which is number based.
  10103. * The user has access to many properties which give statistics of different nature
  10104. *
  10105. * The implementer can track two kinds of Performance Counter: time and count
  10106. * 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.
  10107. * 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.
  10108. */
  10109. var PerfCounter = /** @class */ (function () {
  10110. function PerfCounter() {
  10111. this._startMonitoringTime = 0;
  10112. this._min = 0;
  10113. this._max = 0;
  10114. this._average = 0;
  10115. this._lastSecAverage = 0;
  10116. this._current = 0;
  10117. this._totalValueCount = 0;
  10118. this._totalAccumulated = 0;
  10119. this._lastSecAccumulated = 0;
  10120. this._lastSecTime = 0;
  10121. this._lastSecValueCount = 0;
  10122. }
  10123. Object.defineProperty(PerfCounter.prototype, "min", {
  10124. /**
  10125. * Returns the smallest value ever
  10126. */
  10127. get: function () {
  10128. return this._min;
  10129. },
  10130. enumerable: true,
  10131. configurable: true
  10132. });
  10133. Object.defineProperty(PerfCounter.prototype, "max", {
  10134. /**
  10135. * Returns the biggest value ever
  10136. */
  10137. get: function () {
  10138. return this._max;
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(PerfCounter.prototype, "average", {
  10144. /**
  10145. * Returns the average value since the performance counter is running
  10146. */
  10147. get: function () {
  10148. return this._average;
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10154. /**
  10155. * Returns the average value of the last second the counter was monitored
  10156. */
  10157. get: function () {
  10158. return this._lastSecAverage;
  10159. },
  10160. enumerable: true,
  10161. configurable: true
  10162. });
  10163. Object.defineProperty(PerfCounter.prototype, "current", {
  10164. /**
  10165. * Returns the current value
  10166. */
  10167. get: function () {
  10168. return this._current;
  10169. },
  10170. enumerable: true,
  10171. configurable: true
  10172. });
  10173. Object.defineProperty(PerfCounter.prototype, "total", {
  10174. get: function () {
  10175. return this._totalAccumulated;
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. Object.defineProperty(PerfCounter.prototype, "count", {
  10181. get: function () {
  10182. return this._totalValueCount;
  10183. },
  10184. enumerable: true,
  10185. configurable: true
  10186. });
  10187. /**
  10188. * Call this method to start monitoring a new frame.
  10189. * 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.
  10190. */
  10191. PerfCounter.prototype.fetchNewFrame = function () {
  10192. this._totalValueCount++;
  10193. this._current = 0;
  10194. this._lastSecValueCount++;
  10195. };
  10196. /**
  10197. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10198. * @param newCount the count value to add to the monitored count
  10199. * @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.
  10200. */
  10201. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10202. if (!PerfCounter.Enabled) {
  10203. return;
  10204. }
  10205. this._current += newCount;
  10206. if (fetchResult) {
  10207. this._fetchResult();
  10208. }
  10209. };
  10210. /**
  10211. * Start monitoring this performance counter
  10212. */
  10213. PerfCounter.prototype.beginMonitoring = function () {
  10214. if (!PerfCounter.Enabled) {
  10215. return;
  10216. }
  10217. this._startMonitoringTime = Tools.Now;
  10218. };
  10219. /**
  10220. * Compute the time lapsed since the previous beginMonitoring() call.
  10221. * @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
  10222. */
  10223. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10224. if (newFrame === void 0) { newFrame = true; }
  10225. if (!PerfCounter.Enabled) {
  10226. return;
  10227. }
  10228. if (newFrame) {
  10229. this.fetchNewFrame();
  10230. }
  10231. var currentTime = Tools.Now;
  10232. this._current = currentTime - this._startMonitoringTime;
  10233. if (newFrame) {
  10234. this._fetchResult();
  10235. }
  10236. };
  10237. PerfCounter.prototype._fetchResult = function () {
  10238. this._totalAccumulated += this._current;
  10239. this._lastSecAccumulated += this._current;
  10240. // Min/Max update
  10241. this._min = Math.min(this._min, this._current);
  10242. this._max = Math.max(this._max, this._current);
  10243. this._average = this._totalAccumulated / this._totalValueCount;
  10244. // Reset last sec?
  10245. var now = Tools.Now;
  10246. if ((now - this._lastSecTime) > 1000) {
  10247. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10248. this._lastSecTime = now;
  10249. this._lastSecAccumulated = 0;
  10250. this._lastSecValueCount = 0;
  10251. }
  10252. };
  10253. PerfCounter.Enabled = true;
  10254. return PerfCounter;
  10255. }());
  10256. BABYLON.PerfCounter = PerfCounter;
  10257. /**
  10258. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10259. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10260. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10261. * @param name The name of the class, case should be preserved
  10262. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10263. */
  10264. function className(name, module) {
  10265. return function (target) {
  10266. target["__bjsclassName__"] = name;
  10267. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10268. };
  10269. }
  10270. BABYLON.className = className;
  10271. /**
  10272. * An implementation of a loop for asynchronous functions.
  10273. */
  10274. var AsyncLoop = /** @class */ (function () {
  10275. /**
  10276. * Constroctor.
  10277. * @param iterations the number of iterations.
  10278. * @param _fn the function to run each iteration
  10279. * @param _successCallback the callback that will be called upon succesful execution
  10280. * @param offset starting offset.
  10281. */
  10282. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10283. if (offset === void 0) { offset = 0; }
  10284. this.iterations = iterations;
  10285. this._fn = _fn;
  10286. this._successCallback = _successCallback;
  10287. this.index = offset - 1;
  10288. this._done = false;
  10289. }
  10290. /**
  10291. * Execute the next iteration. Must be called after the last iteration was finished.
  10292. */
  10293. AsyncLoop.prototype.executeNext = function () {
  10294. if (!this._done) {
  10295. if (this.index + 1 < this.iterations) {
  10296. ++this.index;
  10297. this._fn(this);
  10298. }
  10299. else {
  10300. this.breakLoop();
  10301. }
  10302. }
  10303. };
  10304. /**
  10305. * Break the loop and run the success callback.
  10306. */
  10307. AsyncLoop.prototype.breakLoop = function () {
  10308. this._done = true;
  10309. this._successCallback();
  10310. };
  10311. /**
  10312. * Helper function
  10313. */
  10314. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10315. if (offset === void 0) { offset = 0; }
  10316. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10317. loop.executeNext();
  10318. return loop;
  10319. };
  10320. /**
  10321. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10322. * @param iterations total number of iterations
  10323. * @param syncedIterations number of synchronous iterations in each async iteration.
  10324. * @param fn the function to call each iteration.
  10325. * @param callback a success call back that will be called when iterating stops.
  10326. * @param breakFunction a break condition (optional)
  10327. * @param timeout timeout settings for the setTimeout function. default - 0.
  10328. * @constructor
  10329. */
  10330. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10331. if (timeout === void 0) { timeout = 0; }
  10332. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10333. if (breakFunction && breakFunction())
  10334. loop.breakLoop();
  10335. else {
  10336. setTimeout(function () {
  10337. for (var i = 0; i < syncedIterations; ++i) {
  10338. var iteration = (loop.index * syncedIterations) + i;
  10339. if (iteration >= iterations)
  10340. break;
  10341. fn(iteration);
  10342. if (breakFunction && breakFunction()) {
  10343. loop.breakLoop();
  10344. break;
  10345. }
  10346. }
  10347. loop.executeNext();
  10348. }, timeout);
  10349. }
  10350. }, callback);
  10351. };
  10352. return AsyncLoop;
  10353. }());
  10354. BABYLON.AsyncLoop = AsyncLoop;
  10355. })(BABYLON || (BABYLON = {}));
  10356. //# sourceMappingURL=babylon.tools.js.map
  10357. var BABYLON;
  10358. (function (BABYLON) {
  10359. var PromiseStates;
  10360. (function (PromiseStates) {
  10361. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10362. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10363. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10364. })(PromiseStates || (PromiseStates = {}));
  10365. var FulFillmentAgregator = /** @class */ (function () {
  10366. function FulFillmentAgregator() {
  10367. this.count = 0;
  10368. this.target = 0;
  10369. this.results = [];
  10370. }
  10371. return FulFillmentAgregator;
  10372. }());
  10373. var InternalPromise = /** @class */ (function () {
  10374. function InternalPromise(resolver) {
  10375. var _this = this;
  10376. this._state = PromiseStates.Pending;
  10377. this._children = new Array();
  10378. this._rejectWasConsumed = false;
  10379. if (!resolver) {
  10380. return;
  10381. }
  10382. try {
  10383. resolver(function (value) {
  10384. _this._resolve(value);
  10385. }, function (reason) {
  10386. _this._reject(reason);
  10387. });
  10388. }
  10389. catch (e) {
  10390. this._reject(e);
  10391. }
  10392. }
  10393. Object.defineProperty(InternalPromise.prototype, "_result", {
  10394. get: function () {
  10395. return this._resultValue;
  10396. },
  10397. set: function (value) {
  10398. this._resultValue = value;
  10399. if (this._parent && this._parent._result === undefined) {
  10400. this._parent._result = value;
  10401. }
  10402. },
  10403. enumerable: true,
  10404. configurable: true
  10405. });
  10406. InternalPromise.prototype.catch = function (onRejected) {
  10407. return this.then(undefined, onRejected);
  10408. };
  10409. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10410. var _this = this;
  10411. var newPromise = new InternalPromise();
  10412. newPromise._onFulfilled = onFulfilled;
  10413. newPromise._onRejected = onRejected;
  10414. // Composition
  10415. this._children.push(newPromise);
  10416. newPromise._parent = this;
  10417. if (this._state !== PromiseStates.Pending) {
  10418. BABYLON.Tools.SetImmediate(function () {
  10419. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10420. var returnedValue = newPromise._resolve(_this._result);
  10421. if (returnedValue !== undefined && returnedValue !== null) {
  10422. if (returnedValue._state !== undefined) {
  10423. var returnedPromise = returnedValue;
  10424. newPromise._children.push(returnedPromise);
  10425. returnedPromise._parent = newPromise;
  10426. newPromise = returnedPromise;
  10427. }
  10428. else {
  10429. newPromise._result = returnedValue;
  10430. }
  10431. }
  10432. }
  10433. else {
  10434. newPromise._reject(_this._reason);
  10435. }
  10436. });
  10437. }
  10438. return newPromise;
  10439. };
  10440. InternalPromise.prototype._moveChildren = function (children) {
  10441. var _this = this;
  10442. var _a;
  10443. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10444. this._children.forEach(function (child) {
  10445. child._parent = _this;
  10446. });
  10447. if (this._state === PromiseStates.Fulfilled) {
  10448. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10449. var child = _b[_i];
  10450. child._resolve(this._result);
  10451. }
  10452. }
  10453. else if (this._state === PromiseStates.Rejected) {
  10454. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10455. var child = _d[_c];
  10456. child._reject(this._reason);
  10457. }
  10458. }
  10459. };
  10460. InternalPromise.prototype._resolve = function (value) {
  10461. try {
  10462. this._state = PromiseStates.Fulfilled;
  10463. var returnedValue = null;
  10464. if (this._onFulfilled) {
  10465. returnedValue = this._onFulfilled(value);
  10466. }
  10467. if (returnedValue !== undefined && returnedValue !== null) {
  10468. if (returnedValue._state !== undefined) {
  10469. // Transmit children
  10470. var returnedPromise = returnedValue;
  10471. returnedPromise._parent = this;
  10472. returnedPromise._moveChildren(this._children);
  10473. value = returnedPromise._result;
  10474. }
  10475. else {
  10476. value = returnedValue;
  10477. }
  10478. }
  10479. this._result = value;
  10480. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10481. var child = _a[_i];
  10482. child._resolve(value);
  10483. }
  10484. this._children.length = 0;
  10485. delete this._onFulfilled;
  10486. delete this._onRejected;
  10487. }
  10488. catch (e) {
  10489. this._reject(e, true);
  10490. }
  10491. };
  10492. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10493. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10494. this._state = PromiseStates.Rejected;
  10495. this._reason = reason;
  10496. if (this._onRejected && !onLocalThrow) {
  10497. try {
  10498. this._onRejected(reason);
  10499. this._rejectWasConsumed = true;
  10500. }
  10501. catch (e) {
  10502. reason = e;
  10503. }
  10504. }
  10505. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10506. var child = _a[_i];
  10507. if (this._rejectWasConsumed) {
  10508. child._resolve(null);
  10509. }
  10510. else {
  10511. child._reject(reason);
  10512. }
  10513. }
  10514. this._children.length = 0;
  10515. delete this._onFulfilled;
  10516. delete this._onRejected;
  10517. };
  10518. InternalPromise.resolve = function (value) {
  10519. var newPromise = new InternalPromise();
  10520. newPromise._resolve(value);
  10521. return newPromise;
  10522. };
  10523. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10524. promise.then(function (value) {
  10525. agregator.results[index] = value;
  10526. agregator.count++;
  10527. if (agregator.count === agregator.target) {
  10528. agregator.rootPromise._resolve(agregator.results);
  10529. }
  10530. return null;
  10531. }, function (reason) {
  10532. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10533. agregator.rootPromise._reject(reason);
  10534. }
  10535. });
  10536. };
  10537. InternalPromise.all = function (promises) {
  10538. var newPromise = new InternalPromise();
  10539. var agregator = new FulFillmentAgregator();
  10540. agregator.target = promises.length;
  10541. agregator.rootPromise = newPromise;
  10542. if (promises.length) {
  10543. for (var index = 0; index < promises.length; index++) {
  10544. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10545. }
  10546. }
  10547. else {
  10548. newPromise._resolve([]);
  10549. }
  10550. return newPromise;
  10551. };
  10552. InternalPromise.race = function (promises) {
  10553. var newPromise = new InternalPromise();
  10554. if (promises.length) {
  10555. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10556. var promise = promises_1[_i];
  10557. promise.then(function (value) {
  10558. if (newPromise) {
  10559. newPromise._resolve(value);
  10560. newPromise = null;
  10561. }
  10562. return null;
  10563. }, function (reason) {
  10564. if (newPromise) {
  10565. newPromise._reject(reason);
  10566. newPromise = null;
  10567. }
  10568. });
  10569. }
  10570. }
  10571. return newPromise;
  10572. };
  10573. return InternalPromise;
  10574. }());
  10575. /**
  10576. * Helper class that provides a small promise polyfill
  10577. */
  10578. var PromisePolyfill = /** @class */ (function () {
  10579. function PromisePolyfill() {
  10580. }
  10581. /**
  10582. * Static function used to check if the polyfill is required
  10583. * If this is the case then the function will inject the polyfill to window.Promise
  10584. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10585. */
  10586. PromisePolyfill.Apply = function (force) {
  10587. if (force === void 0) { force = false; }
  10588. if (force || typeof Promise === 'undefined') {
  10589. var root = window;
  10590. root.Promise = InternalPromise;
  10591. }
  10592. };
  10593. return PromisePolyfill;
  10594. }());
  10595. BABYLON.PromisePolyfill = PromisePolyfill;
  10596. })(BABYLON || (BABYLON = {}));
  10597. //# sourceMappingURL=babylon.promise.js.map
  10598. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10599. var BABYLON;
  10600. (function (BABYLON) {
  10601. /**
  10602. * Helper class to push actions to a pool of workers.
  10603. */
  10604. var WorkerPool = /** @class */ (function () {
  10605. /**
  10606. * Constructor
  10607. * @param workers Array of workers to use for actions
  10608. */
  10609. function WorkerPool(workers) {
  10610. this._pendingActions = new Array();
  10611. this._workerInfos = workers.map(function (worker) { return ({
  10612. worker: worker,
  10613. active: false
  10614. }); });
  10615. }
  10616. /**
  10617. * Terminates all workers and clears any pending actions.
  10618. */
  10619. WorkerPool.prototype.dispose = function () {
  10620. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10621. var workerInfo = _a[_i];
  10622. workerInfo.worker.terminate();
  10623. }
  10624. delete this._workerInfos;
  10625. delete this._pendingActions;
  10626. };
  10627. /**
  10628. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10629. * pended until a worker has completed its action.
  10630. * @param action The action to perform. Call onComplete when the action is complete.
  10631. */
  10632. WorkerPool.prototype.push = function (action) {
  10633. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10634. var workerInfo = _a[_i];
  10635. if (!workerInfo.active) {
  10636. this._execute(workerInfo, action);
  10637. return;
  10638. }
  10639. }
  10640. this._pendingActions.push(action);
  10641. };
  10642. WorkerPool.prototype._execute = function (workerInfo, action) {
  10643. var _this = this;
  10644. workerInfo.active = true;
  10645. action(workerInfo.worker, function () {
  10646. workerInfo.active = false;
  10647. var nextAction = _this._pendingActions.shift();
  10648. if (nextAction) {
  10649. _this._execute(workerInfo, nextAction);
  10650. }
  10651. });
  10652. };
  10653. return WorkerPool;
  10654. }());
  10655. BABYLON.WorkerPool = WorkerPool;
  10656. })(BABYLON || (BABYLON = {}));
  10657. //# sourceMappingURL=babylon.workerPool.js.map
  10658. var BABYLON;
  10659. (function (BABYLON) {
  10660. /**
  10661. * @hidden
  10662. **/
  10663. var _AlphaState = /** @class */ (function () {
  10664. /**
  10665. * Initializes the state.
  10666. */
  10667. function _AlphaState() {
  10668. this._isAlphaBlendDirty = false;
  10669. this._isBlendFunctionParametersDirty = false;
  10670. this._isBlendEquationParametersDirty = false;
  10671. this._isBlendConstantsDirty = false;
  10672. this._alphaBlend = false;
  10673. this._blendFunctionParameters = new Array(4);
  10674. this._blendEquationParameters = new Array(2);
  10675. this._blendConstants = new Array(4);
  10676. this.reset();
  10677. }
  10678. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10679. get: function () {
  10680. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10686. get: function () {
  10687. return this._alphaBlend;
  10688. },
  10689. set: function (value) {
  10690. if (this._alphaBlend === value) {
  10691. return;
  10692. }
  10693. this._alphaBlend = value;
  10694. this._isAlphaBlendDirty = true;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10700. if (this._blendConstants[0] === r &&
  10701. this._blendConstants[1] === g &&
  10702. this._blendConstants[2] === b &&
  10703. this._blendConstants[3] === a) {
  10704. return;
  10705. }
  10706. this._blendConstants[0] = r;
  10707. this._blendConstants[1] = g;
  10708. this._blendConstants[2] = b;
  10709. this._blendConstants[3] = a;
  10710. this._isBlendConstantsDirty = true;
  10711. };
  10712. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10713. if (this._blendFunctionParameters[0] === value0 &&
  10714. this._blendFunctionParameters[1] === value1 &&
  10715. this._blendFunctionParameters[2] === value2 &&
  10716. this._blendFunctionParameters[3] === value3) {
  10717. return;
  10718. }
  10719. this._blendFunctionParameters[0] = value0;
  10720. this._blendFunctionParameters[1] = value1;
  10721. this._blendFunctionParameters[2] = value2;
  10722. this._blendFunctionParameters[3] = value3;
  10723. this._isBlendFunctionParametersDirty = true;
  10724. };
  10725. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10726. if (this._blendEquationParameters[0] === rgb &&
  10727. this._blendEquationParameters[1] === alpha) {
  10728. return;
  10729. }
  10730. this._blendEquationParameters[0] = rgb;
  10731. this._blendEquationParameters[1] = alpha;
  10732. this._isBlendEquationParametersDirty = true;
  10733. };
  10734. _AlphaState.prototype.reset = function () {
  10735. this._alphaBlend = false;
  10736. this._blendFunctionParameters[0] = null;
  10737. this._blendFunctionParameters[1] = null;
  10738. this._blendFunctionParameters[2] = null;
  10739. this._blendFunctionParameters[3] = null;
  10740. this._blendEquationParameters[0] = null;
  10741. this._blendEquationParameters[1] = null;
  10742. this._blendConstants[0] = null;
  10743. this._blendConstants[1] = null;
  10744. this._blendConstants[2] = null;
  10745. this._blendConstants[3] = null;
  10746. this._isAlphaBlendDirty = true;
  10747. this._isBlendFunctionParametersDirty = false;
  10748. this._isBlendEquationParametersDirty = false;
  10749. this._isBlendConstantsDirty = false;
  10750. };
  10751. _AlphaState.prototype.apply = function (gl) {
  10752. if (!this.isDirty) {
  10753. return;
  10754. }
  10755. // Alpha blend
  10756. if (this._isAlphaBlendDirty) {
  10757. if (this._alphaBlend) {
  10758. gl.enable(gl.BLEND);
  10759. }
  10760. else {
  10761. gl.disable(gl.BLEND);
  10762. }
  10763. this._isAlphaBlendDirty = false;
  10764. }
  10765. // Alpha function
  10766. if (this._isBlendFunctionParametersDirty) {
  10767. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10768. this._isBlendFunctionParametersDirty = false;
  10769. }
  10770. // Alpha equation
  10771. if (this._isBlendEquationParametersDirty) {
  10772. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10773. this._isBlendEquationParametersDirty = false;
  10774. }
  10775. // Constants
  10776. if (this._isBlendConstantsDirty) {
  10777. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10778. this._isBlendConstantsDirty = false;
  10779. }
  10780. };
  10781. return _AlphaState;
  10782. }());
  10783. BABYLON._AlphaState = _AlphaState;
  10784. })(BABYLON || (BABYLON = {}));
  10785. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10786. var BABYLON;
  10787. (function (BABYLON) {
  10788. /**
  10789. * @hidden
  10790. **/
  10791. var _DepthCullingState = /** @class */ (function () {
  10792. /**
  10793. * Initializes the state.
  10794. */
  10795. function _DepthCullingState() {
  10796. this._isDepthTestDirty = false;
  10797. this._isDepthMaskDirty = false;
  10798. this._isDepthFuncDirty = false;
  10799. this._isCullFaceDirty = false;
  10800. this._isCullDirty = false;
  10801. this._isZOffsetDirty = false;
  10802. this._isFrontFaceDirty = false;
  10803. this.reset();
  10804. }
  10805. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10806. get: function () {
  10807. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10813. get: function () {
  10814. return this._zOffset;
  10815. },
  10816. set: function (value) {
  10817. if (this._zOffset === value) {
  10818. return;
  10819. }
  10820. this._zOffset = value;
  10821. this._isZOffsetDirty = true;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10827. get: function () {
  10828. return this._cullFace;
  10829. },
  10830. set: function (value) {
  10831. if (this._cullFace === value) {
  10832. return;
  10833. }
  10834. this._cullFace = value;
  10835. this._isCullFaceDirty = true;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10841. get: function () {
  10842. return this._cull;
  10843. },
  10844. set: function (value) {
  10845. if (this._cull === value) {
  10846. return;
  10847. }
  10848. this._cull = value;
  10849. this._isCullDirty = true;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10855. get: function () {
  10856. return this._depthFunc;
  10857. },
  10858. set: function (value) {
  10859. if (this._depthFunc === value) {
  10860. return;
  10861. }
  10862. this._depthFunc = value;
  10863. this._isDepthFuncDirty = true;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10869. get: function () {
  10870. return this._depthMask;
  10871. },
  10872. set: function (value) {
  10873. if (this._depthMask === value) {
  10874. return;
  10875. }
  10876. this._depthMask = value;
  10877. this._isDepthMaskDirty = true;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10883. get: function () {
  10884. return this._depthTest;
  10885. },
  10886. set: function (value) {
  10887. if (this._depthTest === value) {
  10888. return;
  10889. }
  10890. this._depthTest = value;
  10891. this._isDepthTestDirty = true;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10897. get: function () {
  10898. return this._frontFace;
  10899. },
  10900. set: function (value) {
  10901. if (this._frontFace === value) {
  10902. return;
  10903. }
  10904. this._frontFace = value;
  10905. this._isFrontFaceDirty = true;
  10906. },
  10907. enumerable: true,
  10908. configurable: true
  10909. });
  10910. _DepthCullingState.prototype.reset = function () {
  10911. this._depthMask = true;
  10912. this._depthTest = true;
  10913. this._depthFunc = null;
  10914. this._cullFace = null;
  10915. this._cull = null;
  10916. this._zOffset = 0;
  10917. this._frontFace = null;
  10918. this._isDepthTestDirty = true;
  10919. this._isDepthMaskDirty = true;
  10920. this._isDepthFuncDirty = false;
  10921. this._isCullFaceDirty = false;
  10922. this._isCullDirty = false;
  10923. this._isZOffsetDirty = false;
  10924. this._isFrontFaceDirty = false;
  10925. };
  10926. _DepthCullingState.prototype.apply = function (gl) {
  10927. if (!this.isDirty) {
  10928. return;
  10929. }
  10930. // Cull
  10931. if (this._isCullDirty) {
  10932. if (this.cull) {
  10933. gl.enable(gl.CULL_FACE);
  10934. }
  10935. else {
  10936. gl.disable(gl.CULL_FACE);
  10937. }
  10938. this._isCullDirty = false;
  10939. }
  10940. // Cull face
  10941. if (this._isCullFaceDirty) {
  10942. gl.cullFace(this.cullFace);
  10943. this._isCullFaceDirty = false;
  10944. }
  10945. // Depth mask
  10946. if (this._isDepthMaskDirty) {
  10947. gl.depthMask(this.depthMask);
  10948. this._isDepthMaskDirty = false;
  10949. }
  10950. // Depth test
  10951. if (this._isDepthTestDirty) {
  10952. if (this.depthTest) {
  10953. gl.enable(gl.DEPTH_TEST);
  10954. }
  10955. else {
  10956. gl.disable(gl.DEPTH_TEST);
  10957. }
  10958. this._isDepthTestDirty = false;
  10959. }
  10960. // Depth func
  10961. if (this._isDepthFuncDirty) {
  10962. gl.depthFunc(this.depthFunc);
  10963. this._isDepthFuncDirty = false;
  10964. }
  10965. // zOffset
  10966. if (this._isZOffsetDirty) {
  10967. if (this.zOffset) {
  10968. gl.enable(gl.POLYGON_OFFSET_FILL);
  10969. gl.polygonOffset(this.zOffset, 0);
  10970. }
  10971. else {
  10972. gl.disable(gl.POLYGON_OFFSET_FILL);
  10973. }
  10974. this._isZOffsetDirty = false;
  10975. }
  10976. // Front face
  10977. if (this._isFrontFaceDirty) {
  10978. gl.frontFace(this.frontFace);
  10979. this._isFrontFaceDirty = false;
  10980. }
  10981. };
  10982. return _DepthCullingState;
  10983. }());
  10984. BABYLON._DepthCullingState = _DepthCullingState;
  10985. })(BABYLON || (BABYLON = {}));
  10986. //# sourceMappingURL=babylon.depthCullingState.js.map
  10987. var BABYLON;
  10988. (function (BABYLON) {
  10989. /**
  10990. * @hidden
  10991. **/
  10992. var _StencilState = /** @class */ (function () {
  10993. function _StencilState() {
  10994. this._isStencilTestDirty = false;
  10995. this._isStencilMaskDirty = false;
  10996. this._isStencilFuncDirty = false;
  10997. this._isStencilOpDirty = false;
  10998. this.reset();
  10999. }
  11000. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11001. get: function () {
  11002. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11008. get: function () {
  11009. return this._stencilFunc;
  11010. },
  11011. set: function (value) {
  11012. if (this._stencilFunc === value) {
  11013. return;
  11014. }
  11015. this._stencilFunc = value;
  11016. this._isStencilFuncDirty = true;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11022. get: function () {
  11023. return this._stencilFuncRef;
  11024. },
  11025. set: function (value) {
  11026. if (this._stencilFuncRef === value) {
  11027. return;
  11028. }
  11029. this._stencilFuncRef = value;
  11030. this._isStencilFuncDirty = true;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11036. get: function () {
  11037. return this._stencilFuncMask;
  11038. },
  11039. set: function (value) {
  11040. if (this._stencilFuncMask === value) {
  11041. return;
  11042. }
  11043. this._stencilFuncMask = value;
  11044. this._isStencilFuncDirty = true;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11050. get: function () {
  11051. return this._stencilOpStencilFail;
  11052. },
  11053. set: function (value) {
  11054. if (this._stencilOpStencilFail === value) {
  11055. return;
  11056. }
  11057. this._stencilOpStencilFail = value;
  11058. this._isStencilOpDirty = true;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11064. get: function () {
  11065. return this._stencilOpDepthFail;
  11066. },
  11067. set: function (value) {
  11068. if (this._stencilOpDepthFail === value) {
  11069. return;
  11070. }
  11071. this._stencilOpDepthFail = value;
  11072. this._isStencilOpDirty = true;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11078. get: function () {
  11079. return this._stencilOpStencilDepthPass;
  11080. },
  11081. set: function (value) {
  11082. if (this._stencilOpStencilDepthPass === value) {
  11083. return;
  11084. }
  11085. this._stencilOpStencilDepthPass = value;
  11086. this._isStencilOpDirty = true;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11092. get: function () {
  11093. return this._stencilMask;
  11094. },
  11095. set: function (value) {
  11096. if (this._stencilMask === value) {
  11097. return;
  11098. }
  11099. this._stencilMask = value;
  11100. this._isStencilMaskDirty = true;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11106. get: function () {
  11107. return this._stencilTest;
  11108. },
  11109. set: function (value) {
  11110. if (this._stencilTest === value) {
  11111. return;
  11112. }
  11113. this._stencilTest = value;
  11114. this._isStencilTestDirty = true;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. _StencilState.prototype.reset = function () {
  11120. this._stencilTest = false;
  11121. this._stencilMask = 0xFF;
  11122. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11123. this._stencilFuncRef = 1;
  11124. this._stencilFuncMask = 0xFF;
  11125. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11126. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11127. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11128. this._isStencilTestDirty = true;
  11129. this._isStencilMaskDirty = true;
  11130. this._isStencilFuncDirty = true;
  11131. this._isStencilOpDirty = true;
  11132. };
  11133. _StencilState.prototype.apply = function (gl) {
  11134. if (!this.isDirty) {
  11135. return;
  11136. }
  11137. // Stencil test
  11138. if (this._isStencilTestDirty) {
  11139. if (this.stencilTest) {
  11140. gl.enable(gl.STENCIL_TEST);
  11141. }
  11142. else {
  11143. gl.disable(gl.STENCIL_TEST);
  11144. }
  11145. this._isStencilTestDirty = false;
  11146. }
  11147. // Stencil mask
  11148. if (this._isStencilMaskDirty) {
  11149. gl.stencilMask(this.stencilMask);
  11150. this._isStencilMaskDirty = false;
  11151. }
  11152. // Stencil func
  11153. if (this._isStencilFuncDirty) {
  11154. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11155. this._isStencilFuncDirty = false;
  11156. }
  11157. // Stencil op
  11158. if (this._isStencilOpDirty) {
  11159. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11160. this._isStencilOpDirty = false;
  11161. }
  11162. };
  11163. return _StencilState;
  11164. }());
  11165. BABYLON._StencilState = _StencilState;
  11166. })(BABYLON || (BABYLON = {}));
  11167. //# sourceMappingURL=babylon.stencilState.js.map
  11168. var __assign = (this && this.__assign) || function () {
  11169. __assign = Object.assign || function(t) {
  11170. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11171. s = arguments[i];
  11172. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11173. t[p] = s[p];
  11174. }
  11175. return t;
  11176. };
  11177. return __assign.apply(this, arguments);
  11178. };
  11179. var BABYLON;
  11180. (function (BABYLON) {
  11181. /**
  11182. * Keeps track of all the buffer info used in engine.
  11183. */
  11184. var BufferPointer = /** @class */ (function () {
  11185. function BufferPointer() {
  11186. }
  11187. return BufferPointer;
  11188. }());
  11189. /**
  11190. * Interface for attribute information associated with buffer instanciation
  11191. */
  11192. var InstancingAttributeInfo = /** @class */ (function () {
  11193. function InstancingAttributeInfo() {
  11194. }
  11195. return InstancingAttributeInfo;
  11196. }());
  11197. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11198. /**
  11199. * Define options used to create a render target texture
  11200. */
  11201. var RenderTargetCreationOptions = /** @class */ (function () {
  11202. function RenderTargetCreationOptions() {
  11203. }
  11204. return RenderTargetCreationOptions;
  11205. }());
  11206. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11207. /**
  11208. * Define options used to create a depth texture
  11209. */
  11210. var DepthTextureCreationOptions = /** @class */ (function () {
  11211. function DepthTextureCreationOptions() {
  11212. }
  11213. return DepthTextureCreationOptions;
  11214. }());
  11215. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11216. /**
  11217. * Class used to describe the capabilities of the engine relatively to the current browser
  11218. */
  11219. var EngineCapabilities = /** @class */ (function () {
  11220. function EngineCapabilities() {
  11221. }
  11222. return EngineCapabilities;
  11223. }());
  11224. BABYLON.EngineCapabilities = EngineCapabilities;
  11225. /**
  11226. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11227. */
  11228. var Engine = /** @class */ (function () {
  11229. /**
  11230. * Creates a new engine
  11231. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11232. * @param antialias defines enable antialiasing (default: false)
  11233. * @param options defines further options to be sent to the getContext() function
  11234. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11235. */
  11236. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11237. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11238. var _this = this;
  11239. // Public members
  11240. /**
  11241. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11242. */
  11243. this.forcePOTTextures = false;
  11244. /**
  11245. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11246. */
  11247. this.isFullscreen = false;
  11248. /**
  11249. * Gets a boolean indicating if the pointer is currently locked
  11250. */
  11251. this.isPointerLock = false;
  11252. /**
  11253. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11254. */
  11255. this.cullBackFaces = true;
  11256. /**
  11257. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11258. */
  11259. this.renderEvenInBackground = true;
  11260. /**
  11261. * Gets or sets a boolean indicating that cache can be kept between frames
  11262. */
  11263. this.preventCacheWipeBetweenFrames = false;
  11264. /**
  11265. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11266. **/
  11267. this.enableOfflineSupport = false;
  11268. /**
  11269. * 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)
  11270. **/
  11271. this.disableManifestCheck = false;
  11272. /**
  11273. * Gets the list of created scenes
  11274. */
  11275. this.scenes = new Array();
  11276. /**
  11277. * Gets the list of created postprocesses
  11278. */
  11279. this.postProcesses = new Array();
  11280. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11281. this.validateShaderPrograms = false;
  11282. // Observables
  11283. /**
  11284. * Observable event triggered each time the rendering canvas is resized
  11285. */
  11286. this.onResizeObservable = new BABYLON.Observable();
  11287. /**
  11288. * Observable event triggered each time the canvas loses focus
  11289. */
  11290. this.onCanvasBlurObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable event triggered each time the canvas gains focus
  11293. */
  11294. this.onCanvasFocusObservable = new BABYLON.Observable();
  11295. /**
  11296. * Observable event triggered each time the canvas receives pointerout event
  11297. */
  11298. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11299. /**
  11300. * Observable event triggered before each texture is initialized
  11301. */
  11302. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11303. //WebVR
  11304. this._vrDisplay = undefined;
  11305. this._vrSupported = false;
  11306. this._vrExclusivePointerMode = false;
  11307. // Uniform buffers list
  11308. /**
  11309. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11310. */
  11311. this.disableUniformBuffers = false;
  11312. /** @hidden */
  11313. this._uniformBuffers = new Array();
  11314. // Observables
  11315. /**
  11316. * Observable raised when the engine begins a new frame
  11317. */
  11318. this.onBeginFrameObservable = new BABYLON.Observable();
  11319. /**
  11320. * Observable raised when the engine ends the current frame
  11321. */
  11322. this.onEndFrameObservable = new BABYLON.Observable();
  11323. /**
  11324. * Observable raised when the engine is about to compile a shader
  11325. */
  11326. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11327. /**
  11328. * Observable raised when the engine has jsut compiled a shader
  11329. */
  11330. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11331. this._windowIsBackground = false;
  11332. this._webGLVersion = 1.0;
  11333. /** @hidden */
  11334. this._badOS = false;
  11335. /** @hidden */
  11336. this._badDesktopOS = false;
  11337. /**
  11338. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11339. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11340. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11341. */
  11342. this.disableTextureBindingOptimization = false;
  11343. /**
  11344. * Observable signaled when VR display mode changes
  11345. */
  11346. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11347. /**
  11348. * Observable signaled when VR request present is complete
  11349. */
  11350. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11351. /**
  11352. * Observable signaled when VR request present starts
  11353. */
  11354. this.onVRRequestPresentStart = new BABYLON.Observable();
  11355. this._colorWrite = true;
  11356. /** @hidden */
  11357. this._drawCalls = new BABYLON.PerfCounter();
  11358. /** @hidden */
  11359. this._textureCollisions = new BABYLON.PerfCounter();
  11360. this._renderingQueueLaunched = false;
  11361. this._activeRenderLoops = new Array();
  11362. // Deterministic lockstepMaxSteps
  11363. this._deterministicLockstep = false;
  11364. this._lockstepMaxSteps = 4;
  11365. // Lost context
  11366. /**
  11367. * Observable signaled when a context lost event is raised
  11368. */
  11369. this.onContextLostObservable = new BABYLON.Observable();
  11370. /**
  11371. * Observable signaled when a context restored event is raised
  11372. */
  11373. this.onContextRestoredObservable = new BABYLON.Observable();
  11374. this._contextWasLost = false;
  11375. this._doNotHandleContextLost = false;
  11376. // FPS
  11377. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11378. this._fps = 60;
  11379. this._deltaTime = 0;
  11380. /**
  11381. * Turn this value on if you want to pause FPS computation when in background
  11382. */
  11383. this.disablePerformanceMonitorInBackground = false;
  11384. // States
  11385. /** @hidden */
  11386. this._depthCullingState = new BABYLON._DepthCullingState();
  11387. /** @hidden */
  11388. this._stencilState = new BABYLON._StencilState();
  11389. /** @hidden */
  11390. this._alphaState = new BABYLON._AlphaState();
  11391. /** @hidden */
  11392. this._alphaMode = Engine.ALPHA_DISABLE;
  11393. // Cache
  11394. this._internalTexturesCache = new Array();
  11395. /** @hidden */
  11396. this._activeChannel = 0;
  11397. this._currentTextureChannel = -1;
  11398. /** @hidden */
  11399. this._boundTexturesCache = {};
  11400. this._compiledEffects = {};
  11401. this._vertexAttribArraysEnabled = [];
  11402. this._uintIndicesCurrentlySet = false;
  11403. this._currentBoundBuffer = new Array();
  11404. /** @hidden */
  11405. this._currentFramebuffer = null;
  11406. this._currentBufferPointers = new Array();
  11407. this._currentInstanceLocations = new Array();
  11408. this._currentInstanceBuffers = new Array();
  11409. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11410. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11411. this._vaoRecordInProgress = false;
  11412. this._mustWipeVertexAttributes = false;
  11413. this._nextFreeTextureSlots = new Array();
  11414. this._maxSimultaneousTextures = 0;
  11415. this._activeRequests = new Array();
  11416. // Hardware supported Compressed Textures
  11417. this._texturesSupported = new Array();
  11418. /**
  11419. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11420. */
  11421. this.premultipliedAlpha = true;
  11422. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11423. this._onVRFullScreenTriggered = function () {
  11424. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11425. //get the old size before we change
  11426. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11427. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11428. //get the width and height, change the render size
  11429. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11430. _this.setHardwareScalingLevel(1);
  11431. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11432. }
  11433. else {
  11434. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11435. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11436. }
  11437. };
  11438. this._unpackFlipYCached = null;
  11439. this._boundUniforms = {};
  11440. // Register promises
  11441. BABYLON.PromisePolyfill.Apply();
  11442. var canvas = null;
  11443. Engine.Instances.push(this);
  11444. if (!canvasOrContext) {
  11445. return;
  11446. }
  11447. options = options || {};
  11448. if (canvasOrContext.getContext) {
  11449. canvas = canvasOrContext;
  11450. this._renderingCanvas = canvas;
  11451. if (antialias != null) {
  11452. options.antialias = antialias;
  11453. }
  11454. if (options.deterministicLockstep === undefined) {
  11455. options.deterministicLockstep = false;
  11456. }
  11457. if (options.lockstepMaxSteps === undefined) {
  11458. options.lockstepMaxSteps = 4;
  11459. }
  11460. if (options.preserveDrawingBuffer === undefined) {
  11461. options.preserveDrawingBuffer = false;
  11462. }
  11463. if (options.audioEngine === undefined) {
  11464. options.audioEngine = true;
  11465. }
  11466. if (options.stencil === undefined) {
  11467. options.stencil = true;
  11468. }
  11469. if (options.premultipliedAlpha === false) {
  11470. this.premultipliedAlpha = false;
  11471. }
  11472. this._deterministicLockstep = options.deterministicLockstep;
  11473. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11474. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11475. // Exceptions
  11476. if (navigator && navigator.userAgent) {
  11477. var ua = navigator.userAgent;
  11478. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11479. var exception = _a[_i];
  11480. var key = exception.key;
  11481. var targets = exception.targets;
  11482. if (ua.indexOf(key) > -1) {
  11483. if (exception.capture && exception.captureConstraint) {
  11484. var capture = exception.capture;
  11485. var constraint = exception.captureConstraint;
  11486. var regex = new RegExp(capture);
  11487. var matches = regex.exec(ua);
  11488. if (matches && matches.length > 0) {
  11489. var capturedValue = parseInt(matches[matches.length - 1]);
  11490. if (capturedValue >= constraint) {
  11491. continue;
  11492. }
  11493. }
  11494. }
  11495. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11496. var target = targets_1[_b];
  11497. switch (target) {
  11498. case "uniformBuffer":
  11499. this.disableUniformBuffers = true;
  11500. break;
  11501. case "textureBindingOptimization":
  11502. this.disableTextureBindingOptimization = true;
  11503. break;
  11504. }
  11505. }
  11506. }
  11507. }
  11508. }
  11509. // GL
  11510. if (!options.disableWebGL2Support) {
  11511. try {
  11512. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11513. if (this._gl) {
  11514. this._webGLVersion = 2.0;
  11515. }
  11516. }
  11517. catch (e) {
  11518. // Do nothing
  11519. }
  11520. }
  11521. if (!this._gl) {
  11522. if (!canvas) {
  11523. throw new Error("The provided canvas is null or undefined.");
  11524. }
  11525. try {
  11526. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11527. }
  11528. catch (e) {
  11529. throw new Error("WebGL not supported");
  11530. }
  11531. }
  11532. if (!this._gl) {
  11533. throw new Error("WebGL not supported");
  11534. }
  11535. this._onCanvasFocus = function () {
  11536. _this.onCanvasFocusObservable.notifyObservers(_this);
  11537. };
  11538. this._onCanvasBlur = function () {
  11539. _this.onCanvasBlurObservable.notifyObservers(_this);
  11540. };
  11541. canvas.addEventListener("focus", this._onCanvasFocus);
  11542. canvas.addEventListener("blur", this._onCanvasBlur);
  11543. this._onBlur = function () {
  11544. if (_this.disablePerformanceMonitorInBackground) {
  11545. _this._performanceMonitor.disable();
  11546. }
  11547. _this._windowIsBackground = true;
  11548. };
  11549. this._onFocus = function () {
  11550. if (_this.disablePerformanceMonitorInBackground) {
  11551. _this._performanceMonitor.enable();
  11552. }
  11553. _this._windowIsBackground = false;
  11554. };
  11555. this._onCanvasPointerOut = function (ev) {
  11556. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11557. };
  11558. window.addEventListener("blur", this._onBlur);
  11559. window.addEventListener("focus", this._onFocus);
  11560. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11561. // Context lost
  11562. if (!this._doNotHandleContextLost) {
  11563. this._onContextLost = function (evt) {
  11564. evt.preventDefault();
  11565. _this._contextWasLost = true;
  11566. BABYLON.Tools.Warn("WebGL context lost.");
  11567. _this.onContextLostObservable.notifyObservers(_this);
  11568. };
  11569. this._onContextRestored = function (evt) {
  11570. // Adding a timeout to avoid race condition at browser level
  11571. setTimeout(function () {
  11572. // Rebuild gl context
  11573. _this._initGLContext();
  11574. // Rebuild effects
  11575. _this._rebuildEffects();
  11576. // Rebuild textures
  11577. _this._rebuildInternalTextures();
  11578. // Rebuild buffers
  11579. _this._rebuildBuffers();
  11580. // Cache
  11581. _this.wipeCaches(true);
  11582. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11583. _this.onContextRestoredObservable.notifyObservers(_this);
  11584. _this._contextWasLost = false;
  11585. }, 0);
  11586. };
  11587. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11588. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11589. }
  11590. }
  11591. else {
  11592. this._gl = canvasOrContext;
  11593. this._renderingCanvas = this._gl.canvas;
  11594. if (this._gl.renderbufferStorageMultisample) {
  11595. this._webGLVersion = 2.0;
  11596. }
  11597. options.stencil = this._gl.getContextAttributes().stencil;
  11598. }
  11599. // Viewport
  11600. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11601. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11602. this.resize();
  11603. this._isStencilEnable = options.stencil ? true : false;
  11604. this._initGLContext();
  11605. if (canvas) {
  11606. // Fullscreen
  11607. this._onFullscreenChange = function () {
  11608. if (document.fullscreen !== undefined) {
  11609. _this.isFullscreen = document.fullscreen;
  11610. }
  11611. else if (document.mozFullScreen !== undefined) {
  11612. _this.isFullscreen = document.mozFullScreen;
  11613. }
  11614. else if (document.webkitIsFullScreen !== undefined) {
  11615. _this.isFullscreen = document.webkitIsFullScreen;
  11616. }
  11617. else if (document.msIsFullScreen !== undefined) {
  11618. _this.isFullscreen = document.msIsFullScreen;
  11619. }
  11620. // Pointer lock
  11621. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11622. canvas.requestPointerLock = canvas.requestPointerLock ||
  11623. canvas.msRequestPointerLock ||
  11624. canvas.mozRequestPointerLock ||
  11625. canvas.webkitRequestPointerLock;
  11626. if (canvas.requestPointerLock) {
  11627. canvas.requestPointerLock();
  11628. }
  11629. }
  11630. };
  11631. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11632. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11633. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11634. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11635. // Pointer lock
  11636. this._onPointerLockChange = function () {
  11637. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11638. document.webkitPointerLockElement === canvas ||
  11639. document.msPointerLockElement === canvas ||
  11640. document.pointerLockElement === canvas);
  11641. };
  11642. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11643. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11644. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11645. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11646. this._onVRDisplayPointerRestricted = function () {
  11647. if (canvas) {
  11648. canvas.requestPointerLock();
  11649. }
  11650. };
  11651. this._onVRDisplayPointerUnrestricted = function () {
  11652. document.exitPointerLock();
  11653. };
  11654. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11655. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11656. }
  11657. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11658. Engine.audioEngine = new BABYLON.AudioEngine();
  11659. }
  11660. // Prepare buffer pointers
  11661. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11662. this._currentBufferPointers[i] = new BufferPointer();
  11663. }
  11664. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11665. // Load WebVR Devices
  11666. if (options.autoEnableWebVR) {
  11667. this.initWebVR();
  11668. }
  11669. // Detect if we are running on a faulty buggy OS.
  11670. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11671. // Detect if we are running on a faulty buggy desktop OS.
  11672. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11673. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11674. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11675. }
  11676. Object.defineProperty(Engine, "LastCreatedEngine", {
  11677. /**
  11678. * Gets the latest created engine
  11679. */
  11680. get: function () {
  11681. if (Engine.Instances.length === 0) {
  11682. return null;
  11683. }
  11684. return Engine.Instances[Engine.Instances.length - 1];
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(Engine, "LastCreatedScene", {
  11690. /**
  11691. * Gets the latest created scene
  11692. */
  11693. get: function () {
  11694. var lastCreatedEngine = Engine.LastCreatedEngine;
  11695. if (!lastCreatedEngine) {
  11696. return null;
  11697. }
  11698. if (lastCreatedEngine.scenes.length === 0) {
  11699. return null;
  11700. }
  11701. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. /**
  11707. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11708. * @param flag defines which part of the materials must be marked as dirty
  11709. * @param predicate defines a predicate used to filter which materials should be affected
  11710. */
  11711. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11712. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11713. var engine = Engine.Instances[engineIndex];
  11714. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11715. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11716. }
  11717. }
  11718. };
  11719. Object.defineProperty(Engine, "Version", {
  11720. /**
  11721. * Returns the current version of the framework
  11722. */
  11723. get: function () {
  11724. return "3.3.0-beta.4";
  11725. },
  11726. enumerable: true,
  11727. configurable: true
  11728. });
  11729. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11730. /**
  11731. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11732. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11733. */
  11734. get: function () {
  11735. return this._vrExclusivePointerMode;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11741. /**
  11742. * Gets a boolean indicating that the engine supports uniform buffers
  11743. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11744. */
  11745. get: function () {
  11746. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11752. /**
  11753. * Gets a boolean indicating that only power of 2 textures are supported
  11754. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11755. */
  11756. get: function () {
  11757. return this._webGLVersion < 2 || this.forcePOTTextures;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11763. /**
  11764. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11765. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11766. */
  11767. get: function () {
  11768. return this._doNotHandleContextLost;
  11769. },
  11770. set: function (value) {
  11771. this._doNotHandleContextLost = value;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11777. /**
  11778. * Gets the performance monitor attached to this engine
  11779. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11780. */
  11781. get: function () {
  11782. return this._performanceMonitor;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11788. /**
  11789. * Gets the list of texture formats supported
  11790. */
  11791. get: function () {
  11792. return this._texturesSupported;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11798. /**
  11799. * Gets the list of texture formats in use
  11800. */
  11801. get: function () {
  11802. return this._textureFormatInUse;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine.prototype, "currentViewport", {
  11808. /**
  11809. * Gets the current viewport
  11810. */
  11811. get: function () {
  11812. return this._cachedViewport;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11818. /**
  11819. * Gets the default empty texture
  11820. */
  11821. get: function () {
  11822. if (!this._emptyTexture) {
  11823. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11824. }
  11825. return this._emptyTexture;
  11826. },
  11827. enumerable: true,
  11828. configurable: true
  11829. });
  11830. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11831. /**
  11832. * Gets the default empty 3D texture
  11833. */
  11834. get: function () {
  11835. if (!this._emptyTexture3D) {
  11836. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11837. }
  11838. return this._emptyTexture3D;
  11839. },
  11840. enumerable: true,
  11841. configurable: true
  11842. });
  11843. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11844. /**
  11845. * Gets the default empty cube texture
  11846. */
  11847. get: function () {
  11848. if (!this._emptyCubeTexture) {
  11849. var faceData = new Uint8Array(4);
  11850. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11851. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11852. }
  11853. return this._emptyCubeTexture;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Engine.prototype._rebuildInternalTextures = function () {
  11859. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11860. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11861. var internalTexture = currentState_1[_i];
  11862. internalTexture._rebuild();
  11863. }
  11864. };
  11865. Engine.prototype._rebuildEffects = function () {
  11866. for (var key in this._compiledEffects) {
  11867. var effect = this._compiledEffects[key];
  11868. effect._prepareEffect();
  11869. }
  11870. BABYLON.Effect.ResetCache();
  11871. };
  11872. Engine.prototype._rebuildBuffers = function () {
  11873. // Index / Vertex
  11874. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11875. var scene = _a[_i];
  11876. scene.resetCachedMaterial();
  11877. scene._rebuildGeometries();
  11878. scene._rebuildTextures();
  11879. }
  11880. // Uniforms
  11881. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11882. var uniformBuffer = _c[_b];
  11883. uniformBuffer._rebuild();
  11884. }
  11885. };
  11886. Engine.prototype._initGLContext = function () {
  11887. // Caps
  11888. this._caps = new EngineCapabilities();
  11889. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11890. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11891. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11892. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11893. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11894. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11895. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11896. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11897. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11898. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11899. // Infos
  11900. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11901. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11902. if (rendererInfo != null) {
  11903. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11904. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11905. }
  11906. if (!this._glVendor) {
  11907. this._glVendor = "Unknown vendor";
  11908. }
  11909. if (!this._glRenderer) {
  11910. this._glRenderer = "Unknown renderer";
  11911. }
  11912. // Constants
  11913. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11914. if (this._gl.RGBA16F !== 0x881A) {
  11915. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11916. }
  11917. if (this._gl.RGBA32F !== 0x8814) {
  11918. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11919. }
  11920. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11921. this._gl.DEPTH24_STENCIL8 = 35056;
  11922. }
  11923. // Extensions
  11924. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11925. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11926. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11927. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11928. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11929. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11930. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11931. 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');
  11932. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11933. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11934. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11935. this._caps.highPrecisionShaderSupported = true;
  11936. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11937. if (this._caps.timerQuery) {
  11938. if (this._webGLVersion === 1) {
  11939. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11940. }
  11941. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11942. }
  11943. // Checks if some of the format renders first to allow the use of webgl inspector.
  11944. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11945. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11946. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11947. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11948. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11949. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11950. if (this._webGLVersion > 1) {
  11951. this._gl.HALF_FLOAT_OES = 0x140B;
  11952. }
  11953. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11954. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11955. // Draw buffers
  11956. if (this._webGLVersion > 1) {
  11957. this._caps.drawBuffersExtension = true;
  11958. }
  11959. else {
  11960. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11961. if (drawBuffersExtension !== null) {
  11962. this._caps.drawBuffersExtension = true;
  11963. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11964. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11965. for (var i = 0; i < 16; i++) {
  11966. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11967. }
  11968. }
  11969. else {
  11970. this._caps.drawBuffersExtension = false;
  11971. }
  11972. }
  11973. // Depth Texture
  11974. if (this._webGLVersion > 1) {
  11975. this._caps.depthTextureExtension = true;
  11976. }
  11977. else {
  11978. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11979. if (depthTextureExtension != null) {
  11980. this._caps.depthTextureExtension = true;
  11981. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11982. }
  11983. }
  11984. // Vertex array object
  11985. if (this._webGLVersion > 1) {
  11986. this._caps.vertexArrayObject = true;
  11987. }
  11988. else {
  11989. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11990. if (vertexArrayObjectExtension != null) {
  11991. this._caps.vertexArrayObject = true;
  11992. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11993. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11994. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11995. }
  11996. else {
  11997. this._caps.vertexArrayObject = false;
  11998. }
  11999. }
  12000. // Instances count
  12001. if (this._webGLVersion > 1) {
  12002. this._caps.instancedArrays = true;
  12003. }
  12004. else {
  12005. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12006. if (instanceExtension != null) {
  12007. this._caps.instancedArrays = true;
  12008. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12009. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12010. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12011. }
  12012. else {
  12013. this._caps.instancedArrays = false;
  12014. }
  12015. }
  12016. // Intelligently add supported compressed formats in order to check for.
  12017. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12018. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12019. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12020. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12021. if (this._caps.astc)
  12022. this.texturesSupported.push('-astc.ktx');
  12023. if (this._caps.s3tc)
  12024. this.texturesSupported.push('-dxt.ktx');
  12025. if (this._caps.pvrtc)
  12026. this.texturesSupported.push('-pvrtc.ktx');
  12027. if (this._caps.etc2)
  12028. this.texturesSupported.push('-etc2.ktx');
  12029. if (this._caps.etc1)
  12030. this.texturesSupported.push('-etc1.ktx');
  12031. if (this._gl.getShaderPrecisionFormat) {
  12032. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12033. if (highp) {
  12034. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12035. }
  12036. }
  12037. // Depth buffer
  12038. this.setDepthBuffer(true);
  12039. this.setDepthFunctionToLessOrEqual();
  12040. this.setDepthWrite(true);
  12041. // Texture maps
  12042. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12043. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12044. this._nextFreeTextureSlots.push(slot);
  12045. }
  12046. };
  12047. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12048. /**
  12049. * Gets version of the current webGL context
  12050. */
  12051. get: function () {
  12052. return this._webGLVersion;
  12053. },
  12054. enumerable: true,
  12055. configurable: true
  12056. });
  12057. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12058. /**
  12059. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12060. */
  12061. get: function () {
  12062. return this._isStencilEnable;
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Engine.prototype._prepareWorkingCanvas = function () {
  12068. if (this._workingCanvas) {
  12069. return;
  12070. }
  12071. this._workingCanvas = document.createElement("canvas");
  12072. var context = this._workingCanvas.getContext("2d");
  12073. if (context) {
  12074. this._workingContext = context;
  12075. }
  12076. };
  12077. /**
  12078. * Reset the texture cache to empty state
  12079. */
  12080. Engine.prototype.resetTextureCache = function () {
  12081. for (var key in this._boundTexturesCache) {
  12082. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12083. continue;
  12084. }
  12085. var boundTexture = this._boundTexturesCache[key];
  12086. if (boundTexture) {
  12087. this._removeDesignatedSlot(boundTexture);
  12088. }
  12089. this._boundTexturesCache[key] = null;
  12090. }
  12091. if (!this.disableTextureBindingOptimization) {
  12092. this._nextFreeTextureSlots = [];
  12093. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12094. this._nextFreeTextureSlots.push(slot);
  12095. }
  12096. }
  12097. this._currentTextureChannel = -1;
  12098. };
  12099. /**
  12100. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12101. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12102. * @returns true if engine is in deterministic lock step mode
  12103. */
  12104. Engine.prototype.isDeterministicLockStep = function () {
  12105. return this._deterministicLockstep;
  12106. };
  12107. /**
  12108. * Gets the max steps when engine is running in deterministic lock step
  12109. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12110. * @returns the max steps
  12111. */
  12112. Engine.prototype.getLockstepMaxSteps = function () {
  12113. return this._lockstepMaxSteps;
  12114. };
  12115. /**
  12116. * Gets an object containing information about the current webGL context
  12117. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12118. */
  12119. Engine.prototype.getGlInfo = function () {
  12120. return {
  12121. vendor: this._glVendor,
  12122. renderer: this._glRenderer,
  12123. version: this._glVersion
  12124. };
  12125. };
  12126. /**
  12127. * Gets current aspect ratio
  12128. * @param camera defines the camera to use to get the aspect ratio
  12129. * @param useScreen defines if screen size must be used (or the current render target if any)
  12130. * @returns a number defining the aspect ratio
  12131. */
  12132. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12133. if (useScreen === void 0) { useScreen = false; }
  12134. var viewport = camera.viewport;
  12135. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12136. };
  12137. /**
  12138. * Gets current screen aspect ratio
  12139. * @returns a number defining the aspect ratio
  12140. */
  12141. Engine.prototype.getScreenAspectRatio = function () {
  12142. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12143. };
  12144. /**
  12145. * Gets the current render width
  12146. * @param useScreen defines if screen size must be used (or the current render target if any)
  12147. * @returns a number defining the current render width
  12148. */
  12149. Engine.prototype.getRenderWidth = function (useScreen) {
  12150. if (useScreen === void 0) { useScreen = false; }
  12151. if (!useScreen && this._currentRenderTarget) {
  12152. return this._currentRenderTarget.width;
  12153. }
  12154. return this._gl.drawingBufferWidth;
  12155. };
  12156. /**
  12157. * Gets the current render height
  12158. * @param useScreen defines if screen size must be used (or the current render target if any)
  12159. * @returns a number defining the current render height
  12160. */
  12161. Engine.prototype.getRenderHeight = function (useScreen) {
  12162. if (useScreen === void 0) { useScreen = false; }
  12163. if (!useScreen && this._currentRenderTarget) {
  12164. return this._currentRenderTarget.height;
  12165. }
  12166. return this._gl.drawingBufferHeight;
  12167. };
  12168. /**
  12169. * Gets the HTML canvas attached with the current webGL context
  12170. * @returns a HTML canvas
  12171. */
  12172. Engine.prototype.getRenderingCanvas = function () {
  12173. return this._renderingCanvas;
  12174. };
  12175. /**
  12176. * Gets the client rect of the HTML canvas attached with the current webGL context
  12177. * @returns a client rectanglee
  12178. */
  12179. Engine.prototype.getRenderingCanvasClientRect = function () {
  12180. if (!this._renderingCanvas) {
  12181. return null;
  12182. }
  12183. return this._renderingCanvas.getBoundingClientRect();
  12184. };
  12185. /**
  12186. * Defines the hardware scaling level.
  12187. * By default the hardware scaling level is computed from the window device ratio.
  12188. * 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.
  12189. * @param level defines the level to use
  12190. */
  12191. Engine.prototype.setHardwareScalingLevel = function (level) {
  12192. this._hardwareScalingLevel = level;
  12193. this.resize();
  12194. };
  12195. /**
  12196. * Gets the current hardware scaling level.
  12197. * By default the hardware scaling level is computed from the window device ratio.
  12198. * 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.
  12199. * @returns a number indicating the current hardware scaling level
  12200. */
  12201. Engine.prototype.getHardwareScalingLevel = function () {
  12202. return this._hardwareScalingLevel;
  12203. };
  12204. /**
  12205. * Gets the list of loaded textures
  12206. * @returns an array containing all loaded textures
  12207. */
  12208. Engine.prototype.getLoadedTexturesCache = function () {
  12209. return this._internalTexturesCache;
  12210. };
  12211. /**
  12212. * Gets the object containing all engine capabilities
  12213. * @returns the EngineCapabilities object
  12214. */
  12215. Engine.prototype.getCaps = function () {
  12216. return this._caps;
  12217. };
  12218. Object.defineProperty(Engine.prototype, "drawCalls", {
  12219. /** @hidden */
  12220. get: function () {
  12221. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12222. return 0;
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12228. /** @hidden */
  12229. get: function () {
  12230. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12231. return null;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. /**
  12237. * Gets the current depth function
  12238. * @returns a number defining the depth function
  12239. */
  12240. Engine.prototype.getDepthFunction = function () {
  12241. return this._depthCullingState.depthFunc;
  12242. };
  12243. /**
  12244. * Sets the current depth function
  12245. * @param depthFunc defines the function to use
  12246. */
  12247. Engine.prototype.setDepthFunction = function (depthFunc) {
  12248. this._depthCullingState.depthFunc = depthFunc;
  12249. };
  12250. /**
  12251. * Sets the current depth function to GREATER
  12252. */
  12253. Engine.prototype.setDepthFunctionToGreater = function () {
  12254. this._depthCullingState.depthFunc = this._gl.GREATER;
  12255. };
  12256. /**
  12257. * Sets the current depth function to GEQUAL
  12258. */
  12259. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12260. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12261. };
  12262. /**
  12263. * Sets the current depth function to LESS
  12264. */
  12265. Engine.prototype.setDepthFunctionToLess = function () {
  12266. this._depthCullingState.depthFunc = this._gl.LESS;
  12267. };
  12268. /**
  12269. * Sets the current depth function to LEQUAL
  12270. */
  12271. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12272. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12273. };
  12274. /**
  12275. * Gets a boolean indicating if stencil buffer is enabled
  12276. * @returns the current stencil buffer state
  12277. */
  12278. Engine.prototype.getStencilBuffer = function () {
  12279. return this._stencilState.stencilTest;
  12280. };
  12281. /**
  12282. * Enable or disable the stencil buffer
  12283. * @param enable defines if the stencil buffer must be enabled or disabled
  12284. */
  12285. Engine.prototype.setStencilBuffer = function (enable) {
  12286. this._stencilState.stencilTest = enable;
  12287. };
  12288. /**
  12289. * Gets the current stencil mask
  12290. * @returns a number defining the new stencil mask to use
  12291. */
  12292. Engine.prototype.getStencilMask = function () {
  12293. return this._stencilState.stencilMask;
  12294. };
  12295. /**
  12296. * Sets the current stencil mask
  12297. * @param mask defines the new stencil mask to use
  12298. */
  12299. Engine.prototype.setStencilMask = function (mask) {
  12300. this._stencilState.stencilMask = mask;
  12301. };
  12302. /**
  12303. * Gets the current stencil function
  12304. * @returns a number defining the stencil function to use
  12305. */
  12306. Engine.prototype.getStencilFunction = function () {
  12307. return this._stencilState.stencilFunc;
  12308. };
  12309. /**
  12310. * Gets the current stencil reference value
  12311. * @returns a number defining the stencil reference value to use
  12312. */
  12313. Engine.prototype.getStencilFunctionReference = function () {
  12314. return this._stencilState.stencilFuncRef;
  12315. };
  12316. /**
  12317. * Gets the current stencil mask
  12318. * @returns a number defining the stencil mask to use
  12319. */
  12320. Engine.prototype.getStencilFunctionMask = function () {
  12321. return this._stencilState.stencilFuncMask;
  12322. };
  12323. /**
  12324. * Sets the current stencil function
  12325. * @param stencilFunc defines the new stencil function to use
  12326. */
  12327. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12328. this._stencilState.stencilFunc = stencilFunc;
  12329. };
  12330. /**
  12331. * Sets the current stencil reference
  12332. * @param reference defines the new stencil reference to use
  12333. */
  12334. Engine.prototype.setStencilFunctionReference = function (reference) {
  12335. this._stencilState.stencilFuncRef = reference;
  12336. };
  12337. /**
  12338. * Sets the current stencil mask
  12339. * @param mask defines the new stencil mask to use
  12340. */
  12341. Engine.prototype.setStencilFunctionMask = function (mask) {
  12342. this._stencilState.stencilFuncMask = mask;
  12343. };
  12344. /**
  12345. * Gets the current stencil operation when stencil fails
  12346. * @returns a number defining stencil operation to use when stencil fails
  12347. */
  12348. Engine.prototype.getStencilOperationFail = function () {
  12349. return this._stencilState.stencilOpStencilFail;
  12350. };
  12351. /**
  12352. * Gets the current stencil operation when depth fails
  12353. * @returns a number defining stencil operation to use when depth fails
  12354. */
  12355. Engine.prototype.getStencilOperationDepthFail = function () {
  12356. return this._stencilState.stencilOpDepthFail;
  12357. };
  12358. /**
  12359. * Gets the current stencil operation when stencil passes
  12360. * @returns a number defining stencil operation to use when stencil passes
  12361. */
  12362. Engine.prototype.getStencilOperationPass = function () {
  12363. return this._stencilState.stencilOpStencilDepthPass;
  12364. };
  12365. /**
  12366. * Sets the stencil operation to use when stencil fails
  12367. * @param operation defines the stencil operation to use when stencil fails
  12368. */
  12369. Engine.prototype.setStencilOperationFail = function (operation) {
  12370. this._stencilState.stencilOpStencilFail = operation;
  12371. };
  12372. /**
  12373. * Sets the stencil operation to use when depth fails
  12374. * @param operation defines the stencil operation to use when depth fails
  12375. */
  12376. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12377. this._stencilState.stencilOpDepthFail = operation;
  12378. };
  12379. /**
  12380. * Sets the stencil operation to use when stencil passes
  12381. * @param operation defines the stencil operation to use when stencil passes
  12382. */
  12383. Engine.prototype.setStencilOperationPass = function (operation) {
  12384. this._stencilState.stencilOpStencilDepthPass = operation;
  12385. };
  12386. /**
  12387. * Sets a boolean indicating if the dithering state is enabled or disabled
  12388. * @param value defines the dithering state
  12389. */
  12390. Engine.prototype.setDitheringState = function (value) {
  12391. if (value) {
  12392. this._gl.enable(this._gl.DITHER);
  12393. }
  12394. else {
  12395. this._gl.disable(this._gl.DITHER);
  12396. }
  12397. };
  12398. /**
  12399. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12400. * @param value defines the rasterizer state
  12401. */
  12402. Engine.prototype.setRasterizerState = function (value) {
  12403. if (value) {
  12404. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12405. }
  12406. else {
  12407. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12408. }
  12409. };
  12410. /**
  12411. * stop executing a render loop function and remove it from the execution array
  12412. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12413. */
  12414. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12415. if (!renderFunction) {
  12416. this._activeRenderLoops = [];
  12417. return;
  12418. }
  12419. var index = this._activeRenderLoops.indexOf(renderFunction);
  12420. if (index >= 0) {
  12421. this._activeRenderLoops.splice(index, 1);
  12422. }
  12423. };
  12424. /** @hidden */
  12425. Engine.prototype._renderLoop = function () {
  12426. if (!this._contextWasLost) {
  12427. var shouldRender = true;
  12428. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12429. shouldRender = false;
  12430. }
  12431. if (shouldRender) {
  12432. // Start new frame
  12433. this.beginFrame();
  12434. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12435. var renderFunction = this._activeRenderLoops[index];
  12436. renderFunction();
  12437. }
  12438. // Present
  12439. this.endFrame();
  12440. }
  12441. }
  12442. if (this._activeRenderLoops.length > 0) {
  12443. // Register new frame
  12444. var requester = null;
  12445. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12446. requester = this._vrDisplay;
  12447. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12448. }
  12449. else {
  12450. this._renderingQueueLaunched = false;
  12451. }
  12452. };
  12453. /**
  12454. * Register and execute a render loop. The engine can have more than one render function
  12455. * @param renderFunction defines the function to continuously execute
  12456. */
  12457. Engine.prototype.runRenderLoop = function (renderFunction) {
  12458. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12459. return;
  12460. }
  12461. this._activeRenderLoops.push(renderFunction);
  12462. if (!this._renderingQueueLaunched) {
  12463. this._renderingQueueLaunched = true;
  12464. this._bindedRenderFunction = this._renderLoop.bind(this);
  12465. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12466. }
  12467. };
  12468. /**
  12469. * Toggle full screen mode
  12470. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12471. * @param options defines an option object to be sent to the requestFullscreen function
  12472. */
  12473. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12474. if (this.isFullscreen) {
  12475. BABYLON.Tools.ExitFullscreen();
  12476. }
  12477. else {
  12478. this._pointerLockRequested = requestPointerLock;
  12479. if (this._renderingCanvas) {
  12480. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12481. }
  12482. }
  12483. };
  12484. /**
  12485. * Clear the current render buffer or the current render target (if any is set up)
  12486. * @param color defines the color to use
  12487. * @param backBuffer defines if the back buffer must be cleared
  12488. * @param depth defines if the depth buffer must be cleared
  12489. * @param stencil defines if the stencil buffer must be cleared
  12490. */
  12491. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12492. if (stencil === void 0) { stencil = false; }
  12493. this.applyStates();
  12494. var mode = 0;
  12495. if (backBuffer && color) {
  12496. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12497. mode |= this._gl.COLOR_BUFFER_BIT;
  12498. }
  12499. if (depth) {
  12500. this._gl.clearDepth(1.0);
  12501. mode |= this._gl.DEPTH_BUFFER_BIT;
  12502. }
  12503. if (stencil) {
  12504. this._gl.clearStencil(0);
  12505. mode |= this._gl.STENCIL_BUFFER_BIT;
  12506. }
  12507. this._gl.clear(mode);
  12508. };
  12509. /**
  12510. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12511. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12512. * @param y defines the y-coordinate of the corner of the clear rectangle
  12513. * @param width defines the width of the clear rectangle
  12514. * @param height defines the height of the clear rectangle
  12515. * @param clearColor defines the clear color
  12516. */
  12517. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12518. var gl = this._gl;
  12519. // Save state
  12520. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12521. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12522. // Change state
  12523. gl.enable(gl.SCISSOR_TEST);
  12524. gl.scissor(x, y, width, height);
  12525. // Clear
  12526. this.clear(clearColor, true, true, true);
  12527. // Restore state
  12528. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12529. if (curScissor === true) {
  12530. gl.enable(gl.SCISSOR_TEST);
  12531. }
  12532. else {
  12533. gl.disable(gl.SCISSOR_TEST);
  12534. }
  12535. };
  12536. /** @hidden */
  12537. Engine.prototype._viewport = function (x, y, width, height) {
  12538. if (x !== this._viewportCached.x ||
  12539. y !== this._viewportCached.y ||
  12540. width !== this._viewportCached.z ||
  12541. height !== this._viewportCached.w) {
  12542. this._viewportCached.x = x;
  12543. this._viewportCached.y = y;
  12544. this._viewportCached.z = width;
  12545. this._viewportCached.w = height;
  12546. this._gl.viewport(x, y, width, height);
  12547. }
  12548. };
  12549. /**
  12550. * Set the WebGL's viewport
  12551. * @param viewport defines the viewport element to be used
  12552. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12553. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12554. */
  12555. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12556. var width = requiredWidth || this.getRenderWidth();
  12557. var height = requiredHeight || this.getRenderHeight();
  12558. var x = viewport.x || 0;
  12559. var y = viewport.y || 0;
  12560. this._cachedViewport = viewport;
  12561. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12562. };
  12563. /**
  12564. * Directly set the WebGL Viewport
  12565. * @param x defines the x coordinate of the viewport (in screen space)
  12566. * @param y defines the y coordinate of the viewport (in screen space)
  12567. * @param width defines the width of the viewport (in screen space)
  12568. * @param height defines the height of the viewport (in screen space)
  12569. * @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
  12570. */
  12571. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12572. var currentViewport = this._cachedViewport;
  12573. this._cachedViewport = null;
  12574. this._viewport(x, y, width, height);
  12575. return currentViewport;
  12576. };
  12577. /**
  12578. * Begin a new frame
  12579. */
  12580. Engine.prototype.beginFrame = function () {
  12581. this.onBeginFrameObservable.notifyObservers(this);
  12582. this._measureFps();
  12583. };
  12584. /**
  12585. * Enf the current frame
  12586. */
  12587. Engine.prototype.endFrame = function () {
  12588. // Force a flush in case we are using a bad OS.
  12589. if (this._badOS) {
  12590. this.flushFramebuffer();
  12591. }
  12592. // Submit frame to the vr device, if enabled
  12593. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12594. // TODO: We should only submit the frame if we read frameData successfully.
  12595. this._vrDisplay.submitFrame();
  12596. }
  12597. this.onEndFrameObservable.notifyObservers(this);
  12598. };
  12599. /**
  12600. * Resize the view according to the canvas' size
  12601. */
  12602. Engine.prototype.resize = function () {
  12603. // We're not resizing the size of the canvas while in VR mode & presenting
  12604. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12605. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12606. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12607. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12608. }
  12609. };
  12610. /**
  12611. * Force a specific size of the canvas
  12612. * @param width defines the new canvas' width
  12613. * @param height defines the new canvas' height
  12614. */
  12615. Engine.prototype.setSize = function (width, height) {
  12616. if (!this._renderingCanvas) {
  12617. return;
  12618. }
  12619. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12620. return;
  12621. }
  12622. this._renderingCanvas.width = width;
  12623. this._renderingCanvas.height = height;
  12624. for (var index = 0; index < this.scenes.length; index++) {
  12625. var scene = this.scenes[index];
  12626. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12627. var cam = scene.cameras[camIndex];
  12628. cam._currentRenderId = 0;
  12629. }
  12630. }
  12631. if (this.onResizeObservable.hasObservers) {
  12632. this.onResizeObservable.notifyObservers(this);
  12633. }
  12634. };
  12635. // WebVR functions
  12636. /**
  12637. * Gets a boolean indicating if a webVR device was detected
  12638. * @returns true if a webVR device was detected
  12639. */
  12640. Engine.prototype.isVRDevicePresent = function () {
  12641. return !!this._vrDisplay;
  12642. };
  12643. /**
  12644. * Gets the current webVR device
  12645. * @returns the current webVR device (or null)
  12646. */
  12647. Engine.prototype.getVRDevice = function () {
  12648. return this._vrDisplay;
  12649. };
  12650. /**
  12651. * Initializes a webVR display and starts listening to display change events
  12652. * The onVRDisplayChangedObservable will be notified upon these changes
  12653. * @returns The onVRDisplayChangedObservable
  12654. */
  12655. Engine.prototype.initWebVR = function () {
  12656. this.initWebVRAsync();
  12657. return this.onVRDisplayChangedObservable;
  12658. };
  12659. /**
  12660. * Initializes a webVR display and starts listening to display change events
  12661. * The onVRDisplayChangedObservable will be notified upon these changes
  12662. * @returns A promise containing a VRDisplay and if vr is supported
  12663. */
  12664. Engine.prototype.initWebVRAsync = function () {
  12665. var _this = this;
  12666. var notifyObservers = function () {
  12667. var eventArgs = {
  12668. vrDisplay: _this._vrDisplay,
  12669. vrSupported: _this._vrSupported
  12670. };
  12671. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12672. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12673. };
  12674. if (!this._onVrDisplayConnect) {
  12675. this._onVrDisplayConnect = function (event) {
  12676. _this._vrDisplay = event.display;
  12677. notifyObservers();
  12678. };
  12679. this._onVrDisplayDisconnect = function () {
  12680. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12681. _this._vrDisplay = undefined;
  12682. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12683. notifyObservers();
  12684. };
  12685. this._onVrDisplayPresentChange = function () {
  12686. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12687. };
  12688. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12689. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12690. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12691. }
  12692. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12693. this._webVRInitPromise.then(notifyObservers);
  12694. return this._webVRInitPromise;
  12695. };
  12696. /**
  12697. * Call this function to switch to webVR mode
  12698. * Will do nothing if webVR is not supported or if there is no webVR device
  12699. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12700. */
  12701. Engine.prototype.enableVR = function () {
  12702. var _this = this;
  12703. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12704. var onResolved = function () {
  12705. _this.onVRRequestPresentComplete.notifyObservers(true);
  12706. _this._onVRFullScreenTriggered();
  12707. };
  12708. var onRejected = function () {
  12709. _this.onVRRequestPresentComplete.notifyObservers(false);
  12710. };
  12711. this.onVRRequestPresentStart.notifyObservers(this);
  12712. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12713. }
  12714. };
  12715. /**
  12716. * Call this function to leave webVR mode
  12717. * Will do nothing if webVR is not supported or if there is no webVR device
  12718. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12719. */
  12720. Engine.prototype.disableVR = function () {
  12721. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12722. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12723. }
  12724. };
  12725. Engine.prototype._getVRDisplaysAsync = function () {
  12726. var _this = this;
  12727. return new Promise(function (res, rej) {
  12728. if (navigator.getVRDisplays) {
  12729. navigator.getVRDisplays().then(function (devices) {
  12730. _this._vrSupported = true;
  12731. // note that devices may actually be an empty array. This is fine;
  12732. // we expect this._vrDisplay to be undefined in this case.
  12733. _this._vrDisplay = devices[0];
  12734. res({
  12735. vrDisplay: _this._vrDisplay,
  12736. vrSupported: _this._vrSupported
  12737. });
  12738. });
  12739. }
  12740. else {
  12741. _this._vrDisplay = undefined;
  12742. _this._vrSupported = false;
  12743. res({
  12744. vrDisplay: _this._vrDisplay,
  12745. vrSupported: _this._vrSupported
  12746. });
  12747. }
  12748. });
  12749. };
  12750. /**
  12751. * Binds the frame buffer to the specified texture.
  12752. * @param texture The texture to render to or null for the default canvas
  12753. * @param faceIndex The face of the texture to render to in case of cube texture
  12754. * @param requiredWidth The width of the target to render to
  12755. * @param requiredHeight The height of the target to render to
  12756. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12757. * @param depthStencilTexture The depth stencil texture to use to render
  12758. * @param lodLevel defines le lod level to bind to the frame buffer
  12759. */
  12760. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12761. if (lodLevel === void 0) { lodLevel = 0; }
  12762. if (this._currentRenderTarget) {
  12763. this.unBindFramebuffer(this._currentRenderTarget);
  12764. }
  12765. this._currentRenderTarget = texture;
  12766. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12767. var gl = this._gl;
  12768. if (texture.isCube) {
  12769. if (faceIndex === undefined) {
  12770. faceIndex = 0;
  12771. }
  12772. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12773. if (depthStencilTexture) {
  12774. if (depthStencilTexture._generateStencilBuffer) {
  12775. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12776. }
  12777. else {
  12778. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12779. }
  12780. }
  12781. }
  12782. if (this._cachedViewport && !forceFullscreenViewport) {
  12783. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12784. }
  12785. else {
  12786. if (!requiredWidth) {
  12787. requiredWidth = texture.width;
  12788. if (lodLevel) {
  12789. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12790. }
  12791. }
  12792. if (!requiredHeight) {
  12793. requiredHeight = texture.height;
  12794. if (lodLevel) {
  12795. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12796. }
  12797. }
  12798. this._viewport(0, 0, requiredWidth, requiredHeight);
  12799. }
  12800. this.wipeCaches();
  12801. };
  12802. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12803. if (this._currentFramebuffer !== framebuffer) {
  12804. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12805. this._currentFramebuffer = framebuffer;
  12806. }
  12807. };
  12808. /**
  12809. * Unbind the current render target texture from the webGL context
  12810. * @param texture defines the render target texture to unbind
  12811. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12812. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12813. */
  12814. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12815. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12816. this._currentRenderTarget = null;
  12817. // If MSAA, we need to bitblt back to main texture
  12818. var gl = this._gl;
  12819. if (texture._MSAAFramebuffer) {
  12820. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12821. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12822. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12823. }
  12824. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12825. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12826. gl.generateMipmap(gl.TEXTURE_2D);
  12827. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12828. }
  12829. if (onBeforeUnbind) {
  12830. if (texture._MSAAFramebuffer) {
  12831. // Bind the correct framebuffer
  12832. this.bindUnboundFramebuffer(texture._framebuffer);
  12833. }
  12834. onBeforeUnbind();
  12835. }
  12836. this.bindUnboundFramebuffer(null);
  12837. };
  12838. /**
  12839. * Unbind a list of render target textures from the webGL context
  12840. * This is used only when drawBuffer extension or webGL2 are active
  12841. * @param textures defines the render target textures to unbind
  12842. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12843. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12844. */
  12845. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12846. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12847. this._currentRenderTarget = null;
  12848. // If MSAA, we need to bitblt back to main texture
  12849. var gl = this._gl;
  12850. if (textures[0]._MSAAFramebuffer) {
  12851. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12852. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12853. var attachments = textures[0]._attachments;
  12854. if (!attachments) {
  12855. attachments = new Array(textures.length);
  12856. textures[0]._attachments = attachments;
  12857. }
  12858. for (var i = 0; i < textures.length; i++) {
  12859. var texture = textures[i];
  12860. for (var j = 0; j < attachments.length; j++) {
  12861. attachments[j] = gl.NONE;
  12862. }
  12863. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12864. gl.readBuffer(attachments[i]);
  12865. gl.drawBuffers(attachments);
  12866. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12867. }
  12868. for (var i = 0; i < attachments.length; i++) {
  12869. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12870. }
  12871. gl.drawBuffers(attachments);
  12872. }
  12873. for (var i = 0; i < textures.length; i++) {
  12874. var texture = textures[i];
  12875. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12876. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12877. gl.generateMipmap(gl.TEXTURE_2D);
  12878. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12879. }
  12880. }
  12881. if (onBeforeUnbind) {
  12882. if (textures[0]._MSAAFramebuffer) {
  12883. // Bind the correct framebuffer
  12884. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12885. }
  12886. onBeforeUnbind();
  12887. }
  12888. this.bindUnboundFramebuffer(null);
  12889. };
  12890. /**
  12891. * Force the mipmap generation for the given render target texture
  12892. * @param texture defines the render target texture to use
  12893. */
  12894. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12895. if (texture.generateMipMaps) {
  12896. var gl = this._gl;
  12897. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12898. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12900. }
  12901. };
  12902. /**
  12903. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12904. */
  12905. Engine.prototype.flushFramebuffer = function () {
  12906. this._gl.flush();
  12907. };
  12908. /**
  12909. * Unbind the current render target and bind the default framebuffer
  12910. */
  12911. Engine.prototype.restoreDefaultFramebuffer = function () {
  12912. if (this._currentRenderTarget) {
  12913. this.unBindFramebuffer(this._currentRenderTarget);
  12914. }
  12915. else {
  12916. this.bindUnboundFramebuffer(null);
  12917. }
  12918. if (this._cachedViewport) {
  12919. this.setViewport(this._cachedViewport);
  12920. }
  12921. this.wipeCaches();
  12922. };
  12923. // UBOs
  12924. /**
  12925. * Create an uniform buffer
  12926. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12927. * @param elements defines the content of the uniform buffer
  12928. * @returns the webGL uniform buffer
  12929. */
  12930. Engine.prototype.createUniformBuffer = function (elements) {
  12931. var ubo = this._gl.createBuffer();
  12932. if (!ubo) {
  12933. throw new Error("Unable to create uniform buffer");
  12934. }
  12935. this.bindUniformBuffer(ubo);
  12936. if (elements instanceof Float32Array) {
  12937. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12938. }
  12939. else {
  12940. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12941. }
  12942. this.bindUniformBuffer(null);
  12943. ubo.references = 1;
  12944. return ubo;
  12945. };
  12946. /**
  12947. * Create a dynamic uniform buffer
  12948. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12949. * @param elements defines the content of the uniform buffer
  12950. * @returns the webGL uniform buffer
  12951. */
  12952. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12953. var ubo = this._gl.createBuffer();
  12954. if (!ubo) {
  12955. throw new Error("Unable to create dynamic uniform buffer");
  12956. }
  12957. this.bindUniformBuffer(ubo);
  12958. if (elements instanceof Float32Array) {
  12959. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12960. }
  12961. else {
  12962. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12963. }
  12964. this.bindUniformBuffer(null);
  12965. ubo.references = 1;
  12966. return ubo;
  12967. };
  12968. /**
  12969. * Update an existing uniform buffer
  12970. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12971. * @param uniformBuffer defines the target uniform buffer
  12972. * @param elements defines the content to update
  12973. * @param offset defines the offset in the uniform buffer where update should start
  12974. * @param count defines the size of the data to update
  12975. */
  12976. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12977. this.bindUniformBuffer(uniformBuffer);
  12978. if (offset === undefined) {
  12979. offset = 0;
  12980. }
  12981. if (count === undefined) {
  12982. if (elements instanceof Float32Array) {
  12983. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12984. }
  12985. else {
  12986. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12987. }
  12988. }
  12989. else {
  12990. if (elements instanceof Float32Array) {
  12991. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12992. }
  12993. else {
  12994. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12995. }
  12996. }
  12997. this.bindUniformBuffer(null);
  12998. };
  12999. // VBOs
  13000. Engine.prototype._resetVertexBufferBinding = function () {
  13001. this.bindArrayBuffer(null);
  13002. this._cachedVertexBuffers = null;
  13003. };
  13004. /**
  13005. * Creates a vertex buffer
  13006. * @param data the data for the vertex buffer
  13007. * @returns the new WebGL static buffer
  13008. */
  13009. Engine.prototype.createVertexBuffer = function (data) {
  13010. var vbo = this._gl.createBuffer();
  13011. if (!vbo) {
  13012. throw new Error("Unable to create vertex buffer");
  13013. }
  13014. this.bindArrayBuffer(vbo);
  13015. if (data instanceof Array) {
  13016. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13017. }
  13018. else {
  13019. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13020. }
  13021. this._resetVertexBufferBinding();
  13022. vbo.references = 1;
  13023. return vbo;
  13024. };
  13025. /**
  13026. * Creates a dynamic vertex buffer
  13027. * @param data the data for the dynamic vertex buffer
  13028. * @returns the new WebGL dynamic buffer
  13029. */
  13030. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13031. var vbo = this._gl.createBuffer();
  13032. if (!vbo) {
  13033. throw new Error("Unable to create dynamic vertex buffer");
  13034. }
  13035. this.bindArrayBuffer(vbo);
  13036. if (data instanceof Array) {
  13037. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13038. }
  13039. else {
  13040. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13041. }
  13042. this._resetVertexBufferBinding();
  13043. vbo.references = 1;
  13044. return vbo;
  13045. };
  13046. /**
  13047. * Update a dynamic index buffer
  13048. * @param indexBuffer defines the target index buffer
  13049. * @param indices defines the data to update
  13050. * @param offset defines the offset in the target index buffer where update should start
  13051. */
  13052. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13053. if (offset === void 0) { offset = 0; }
  13054. // Force cache update
  13055. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13056. this.bindIndexBuffer(indexBuffer);
  13057. var arrayBuffer;
  13058. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13059. arrayBuffer = indices;
  13060. }
  13061. else {
  13062. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13063. }
  13064. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13065. this._resetIndexBufferBinding();
  13066. };
  13067. /**
  13068. * Updates a dynamic vertex buffer.
  13069. * @param vertexBuffer the vertex buffer to update
  13070. * @param data the data used to update the vertex buffer
  13071. * @param byteOffset the byte offset of the data
  13072. * @param byteLength the byte length of the data
  13073. */
  13074. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13075. this.bindArrayBuffer(vertexBuffer);
  13076. if (byteOffset === undefined) {
  13077. byteOffset = 0;
  13078. }
  13079. if (byteLength === undefined) {
  13080. if (data instanceof Array) {
  13081. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13082. }
  13083. else {
  13084. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13085. }
  13086. }
  13087. else {
  13088. if (data instanceof Array) {
  13089. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13090. }
  13091. else {
  13092. if (data instanceof ArrayBuffer) {
  13093. data = new Uint8Array(data, byteOffset, byteLength);
  13094. }
  13095. else {
  13096. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13097. }
  13098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13099. }
  13100. }
  13101. this._resetVertexBufferBinding();
  13102. };
  13103. Engine.prototype._resetIndexBufferBinding = function () {
  13104. this.bindIndexBuffer(null);
  13105. this._cachedIndexBuffer = null;
  13106. };
  13107. /**
  13108. * Creates a new index buffer
  13109. * @param indices defines the content of the index buffer
  13110. * @param updatable defines if the index buffer must be updatable
  13111. * @returns a new webGL buffer
  13112. */
  13113. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13114. var vbo = this._gl.createBuffer();
  13115. if (!vbo) {
  13116. throw new Error("Unable to create index buffer");
  13117. }
  13118. this.bindIndexBuffer(vbo);
  13119. // Check for 32 bits indices
  13120. var arrayBuffer;
  13121. var need32Bits = false;
  13122. if (indices instanceof Uint16Array) {
  13123. arrayBuffer = indices;
  13124. }
  13125. else {
  13126. //check 32 bit support
  13127. if (this._caps.uintIndices) {
  13128. if (indices instanceof Uint32Array) {
  13129. arrayBuffer = indices;
  13130. need32Bits = true;
  13131. }
  13132. else {
  13133. //number[] or Int32Array, check if 32 bit is necessary
  13134. for (var index = 0; index < indices.length; index++) {
  13135. if (indices[index] > 65535) {
  13136. need32Bits = true;
  13137. break;
  13138. }
  13139. }
  13140. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13141. }
  13142. }
  13143. else {
  13144. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13145. arrayBuffer = new Uint16Array(indices);
  13146. }
  13147. }
  13148. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13149. this._resetIndexBufferBinding();
  13150. vbo.references = 1;
  13151. vbo.is32Bits = need32Bits;
  13152. return vbo;
  13153. };
  13154. /**
  13155. * Bind a webGL buffer to the webGL context
  13156. * @param buffer defines the buffer to bind
  13157. */
  13158. Engine.prototype.bindArrayBuffer = function (buffer) {
  13159. if (!this._vaoRecordInProgress) {
  13160. this._unbindVertexArrayObject();
  13161. }
  13162. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13163. };
  13164. /**
  13165. * Bind an uniform buffer to the current webGL context
  13166. * @param buffer defines the buffer to bind
  13167. */
  13168. Engine.prototype.bindUniformBuffer = function (buffer) {
  13169. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13170. };
  13171. /**
  13172. * Bind a buffer to the current webGL context at a given location
  13173. * @param buffer defines the buffer to bind
  13174. * @param location defines the index where to bind the buffer
  13175. */
  13176. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13177. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13178. };
  13179. /**
  13180. * Bind a specific block at a given index in a specific shader program
  13181. * @param shaderProgram defines the shader program
  13182. * @param blockName defines the block name
  13183. * @param index defines the index where to bind the block
  13184. */
  13185. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13186. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13187. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13188. };
  13189. ;
  13190. Engine.prototype.bindIndexBuffer = function (buffer) {
  13191. if (!this._vaoRecordInProgress) {
  13192. this._unbindVertexArrayObject();
  13193. }
  13194. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13195. };
  13196. Engine.prototype.bindBuffer = function (buffer, target) {
  13197. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13198. this._gl.bindBuffer(target, buffer);
  13199. this._currentBoundBuffer[target] = buffer;
  13200. }
  13201. };
  13202. /**
  13203. * update the bound buffer with the given data
  13204. * @param data defines the data to update
  13205. */
  13206. Engine.prototype.updateArrayBuffer = function (data) {
  13207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13208. };
  13209. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13210. var pointer = this._currentBufferPointers[indx];
  13211. var changed = false;
  13212. if (!pointer.active) {
  13213. changed = true;
  13214. pointer.active = true;
  13215. pointer.index = indx;
  13216. pointer.size = size;
  13217. pointer.type = type;
  13218. pointer.normalized = normalized;
  13219. pointer.stride = stride;
  13220. pointer.offset = offset;
  13221. pointer.buffer = buffer;
  13222. }
  13223. else {
  13224. if (pointer.buffer !== buffer) {
  13225. pointer.buffer = buffer;
  13226. changed = true;
  13227. }
  13228. if (pointer.size !== size) {
  13229. pointer.size = size;
  13230. changed = true;
  13231. }
  13232. if (pointer.type !== type) {
  13233. pointer.type = type;
  13234. changed = true;
  13235. }
  13236. if (pointer.normalized !== normalized) {
  13237. pointer.normalized = normalized;
  13238. changed = true;
  13239. }
  13240. if (pointer.stride !== stride) {
  13241. pointer.stride = stride;
  13242. changed = true;
  13243. }
  13244. if (pointer.offset !== offset) {
  13245. pointer.offset = offset;
  13246. changed = true;
  13247. }
  13248. }
  13249. if (changed || this._vaoRecordInProgress) {
  13250. this.bindArrayBuffer(buffer);
  13251. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13252. }
  13253. };
  13254. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13255. if (indexBuffer == null) {
  13256. return;
  13257. }
  13258. if (this._cachedIndexBuffer !== indexBuffer) {
  13259. this._cachedIndexBuffer = indexBuffer;
  13260. this.bindIndexBuffer(indexBuffer);
  13261. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13262. }
  13263. };
  13264. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13265. var attributes = effect.getAttributesNames();
  13266. if (!this._vaoRecordInProgress) {
  13267. this._unbindVertexArrayObject();
  13268. }
  13269. this.unbindAllAttributes();
  13270. for (var index = 0; index < attributes.length; index++) {
  13271. var order = effect.getAttributeLocation(index);
  13272. if (order >= 0) {
  13273. var vertexBuffer = vertexBuffers[attributes[index]];
  13274. if (!vertexBuffer) {
  13275. continue;
  13276. }
  13277. this._gl.enableVertexAttribArray(order);
  13278. if (!this._vaoRecordInProgress) {
  13279. this._vertexAttribArraysEnabled[order] = true;
  13280. }
  13281. var buffer = vertexBuffer.getBuffer();
  13282. if (buffer) {
  13283. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13284. if (vertexBuffer.getIsInstanced()) {
  13285. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13286. if (!this._vaoRecordInProgress) {
  13287. this._currentInstanceLocations.push(order);
  13288. this._currentInstanceBuffers.push(buffer);
  13289. }
  13290. }
  13291. }
  13292. }
  13293. }
  13294. };
  13295. /**
  13296. * Records a vertex array object
  13297. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13298. * @param vertexBuffers defines the list of vertex buffers to store
  13299. * @param indexBuffer defines the index buffer to store
  13300. * @param effect defines the effect to store
  13301. * @returns the new vertex array object
  13302. */
  13303. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13304. var vao = this._gl.createVertexArray();
  13305. this._vaoRecordInProgress = true;
  13306. this._gl.bindVertexArray(vao);
  13307. this._mustWipeVertexAttributes = true;
  13308. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13309. this.bindIndexBuffer(indexBuffer);
  13310. this._vaoRecordInProgress = false;
  13311. this._gl.bindVertexArray(null);
  13312. return vao;
  13313. };
  13314. /**
  13315. * Bind a specific vertex array object
  13316. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13317. * @param vertexArrayObject defines the vertex array object to bind
  13318. * @param indexBuffer defines the index buffer to bind
  13319. */
  13320. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13321. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13322. this._cachedVertexArrayObject = vertexArrayObject;
  13323. this._gl.bindVertexArray(vertexArrayObject);
  13324. this._cachedVertexBuffers = null;
  13325. this._cachedIndexBuffer = null;
  13326. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13327. this._mustWipeVertexAttributes = true;
  13328. }
  13329. };
  13330. /**
  13331. * Bind webGl buffers directly to the webGL context
  13332. * @param vertexBuffer defines the vertex buffer to bind
  13333. * @param indexBuffer defines the index buffer to bind
  13334. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13335. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13336. * @param effect defines the effect associated with the vertex buffer
  13337. */
  13338. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13339. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13340. this._cachedVertexBuffers = vertexBuffer;
  13341. this._cachedEffectForVertexBuffers = effect;
  13342. var attributesCount = effect.getAttributesCount();
  13343. this._unbindVertexArrayObject();
  13344. this.unbindAllAttributes();
  13345. var offset = 0;
  13346. for (var index = 0; index < attributesCount; index++) {
  13347. if (index < vertexDeclaration.length) {
  13348. var order = effect.getAttributeLocation(index);
  13349. if (order >= 0) {
  13350. this._gl.enableVertexAttribArray(order);
  13351. this._vertexAttribArraysEnabled[order] = true;
  13352. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13353. }
  13354. offset += vertexDeclaration[index] * 4;
  13355. }
  13356. }
  13357. }
  13358. this._bindIndexBufferWithCache(indexBuffer);
  13359. };
  13360. Engine.prototype._unbindVertexArrayObject = function () {
  13361. if (!this._cachedVertexArrayObject) {
  13362. return;
  13363. }
  13364. this._cachedVertexArrayObject = null;
  13365. this._gl.bindVertexArray(null);
  13366. };
  13367. /**
  13368. * Bind a list of vertex buffers to the webGL context
  13369. * @param vertexBuffers defines the list of vertex buffers to bind
  13370. * @param indexBuffer defines the index buffer to bind
  13371. * @param effect defines the effect associated with the vertex buffers
  13372. */
  13373. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13374. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13375. this._cachedVertexBuffers = vertexBuffers;
  13376. this._cachedEffectForVertexBuffers = effect;
  13377. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13378. }
  13379. this._bindIndexBufferWithCache(indexBuffer);
  13380. };
  13381. /**
  13382. * Unbind all instance attributes
  13383. */
  13384. Engine.prototype.unbindInstanceAttributes = function () {
  13385. var boundBuffer;
  13386. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13387. var instancesBuffer = this._currentInstanceBuffers[i];
  13388. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13389. boundBuffer = instancesBuffer;
  13390. this.bindArrayBuffer(instancesBuffer);
  13391. }
  13392. var offsetLocation = this._currentInstanceLocations[i];
  13393. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13394. }
  13395. this._currentInstanceBuffers.length = 0;
  13396. this._currentInstanceLocations.length = 0;
  13397. };
  13398. /**
  13399. * Release and free the memory of a vertex array object
  13400. * @param vao defines the vertex array object to delete
  13401. */
  13402. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13403. this._gl.deleteVertexArray(vao);
  13404. };
  13405. /** @hidden */
  13406. Engine.prototype._releaseBuffer = function (buffer) {
  13407. buffer.references--;
  13408. if (buffer.references === 0) {
  13409. this._gl.deleteBuffer(buffer);
  13410. return true;
  13411. }
  13412. return false;
  13413. };
  13414. /**
  13415. * Creates a webGL buffer to use with instanciation
  13416. * @param capacity defines the size of the buffer
  13417. * @returns the webGL buffer
  13418. */
  13419. Engine.prototype.createInstancesBuffer = function (capacity) {
  13420. var buffer = this._gl.createBuffer();
  13421. if (!buffer) {
  13422. throw new Error("Unable to create instance buffer");
  13423. }
  13424. buffer.capacity = capacity;
  13425. this.bindArrayBuffer(buffer);
  13426. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13427. return buffer;
  13428. };
  13429. /**
  13430. * Delete a webGL buffer used with instanciation
  13431. * @param buffer defines the webGL buffer to delete
  13432. */
  13433. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13434. this._gl.deleteBuffer(buffer);
  13435. };
  13436. /**
  13437. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13438. * @param instancesBuffer defines the webGL buffer to update and bind
  13439. * @param data defines the data to store in the buffer
  13440. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13441. */
  13442. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13443. this.bindArrayBuffer(instancesBuffer);
  13444. if (data) {
  13445. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13446. }
  13447. if (offsetLocations[0].index !== undefined) {
  13448. var stride = 0;
  13449. for (var i = 0; i < offsetLocations.length; i++) {
  13450. var ai = offsetLocations[i];
  13451. stride += ai.attributeSize * 4;
  13452. }
  13453. for (var i = 0; i < offsetLocations.length; i++) {
  13454. var ai = offsetLocations[i];
  13455. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13456. this._gl.enableVertexAttribArray(ai.index);
  13457. this._vertexAttribArraysEnabled[ai.index] = true;
  13458. }
  13459. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13460. this._gl.vertexAttribDivisor(ai.index, 1);
  13461. this._currentInstanceLocations.push(ai.index);
  13462. this._currentInstanceBuffers.push(instancesBuffer);
  13463. }
  13464. }
  13465. else {
  13466. for (var index = 0; index < 4; index++) {
  13467. var offsetLocation = offsetLocations[index];
  13468. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13469. this._gl.enableVertexAttribArray(offsetLocation);
  13470. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13471. }
  13472. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13473. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13474. this._currentInstanceLocations.push(offsetLocation);
  13475. this._currentInstanceBuffers.push(instancesBuffer);
  13476. }
  13477. }
  13478. };
  13479. /**
  13480. * Apply all cached states (depth, culling, stencil and alpha)
  13481. */
  13482. Engine.prototype.applyStates = function () {
  13483. this._depthCullingState.apply(this._gl);
  13484. this._stencilState.apply(this._gl);
  13485. this._alphaState.apply(this._gl);
  13486. };
  13487. /**
  13488. * Send a draw order
  13489. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13490. * @param indexStart defines the starting index
  13491. * @param indexCount defines the number of index to draw
  13492. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13493. */
  13494. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13495. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13496. };
  13497. /**
  13498. * Draw a list of points
  13499. * @param verticesStart defines the index of first vertex to draw
  13500. * @param verticesCount defines the count of vertices to draw
  13501. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13502. */
  13503. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13504. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13505. };
  13506. /**
  13507. * Draw a list of unindexed primitives
  13508. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13509. * @param verticesStart defines the index of first vertex to draw
  13510. * @param verticesCount defines the count of vertices to draw
  13511. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13512. */
  13513. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13514. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13515. };
  13516. /**
  13517. * Draw a list of indexed primitives
  13518. * @param fillMode defines the primitive to use
  13519. * @param indexStart defines the starting index
  13520. * @param indexCount defines the number of index to draw
  13521. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13522. */
  13523. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13524. // Apply states
  13525. this.applyStates();
  13526. this._drawCalls.addCount(1, false);
  13527. // Render
  13528. var drawMode = this._drawMode(fillMode);
  13529. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13530. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13531. if (instancesCount) {
  13532. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13533. }
  13534. else {
  13535. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13536. }
  13537. };
  13538. /**
  13539. * Draw a list of unindexed primitives
  13540. * @param fillMode defines the primitive to use
  13541. * @param verticesStart defines the index of first vertex to draw
  13542. * @param verticesCount defines the count of vertices to draw
  13543. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13544. */
  13545. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13546. // Apply states
  13547. this.applyStates();
  13548. this._drawCalls.addCount(1, false);
  13549. var drawMode = this._drawMode(fillMode);
  13550. if (instancesCount) {
  13551. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13552. }
  13553. else {
  13554. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13555. }
  13556. };
  13557. Engine.prototype._drawMode = function (fillMode) {
  13558. switch (fillMode) {
  13559. // Triangle views
  13560. case BABYLON.Material.TriangleFillMode:
  13561. return this._gl.TRIANGLES;
  13562. case BABYLON.Material.PointFillMode:
  13563. return this._gl.POINTS;
  13564. case BABYLON.Material.WireFrameFillMode:
  13565. return this._gl.LINES;
  13566. // Draw modes
  13567. case BABYLON.Material.PointListDrawMode:
  13568. return this._gl.POINTS;
  13569. case BABYLON.Material.LineListDrawMode:
  13570. return this._gl.LINES;
  13571. case BABYLON.Material.LineLoopDrawMode:
  13572. return this._gl.LINE_LOOP;
  13573. case BABYLON.Material.LineStripDrawMode:
  13574. return this._gl.LINE_STRIP;
  13575. case BABYLON.Material.TriangleStripDrawMode:
  13576. return this._gl.TRIANGLE_STRIP;
  13577. case BABYLON.Material.TriangleFanDrawMode:
  13578. return this._gl.TRIANGLE_FAN;
  13579. default:
  13580. return this._gl.TRIANGLES;
  13581. }
  13582. };
  13583. // Shaders
  13584. /** @hidden */
  13585. Engine.prototype._releaseEffect = function (effect) {
  13586. if (this._compiledEffects[effect._key]) {
  13587. delete this._compiledEffects[effect._key];
  13588. this._deleteProgram(effect.getProgram());
  13589. }
  13590. };
  13591. /** @hidden */
  13592. Engine.prototype._deleteProgram = function (program) {
  13593. if (program) {
  13594. program.__SPECTOR_rebuildProgram = null;
  13595. if (program.transformFeedback) {
  13596. this.deleteTransformFeedback(program.transformFeedback);
  13597. program.transformFeedback = null;
  13598. }
  13599. this._gl.deleteProgram(program);
  13600. }
  13601. };
  13602. /**
  13603. * Create a new effect (used to store vertex/fragment shaders)
  13604. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13605. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13606. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13607. * @param samplers defines an array of string used to represent textures
  13608. * @param defines defines the string containing the defines to use to compile the shaders
  13609. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13610. * @param onCompiled defines a function to call when the effect creation is successful
  13611. * @param onError defines a function to call when the effect creation has failed
  13612. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13613. * @returns the new Effect
  13614. */
  13615. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13616. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13617. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13618. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13619. if (this._compiledEffects[name]) {
  13620. var compiledEffect = this._compiledEffects[name];
  13621. if (onCompiled && compiledEffect.isReady()) {
  13622. onCompiled(compiledEffect);
  13623. }
  13624. return compiledEffect;
  13625. }
  13626. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13627. effect._key = name;
  13628. this._compiledEffects[name] = effect;
  13629. return effect;
  13630. };
  13631. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13632. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13633. };
  13634. ;
  13635. Engine.prototype._compileRawShader = function (source, type) {
  13636. var gl = this._gl;
  13637. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13638. gl.shaderSource(shader, source);
  13639. gl.compileShader(shader);
  13640. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13641. var log = gl.getShaderInfoLog(shader);
  13642. if (log) {
  13643. throw new Error(log);
  13644. }
  13645. }
  13646. if (!shader) {
  13647. throw new Error("Something went wrong while compile the shader.");
  13648. }
  13649. return shader;
  13650. };
  13651. ;
  13652. /**
  13653. * Directly creates a webGL program
  13654. * @param vertexCode defines the vertex shader code to use
  13655. * @param fragmentCode defines the fragment shader code to use
  13656. * @param context defines the webGL context to use (if not set, the current one will be used)
  13657. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13658. * @returns the new webGL program
  13659. */
  13660. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13661. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13662. context = context || this._gl;
  13663. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13664. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13665. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13666. };
  13667. /**
  13668. * Creates a webGL program
  13669. * @param vertexCode defines the vertex shader code to use
  13670. * @param fragmentCode defines the fragment shader code to use
  13671. * @param defines defines the string containing the defines to use to compile the shaders
  13672. * @param context defines the webGL context to use (if not set, the current one will be used)
  13673. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13674. * @returns the new webGL program
  13675. */
  13676. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13677. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13678. context = context || this._gl;
  13679. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13680. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13681. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13682. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13683. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13684. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13685. return program;
  13686. };
  13687. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13688. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13689. var shaderProgram = context.createProgram();
  13690. if (!shaderProgram) {
  13691. throw new Error("Unable to create program");
  13692. }
  13693. context.attachShader(shaderProgram, vertexShader);
  13694. context.attachShader(shaderProgram, fragmentShader);
  13695. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13696. var transformFeedback = this.createTransformFeedback();
  13697. this.bindTransformFeedback(transformFeedback);
  13698. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13699. shaderProgram.transformFeedback = transformFeedback;
  13700. }
  13701. context.linkProgram(shaderProgram);
  13702. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13703. this.bindTransformFeedback(null);
  13704. }
  13705. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13706. if (!linked) {
  13707. var error = context.getProgramInfoLog(shaderProgram);
  13708. if (error) {
  13709. throw new Error(error);
  13710. }
  13711. }
  13712. if (this.validateShaderPrograms) {
  13713. context.validateProgram(shaderProgram);
  13714. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13715. if (!validated) {
  13716. var error = context.getProgramInfoLog(shaderProgram);
  13717. if (error) {
  13718. throw new Error(error);
  13719. }
  13720. }
  13721. }
  13722. context.deleteShader(vertexShader);
  13723. context.deleteShader(fragmentShader);
  13724. return shaderProgram;
  13725. };
  13726. /**
  13727. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13728. * @param shaderProgram defines the webGL program to use
  13729. * @param uniformsNames defines the list of uniform names
  13730. * @returns an array of webGL uniform locations
  13731. */
  13732. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13733. var results = new Array();
  13734. for (var index = 0; index < uniformsNames.length; index++) {
  13735. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13736. }
  13737. return results;
  13738. };
  13739. /**
  13740. * Gets the lsit of active attributes for a given webGL program
  13741. * @param shaderProgram defines the webGL program to use
  13742. * @param attributesNames defines the list of attribute names to get
  13743. * @returns an array of indices indicating the offset of each attribute
  13744. */
  13745. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13746. var results = [];
  13747. for (var index = 0; index < attributesNames.length; index++) {
  13748. try {
  13749. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13750. }
  13751. catch (e) {
  13752. results.push(-1);
  13753. }
  13754. }
  13755. return results;
  13756. };
  13757. /**
  13758. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13759. * @param effect defines the effect to activate
  13760. */
  13761. Engine.prototype.enableEffect = function (effect) {
  13762. if (!effect || effect === this._currentEffect) {
  13763. return;
  13764. }
  13765. // Use program
  13766. this.bindSamplers(effect);
  13767. this._currentEffect = effect;
  13768. if (effect.onBind) {
  13769. effect.onBind(effect);
  13770. }
  13771. if (effect._onBindObservable) {
  13772. effect._onBindObservable.notifyObservers(effect);
  13773. }
  13774. };
  13775. /**
  13776. * Set the value of an uniform to an array of int32
  13777. * @param uniform defines the webGL uniform location where to store the value
  13778. * @param array defines the array of int32 to store
  13779. */
  13780. Engine.prototype.setIntArray = function (uniform, array) {
  13781. if (!uniform)
  13782. return;
  13783. this._gl.uniform1iv(uniform, array);
  13784. };
  13785. /**
  13786. * Set the value of an uniform to an array of int32 (stored as vec2)
  13787. * @param uniform defines the webGL uniform location where to store the value
  13788. * @param array defines the array of int32 to store
  13789. */
  13790. Engine.prototype.setIntArray2 = function (uniform, array) {
  13791. if (!uniform || array.length % 2 !== 0)
  13792. return;
  13793. this._gl.uniform2iv(uniform, array);
  13794. };
  13795. /**
  13796. * Set the value of an uniform to an array of int32 (stored as vec3)
  13797. * @param uniform defines the webGL uniform location where to store the value
  13798. * @param array defines the array of int32 to store
  13799. */
  13800. Engine.prototype.setIntArray3 = function (uniform, array) {
  13801. if (!uniform || array.length % 3 !== 0)
  13802. return;
  13803. this._gl.uniform3iv(uniform, array);
  13804. };
  13805. /**
  13806. * Set the value of an uniform to an array of int32 (stored as vec4)
  13807. * @param uniform defines the webGL uniform location where to store the value
  13808. * @param array defines the array of int32 to store
  13809. */
  13810. Engine.prototype.setIntArray4 = function (uniform, array) {
  13811. if (!uniform || array.length % 4 !== 0)
  13812. return;
  13813. this._gl.uniform4iv(uniform, array);
  13814. };
  13815. /**
  13816. * Set the value of an uniform to an array of float32
  13817. * @param uniform defines the webGL uniform location where to store the value
  13818. * @param array defines the array of float32 to store
  13819. */
  13820. Engine.prototype.setFloatArray = function (uniform, array) {
  13821. if (!uniform)
  13822. return;
  13823. this._gl.uniform1fv(uniform, array);
  13824. };
  13825. /**
  13826. * Set the value of an uniform to an array of float32 (stored as vec2)
  13827. * @param uniform defines the webGL uniform location where to store the value
  13828. * @param array defines the array of float32 to store
  13829. */
  13830. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13831. if (!uniform || array.length % 2 !== 0)
  13832. return;
  13833. this._gl.uniform2fv(uniform, array);
  13834. };
  13835. /**
  13836. * Set the value of an uniform to an array of float32 (stored as vec3)
  13837. * @param uniform defines the webGL uniform location where to store the value
  13838. * @param array defines the array of float32 to store
  13839. */
  13840. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13841. if (!uniform || array.length % 3 !== 0)
  13842. return;
  13843. this._gl.uniform3fv(uniform, array);
  13844. };
  13845. /**
  13846. * Set the value of an uniform to an array of float32 (stored as vec4)
  13847. * @param uniform defines the webGL uniform location where to store the value
  13848. * @param array defines the array of float32 to store
  13849. */
  13850. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13851. if (!uniform || array.length % 4 !== 0)
  13852. return;
  13853. this._gl.uniform4fv(uniform, array);
  13854. };
  13855. /**
  13856. * Set the value of an uniform to an array of number
  13857. * @param uniform defines the webGL uniform location where to store the value
  13858. * @param array defines the array of number to store
  13859. */
  13860. Engine.prototype.setArray = function (uniform, array) {
  13861. if (!uniform)
  13862. return;
  13863. this._gl.uniform1fv(uniform, array);
  13864. };
  13865. /**
  13866. * Set the value of an uniform to an array of number (stored as vec2)
  13867. * @param uniform defines the webGL uniform location where to store the value
  13868. * @param array defines the array of number to store
  13869. */
  13870. Engine.prototype.setArray2 = function (uniform, array) {
  13871. if (!uniform || array.length % 2 !== 0)
  13872. return;
  13873. this._gl.uniform2fv(uniform, array);
  13874. };
  13875. /**
  13876. * Set the value of an uniform to an array of number (stored as vec3)
  13877. * @param uniform defines the webGL uniform location where to store the value
  13878. * @param array defines the array of number to store
  13879. */
  13880. Engine.prototype.setArray3 = function (uniform, array) {
  13881. if (!uniform || array.length % 3 !== 0)
  13882. return;
  13883. this._gl.uniform3fv(uniform, array);
  13884. };
  13885. /**
  13886. * Set the value of an uniform to an array of number (stored as vec4)
  13887. * @param uniform defines the webGL uniform location where to store the value
  13888. * @param array defines the array of number to store
  13889. */
  13890. Engine.prototype.setArray4 = function (uniform, array) {
  13891. if (!uniform || array.length % 4 !== 0)
  13892. return;
  13893. this._gl.uniform4fv(uniform, array);
  13894. };
  13895. /**
  13896. * Set the value of an uniform to an array of float32 (stored as matrices)
  13897. * @param uniform defines the webGL uniform location where to store the value
  13898. * @param matrices defines the array of float32 to store
  13899. */
  13900. Engine.prototype.setMatrices = function (uniform, matrices) {
  13901. if (!uniform)
  13902. return;
  13903. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13904. };
  13905. /**
  13906. * Set the value of an uniform to a matrix
  13907. * @param uniform defines the webGL uniform location where to store the value
  13908. * @param matrix defines the matrix to store
  13909. */
  13910. Engine.prototype.setMatrix = function (uniform, matrix) {
  13911. if (!uniform)
  13912. return;
  13913. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13914. };
  13915. /**
  13916. * Set the value of an uniform to a matrix (3x3)
  13917. * @param uniform defines the webGL uniform location where to store the value
  13918. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13919. */
  13920. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13921. if (!uniform)
  13922. return;
  13923. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13924. };
  13925. /**
  13926. * Set the value of an uniform to a matrix (2x2)
  13927. * @param uniform defines the webGL uniform location where to store the value
  13928. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13929. */
  13930. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13931. if (!uniform)
  13932. return;
  13933. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13934. };
  13935. /**
  13936. * Set the value of an uniform to a number (int)
  13937. * @param uniform defines the webGL uniform location where to store the value
  13938. * @param value defines the int number to store
  13939. */
  13940. Engine.prototype.setInt = function (uniform, value) {
  13941. if (!uniform)
  13942. return;
  13943. this._gl.uniform1i(uniform, value);
  13944. };
  13945. /**
  13946. * Set the value of an uniform to a number (float)
  13947. * @param uniform defines the webGL uniform location where to store the value
  13948. * @param value defines the float number to store
  13949. */
  13950. Engine.prototype.setFloat = function (uniform, value) {
  13951. if (!uniform)
  13952. return;
  13953. this._gl.uniform1f(uniform, value);
  13954. };
  13955. /**
  13956. * Set the value of an uniform to a vec2
  13957. * @param uniform defines the webGL uniform location where to store the value
  13958. * @param x defines the 1st component of the value
  13959. * @param y defines the 2nd component of the value
  13960. */
  13961. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13962. if (!uniform)
  13963. return;
  13964. this._gl.uniform2f(uniform, x, y);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to a vec3
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param x defines the 1st component of the value
  13970. * @param y defines the 2nd component of the value
  13971. * @param z defines the 3rd component of the value
  13972. */
  13973. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13974. if (!uniform)
  13975. return;
  13976. this._gl.uniform3f(uniform, x, y, z);
  13977. };
  13978. /**
  13979. * Set the value of an uniform to a boolean
  13980. * @param uniform defines the webGL uniform location where to store the value
  13981. * @param bool defines the boolean to store
  13982. */
  13983. Engine.prototype.setBool = function (uniform, bool) {
  13984. if (!uniform)
  13985. return;
  13986. this._gl.uniform1i(uniform, bool);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to a vec4
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param x defines the 1st component of the value
  13992. * @param y defines the 2nd component of the value
  13993. * @param z defines the 3rd component of the value
  13994. * @param w defines the 4th component of the value
  13995. */
  13996. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13997. if (!uniform)
  13998. return;
  13999. this._gl.uniform4f(uniform, x, y, z, w);
  14000. };
  14001. /**
  14002. * Set the value of an uniform to a Color3
  14003. * @param uniform defines the webGL uniform location where to store the value
  14004. * @param color3 defines the color to store
  14005. */
  14006. Engine.prototype.setColor3 = function (uniform, color3) {
  14007. if (!uniform)
  14008. return;
  14009. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14010. };
  14011. /**
  14012. * Set the value of an uniform to a Color3 and an alpha value
  14013. * @param uniform defines the webGL uniform location where to store the value
  14014. * @param color3 defines the color to store
  14015. * @param alpha defines the alpha component to store
  14016. */
  14017. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14018. if (!uniform)
  14019. return;
  14020. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14021. };
  14022. /**
  14023. * Sets a Color4 on a uniform variable
  14024. * @param uniform defines the uniform location
  14025. * @param color4 defines the value to be set
  14026. */
  14027. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14028. if (!uniform)
  14029. return;
  14030. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14031. };
  14032. // States
  14033. /**
  14034. * Set various states to the webGL context
  14035. * @param culling defines backface culling state
  14036. * @param zOffset defines the value to apply to zOffset (0 by default)
  14037. * @param force defines if states must be applied even if cache is up to date
  14038. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14039. */
  14040. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14041. if (zOffset === void 0) { zOffset = 0; }
  14042. if (reverseSide === void 0) { reverseSide = false; }
  14043. // Culling
  14044. if (this._depthCullingState.cull !== culling || force) {
  14045. this._depthCullingState.cull = culling;
  14046. }
  14047. // Cull face
  14048. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14049. if (this._depthCullingState.cullFace !== cullFace || force) {
  14050. this._depthCullingState.cullFace = cullFace;
  14051. }
  14052. // Z offset
  14053. this.setZOffset(zOffset);
  14054. // Front face
  14055. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14056. if (this._depthCullingState.frontFace !== frontFace || force) {
  14057. this._depthCullingState.frontFace = frontFace;
  14058. }
  14059. };
  14060. /**
  14061. * Set the z offset to apply to current rendering
  14062. * @param value defines the offset to apply
  14063. */
  14064. Engine.prototype.setZOffset = function (value) {
  14065. this._depthCullingState.zOffset = value;
  14066. };
  14067. /**
  14068. * Gets the current value of the zOffset
  14069. * @returns the current zOffset state
  14070. */
  14071. Engine.prototype.getZOffset = function () {
  14072. return this._depthCullingState.zOffset;
  14073. };
  14074. /**
  14075. * Enable or disable depth buffering
  14076. * @param enable defines the state to set
  14077. */
  14078. Engine.prototype.setDepthBuffer = function (enable) {
  14079. this._depthCullingState.depthTest = enable;
  14080. };
  14081. /**
  14082. * Gets a boolean indicating if depth writing is enabled
  14083. * @returns the current depth writing state
  14084. */
  14085. Engine.prototype.getDepthWrite = function () {
  14086. return this._depthCullingState.depthMask;
  14087. };
  14088. /**
  14089. * Enable or disable depth writing
  14090. * @param enable defines the state to set
  14091. */
  14092. Engine.prototype.setDepthWrite = function (enable) {
  14093. this._depthCullingState.depthMask = enable;
  14094. };
  14095. /**
  14096. * Enable or disable color writing
  14097. * @param enable defines the state to set
  14098. */
  14099. Engine.prototype.setColorWrite = function (enable) {
  14100. this._gl.colorMask(enable, enable, enable, enable);
  14101. this._colorWrite = enable;
  14102. };
  14103. /**
  14104. * Gets a boolean indicating if color writing is enabled
  14105. * @returns the current color writing state
  14106. */
  14107. Engine.prototype.getColorWrite = function () {
  14108. return this._colorWrite;
  14109. };
  14110. /**
  14111. * Sets alpha constants used by some alpha blending modes
  14112. * @param r defines the red component
  14113. * @param g defines the green component
  14114. * @param b defines the blue component
  14115. * @param a defines the alpha component
  14116. */
  14117. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14118. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14119. };
  14120. /**
  14121. * Sets the current alpha mode
  14122. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14123. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14124. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14125. */
  14126. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14127. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14128. if (this._alphaMode === mode) {
  14129. return;
  14130. }
  14131. switch (mode) {
  14132. case Engine.ALPHA_DISABLE:
  14133. this._alphaState.alphaBlend = false;
  14134. break;
  14135. case Engine.ALPHA_PREMULTIPLIED:
  14136. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14137. this._alphaState.alphaBlend = true;
  14138. break;
  14139. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14141. this._alphaState.alphaBlend = true;
  14142. break;
  14143. case Engine.ALPHA_COMBINE:
  14144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14145. this._alphaState.alphaBlend = true;
  14146. break;
  14147. case Engine.ALPHA_ONEONE:
  14148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14149. this._alphaState.alphaBlend = true;
  14150. break;
  14151. case Engine.ALPHA_ADD:
  14152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14153. this._alphaState.alphaBlend = true;
  14154. break;
  14155. case Engine.ALPHA_SUBTRACT:
  14156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14157. this._alphaState.alphaBlend = true;
  14158. break;
  14159. case Engine.ALPHA_MULTIPLY:
  14160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14161. this._alphaState.alphaBlend = true;
  14162. break;
  14163. case Engine.ALPHA_MAXIMIZED:
  14164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14165. this._alphaState.alphaBlend = true;
  14166. break;
  14167. case Engine.ALPHA_INTERPOLATE:
  14168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14169. this._alphaState.alphaBlend = true;
  14170. break;
  14171. case Engine.ALPHA_SCREENMODE:
  14172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14173. this._alphaState.alphaBlend = true;
  14174. break;
  14175. }
  14176. if (!noDepthWriteChange) {
  14177. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14178. }
  14179. this._alphaMode = mode;
  14180. };
  14181. /**
  14182. * Gets the current alpha mode
  14183. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14184. * @returns the current alpha mode
  14185. */
  14186. Engine.prototype.getAlphaMode = function () {
  14187. return this._alphaMode;
  14188. };
  14189. // Textures
  14190. /**
  14191. * Clears the list of texture accessible through engine.
  14192. * This can help preventing texture load conflict due to name collision.
  14193. */
  14194. Engine.prototype.clearInternalTexturesCache = function () {
  14195. this._internalTexturesCache = [];
  14196. };
  14197. /**
  14198. * Force the entire cache to be cleared
  14199. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14200. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14201. */
  14202. Engine.prototype.wipeCaches = function (bruteForce) {
  14203. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14204. return;
  14205. }
  14206. this._currentEffect = null;
  14207. this._unpackFlipYCached = null;
  14208. this._viewportCached.x = 0;
  14209. this._viewportCached.y = 0;
  14210. this._viewportCached.z = 0;
  14211. this._viewportCached.w = 0;
  14212. if (bruteForce) {
  14213. this.resetTextureCache();
  14214. this._currentProgram = null;
  14215. this._stencilState.reset();
  14216. this._depthCullingState.reset();
  14217. this.setDepthFunctionToLessOrEqual();
  14218. this._alphaState.reset();
  14219. }
  14220. this._resetVertexBufferBinding();
  14221. this._cachedIndexBuffer = null;
  14222. this._cachedEffectForVertexBuffers = null;
  14223. this._unbindVertexArrayObject();
  14224. this.bindIndexBuffer(null);
  14225. };
  14226. /**
  14227. * Set the compressed texture format to use, based on the formats you have, and the formats
  14228. * supported by the hardware / browser.
  14229. *
  14230. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14231. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14232. * to API arguments needed to compressed textures. This puts the burden on the container
  14233. * generator to house the arcane code for determining these for current & future formats.
  14234. *
  14235. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14236. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14237. *
  14238. * Note: The result of this call is not taken into account when a texture is base64.
  14239. *
  14240. * @param formatsAvailable defines the list of those format families you have created
  14241. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14242. *
  14243. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14244. * @returns The extension selected.
  14245. */
  14246. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14247. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14248. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14249. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14250. return this._textureFormatInUse = this._texturesSupported[i];
  14251. }
  14252. }
  14253. }
  14254. // actively set format to nothing, to allow this to be called more than once
  14255. // and possibly fail the 2nd time
  14256. this._textureFormatInUse = null;
  14257. return null;
  14258. };
  14259. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14260. var gl = this._gl;
  14261. var magFilter = gl.NEAREST;
  14262. var minFilter = gl.NEAREST;
  14263. switch (samplingMode) {
  14264. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14265. magFilter = gl.LINEAR;
  14266. if (generateMipMaps) {
  14267. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14268. }
  14269. else {
  14270. minFilter = gl.LINEAR;
  14271. }
  14272. break;
  14273. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14274. magFilter = gl.LINEAR;
  14275. if (generateMipMaps) {
  14276. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14277. }
  14278. else {
  14279. minFilter = gl.LINEAR;
  14280. }
  14281. break;
  14282. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14283. magFilter = gl.NEAREST;
  14284. if (generateMipMaps) {
  14285. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14286. }
  14287. else {
  14288. minFilter = gl.NEAREST;
  14289. }
  14290. break;
  14291. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14292. magFilter = gl.NEAREST;
  14293. if (generateMipMaps) {
  14294. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14295. }
  14296. else {
  14297. minFilter = gl.NEAREST;
  14298. }
  14299. break;
  14300. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14301. magFilter = gl.NEAREST;
  14302. if (generateMipMaps) {
  14303. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14304. }
  14305. else {
  14306. minFilter = gl.LINEAR;
  14307. }
  14308. break;
  14309. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14310. magFilter = gl.NEAREST;
  14311. if (generateMipMaps) {
  14312. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14313. }
  14314. else {
  14315. minFilter = gl.LINEAR;
  14316. }
  14317. break;
  14318. case Engine.TEXTURE_NEAREST_LINEAR:
  14319. magFilter = gl.NEAREST;
  14320. minFilter = gl.LINEAR;
  14321. break;
  14322. case Engine.TEXTURE_NEAREST_NEAREST:
  14323. magFilter = gl.NEAREST;
  14324. minFilter = gl.NEAREST;
  14325. break;
  14326. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14327. magFilter = gl.LINEAR;
  14328. if (generateMipMaps) {
  14329. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14330. }
  14331. else {
  14332. minFilter = gl.NEAREST;
  14333. }
  14334. break;
  14335. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14336. magFilter = gl.LINEAR;
  14337. if (generateMipMaps) {
  14338. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14339. }
  14340. else {
  14341. minFilter = gl.NEAREST;
  14342. }
  14343. break;
  14344. case Engine.TEXTURE_LINEAR_LINEAR:
  14345. magFilter = gl.LINEAR;
  14346. minFilter = gl.LINEAR;
  14347. break;
  14348. case Engine.TEXTURE_LINEAR_NEAREST:
  14349. magFilter = gl.LINEAR;
  14350. minFilter = gl.NEAREST;
  14351. break;
  14352. }
  14353. return {
  14354. min: minFilter,
  14355. mag: magFilter
  14356. };
  14357. };
  14358. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14359. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14360. var img;
  14361. var onload = function () {
  14362. loadedImages[index] = img;
  14363. loadedImages._internalCount++;
  14364. if (scene) {
  14365. scene._removePendingData(img);
  14366. }
  14367. if (loadedImages._internalCount === 6) {
  14368. onfinish(loadedImages);
  14369. }
  14370. };
  14371. var onerror = function (message, exception) {
  14372. if (scene) {
  14373. scene._removePendingData(img);
  14374. }
  14375. if (onErrorCallBack) {
  14376. onErrorCallBack(message, exception);
  14377. }
  14378. };
  14379. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14380. if (scene) {
  14381. scene._addPendingData(img);
  14382. }
  14383. };
  14384. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14385. if (onError === void 0) { onError = null; }
  14386. var loadedImages = [];
  14387. loadedImages._internalCount = 0;
  14388. for (var index = 0; index < 6; index++) {
  14389. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14390. }
  14391. };
  14392. ;
  14393. /** @hidden */
  14394. Engine.prototype._createTexture = function () {
  14395. var texture = this._gl.createTexture();
  14396. if (!texture) {
  14397. throw new Error("Unable to create texture");
  14398. }
  14399. return texture;
  14400. };
  14401. /**
  14402. * Usually called from BABYLON.Texture.ts.
  14403. * Passed information to create a WebGLTexture
  14404. * @param urlArg defines a value which contains one of the following:
  14405. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14406. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14407. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14408. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14409. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14410. * @param scene needed for loading to the correct scene
  14411. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14412. * @param onLoad optional callback to be called upon successful completion
  14413. * @param onError optional callback to be called upon failure
  14414. * @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
  14415. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14416. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14417. * @param forcedExtension defines the extension to use to pick the right loader
  14418. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14419. */
  14420. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14421. var _this = this;
  14422. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14423. if (onLoad === void 0) { onLoad = null; }
  14424. if (onError === void 0) { onError = null; }
  14425. if (buffer === void 0) { buffer = null; }
  14426. if (fallback === void 0) { fallback = null; }
  14427. if (format === void 0) { format = null; }
  14428. if (forcedExtension === void 0) { forcedExtension = null; }
  14429. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14430. var fromData = url.substr(0, 5) === "data:";
  14431. var fromBlob = url.substr(0, 5) === "blob:";
  14432. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14433. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14434. // establish the file extension, if possible
  14435. var lastDot = url.lastIndexOf('.');
  14436. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14437. var loader = null;
  14438. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14439. var availableLoader = _a[_i];
  14440. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14441. loader = availableLoader;
  14442. break;
  14443. }
  14444. }
  14445. if (loader) {
  14446. url = loader.transformUrl(url, this._textureFormatInUse);
  14447. }
  14448. if (scene) {
  14449. scene._addPendingData(texture);
  14450. }
  14451. texture.url = url;
  14452. texture.generateMipMaps = !noMipmap;
  14453. texture.samplingMode = samplingMode;
  14454. texture.invertY = invertY;
  14455. if (!this._doNotHandleContextLost) {
  14456. // Keep a link to the buffer only if we plan to handle context lost
  14457. texture._buffer = buffer;
  14458. }
  14459. var onLoadObserver = null;
  14460. if (onLoad && !fallback) {
  14461. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14462. }
  14463. if (!fallback)
  14464. this._internalTexturesCache.push(texture);
  14465. var onInternalError = function (message, exception) {
  14466. if (scene) {
  14467. scene._removePendingData(texture);
  14468. }
  14469. var customFallback = false;
  14470. if (loader) {
  14471. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14472. if (fallbackUrl) {
  14473. // Add Back
  14474. customFallback = true;
  14475. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14476. }
  14477. }
  14478. if (!customFallback) {
  14479. if (onLoadObserver) {
  14480. texture.onLoadedObservable.remove(onLoadObserver);
  14481. }
  14482. if (BABYLON.Tools.UseFallbackTexture) {
  14483. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14484. }
  14485. }
  14486. if (onError) {
  14487. onError(message || "Unknown error", exception);
  14488. }
  14489. };
  14490. // processing for non-image formats
  14491. if (loader) {
  14492. var callback = function (data) {
  14493. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14494. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14495. done();
  14496. return false;
  14497. }, samplingMode);
  14498. });
  14499. };
  14500. if (!buffer) {
  14501. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14502. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14503. });
  14504. }
  14505. else {
  14506. callback(buffer);
  14507. }
  14508. }
  14509. else {
  14510. var onload = function (img) {
  14511. if (fromBlob && !_this._doNotHandleContextLost) {
  14512. // We need to store the image if we need to rebuild the texture
  14513. // in case of a webgl context lost
  14514. texture._buffer = img;
  14515. }
  14516. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14517. var gl = _this._gl;
  14518. var isPot = (img.width === potWidth && img.height === potHeight);
  14519. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14520. if (isPot) {
  14521. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14522. return false;
  14523. }
  14524. var maxTextureSize = _this._caps.maxTextureSize;
  14525. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14526. _this._prepareWorkingCanvas();
  14527. if (!_this._workingCanvas || !_this._workingContext) {
  14528. return false;
  14529. }
  14530. _this._workingCanvas.width = potWidth;
  14531. _this._workingCanvas.height = potHeight;
  14532. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14533. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14534. texture.width = potWidth;
  14535. texture.height = potHeight;
  14536. return false;
  14537. }
  14538. else {
  14539. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14540. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14541. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14542. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14547. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14548. _this._releaseTexture(source_1);
  14549. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14550. continuationCallback();
  14551. });
  14552. }
  14553. return true;
  14554. }, samplingMode);
  14555. };
  14556. if (!fromData || isBase64) {
  14557. if (buffer instanceof HTMLImageElement) {
  14558. onload(buffer);
  14559. }
  14560. else {
  14561. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14562. }
  14563. }
  14564. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14565. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14566. }
  14567. else {
  14568. onload(buffer);
  14569. }
  14570. }
  14571. return texture;
  14572. };
  14573. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14574. var _this = this;
  14575. var rtt = this.createRenderTargetTexture({
  14576. width: destination.width,
  14577. height: destination.height,
  14578. }, {
  14579. generateMipMaps: false,
  14580. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14581. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14582. generateDepthBuffer: false,
  14583. generateStencilBuffer: false
  14584. });
  14585. if (!this._rescalePostProcess) {
  14586. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14587. }
  14588. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14589. _this._rescalePostProcess.onApply = function (effect) {
  14590. effect._bindTexture("textureSampler", source);
  14591. };
  14592. var hostingScene = scene;
  14593. if (!hostingScene) {
  14594. hostingScene = _this.scenes[_this.scenes.length - 1];
  14595. }
  14596. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14597. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14598. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14599. _this.unBindFramebuffer(rtt);
  14600. _this._releaseTexture(rtt);
  14601. if (onComplete) {
  14602. onComplete();
  14603. }
  14604. });
  14605. };
  14606. /**
  14607. * Update a raw texture
  14608. * @param texture defines the texture to update
  14609. * @param data defines the data to store in the texture
  14610. * @param format defines the format of the data
  14611. * @param invertY defines if data must be stored with Y axis inverted
  14612. * @param compression defines the compression used (null by default)
  14613. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14614. */
  14615. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14616. if (compression === void 0) { compression = null; }
  14617. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14618. if (!texture) {
  14619. return;
  14620. }
  14621. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14622. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14623. // babylon's internalFormat but gl's texImage2D format
  14624. var internalFormat = this._getInternalFormat(format);
  14625. var textureType = this._getWebGLTextureType(type);
  14626. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14627. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14628. if (!this._doNotHandleContextLost) {
  14629. texture._bufferView = data;
  14630. texture.format = format;
  14631. texture.type = type;
  14632. texture.invertY = invertY;
  14633. texture._compression = compression;
  14634. }
  14635. if (texture.width % 4 !== 0) {
  14636. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14637. }
  14638. if (compression && data) {
  14639. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14640. }
  14641. else {
  14642. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14643. }
  14644. if (texture.generateMipMaps) {
  14645. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14646. }
  14647. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14648. // this.resetTextureCache();
  14649. texture.isReady = true;
  14650. };
  14651. /**
  14652. * Creates a raw texture
  14653. * @param data defines the data to store in the texture
  14654. * @param width defines the width of the texture
  14655. * @param height defines the height of the texture
  14656. * @param format defines the format of the data
  14657. * @param generateMipMaps defines if the engine should generate the mip levels
  14658. * @param invertY defines if data must be stored with Y axis inverted
  14659. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14660. * @param compression defines the compression used (null by default)
  14661. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14662. * @returns the raw texture inside an InternalTexture
  14663. */
  14664. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14665. if (compression === void 0) { compression = null; }
  14666. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14667. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14668. texture.baseWidth = width;
  14669. texture.baseHeight = height;
  14670. texture.width = width;
  14671. texture.height = height;
  14672. texture.format = format;
  14673. texture.generateMipMaps = generateMipMaps;
  14674. texture.samplingMode = samplingMode;
  14675. texture.invertY = invertY;
  14676. texture._compression = compression;
  14677. texture.type = type;
  14678. if (!this._doNotHandleContextLost) {
  14679. texture._bufferView = data;
  14680. }
  14681. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14682. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14683. // Filters
  14684. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14686. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14687. if (generateMipMaps) {
  14688. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14689. }
  14690. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14691. this._internalTexturesCache.push(texture);
  14692. return texture;
  14693. };
  14694. /** @hidden */
  14695. Engine.prototype._unpackFlipY = function (value) {
  14696. if (this._unpackFlipYCached !== value) {
  14697. this._unpackFlipYCached = value;
  14698. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14699. }
  14700. };
  14701. /** @hidden */
  14702. Engine.prototype._getUnpackAlignement = function () {
  14703. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14704. };
  14705. /**
  14706. * Creates a dynamic texture
  14707. * @param width defines the width of the texture
  14708. * @param height defines the height of the texture
  14709. * @param generateMipMaps defines if the engine should generate the mip levels
  14710. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14711. * @returns the dynamic texture inside an InternalTexture
  14712. */
  14713. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14714. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14715. texture.baseWidth = width;
  14716. texture.baseHeight = height;
  14717. if (generateMipMaps) {
  14718. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14719. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14720. }
  14721. // this.resetTextureCache();
  14722. texture.width = width;
  14723. texture.height = height;
  14724. texture.isReady = false;
  14725. texture.generateMipMaps = generateMipMaps;
  14726. texture.samplingMode = samplingMode;
  14727. this.updateTextureSamplingMode(samplingMode, texture);
  14728. this._internalTexturesCache.push(texture);
  14729. return texture;
  14730. };
  14731. /**
  14732. * Update the sampling mode of a given texture
  14733. * @param samplingMode defines the required sampling mode
  14734. * @param texture defines the texture to update
  14735. */
  14736. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14737. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14738. if (texture.isCube) {
  14739. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14740. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14741. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14742. }
  14743. else if (texture.is3D) {
  14744. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14745. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14746. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14747. }
  14748. else {
  14749. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14750. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14751. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14752. }
  14753. texture.samplingMode = samplingMode;
  14754. };
  14755. /**
  14756. * Update the content of a dynamic texture
  14757. * @param texture defines the texture to update
  14758. * @param canvas defines the canvas containing the source
  14759. * @param invertY defines if data must be stored with Y axis inverted
  14760. * @param premulAlpha defines if alpha is stored as premultiplied
  14761. * @param format defines the format of the data
  14762. */
  14763. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14764. if (premulAlpha === void 0) { premulAlpha = false; }
  14765. if (!texture) {
  14766. return;
  14767. }
  14768. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14769. this._unpackFlipY(invertY);
  14770. if (premulAlpha) {
  14771. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14772. }
  14773. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14774. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14775. if (texture.generateMipMaps) {
  14776. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14777. }
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. if (premulAlpha) {
  14780. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14781. }
  14782. texture.isReady = true;
  14783. };
  14784. /**
  14785. * Update a video texture
  14786. * @param texture defines the texture to update
  14787. * @param video defines the video element to use
  14788. * @param invertY defines if data must be stored with Y axis inverted
  14789. */
  14790. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14791. if (!texture || texture._isDisabled) {
  14792. return;
  14793. }
  14794. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14795. this._unpackFlipY(!invertY); // Video are upside down by default
  14796. try {
  14797. // Testing video texture support
  14798. if (this._videoTextureSupported === undefined) {
  14799. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14800. if (this._gl.getError() !== 0) {
  14801. this._videoTextureSupported = false;
  14802. }
  14803. else {
  14804. this._videoTextureSupported = true;
  14805. }
  14806. }
  14807. // Copy video through the current working canvas if video texture is not supported
  14808. if (!this._videoTextureSupported) {
  14809. if (!texture._workingCanvas) {
  14810. texture._workingCanvas = document.createElement("canvas");
  14811. var context = texture._workingCanvas.getContext("2d");
  14812. if (!context) {
  14813. throw new Error("Unable to get 2d context");
  14814. }
  14815. texture._workingContext = context;
  14816. texture._workingCanvas.width = texture.width;
  14817. texture._workingCanvas.height = texture.height;
  14818. }
  14819. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14821. }
  14822. else {
  14823. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14824. }
  14825. if (texture.generateMipMaps) {
  14826. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14827. }
  14828. if (!wasPreviouslyBound) {
  14829. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14830. }
  14831. // this.resetTextureCache();
  14832. texture.isReady = true;
  14833. }
  14834. catch (ex) {
  14835. // Something unexpected
  14836. // Let's disable the texture
  14837. texture._isDisabled = true;
  14838. }
  14839. };
  14840. /**
  14841. * Updates a depth texture Comparison Mode and Function.
  14842. * If the comparison Function is equal to 0, the mode will be set to none.
  14843. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14844. * @param texture The texture to set the comparison function for
  14845. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14846. */
  14847. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14848. if (this.webGLVersion === 1) {
  14849. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14850. return;
  14851. }
  14852. var gl = this._gl;
  14853. if (texture.isCube) {
  14854. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14855. if (comparisonFunction === 0) {
  14856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14858. }
  14859. else {
  14860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14862. }
  14863. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14864. }
  14865. else {
  14866. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14867. if (comparisonFunction === 0) {
  14868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14870. }
  14871. else {
  14872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14874. }
  14875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14876. }
  14877. texture._comparisonFunction = comparisonFunction;
  14878. };
  14879. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14880. var width = size.width || size;
  14881. var height = size.height || size;
  14882. internalTexture.baseWidth = width;
  14883. internalTexture.baseHeight = height;
  14884. internalTexture.width = width;
  14885. internalTexture.height = height;
  14886. internalTexture.isReady = true;
  14887. internalTexture.samples = 1;
  14888. internalTexture.generateMipMaps = false;
  14889. internalTexture._generateDepthBuffer = true;
  14890. internalTexture._generateStencilBuffer = generateStencil;
  14891. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14892. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14893. internalTexture._comparisonFunction = comparisonFunction;
  14894. var gl = this._gl;
  14895. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14896. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14897. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14898. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14899. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14900. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14901. if (comparisonFunction === 0) {
  14902. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14903. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14904. }
  14905. else {
  14906. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14907. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14908. }
  14909. };
  14910. /**
  14911. * Creates a depth stencil texture.
  14912. * This is only available in WebGL 2 or with the depth texture extension available.
  14913. * @param size The size of face edge in the texture.
  14914. * @param options The options defining the texture.
  14915. * @returns The texture
  14916. */
  14917. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14918. if (options.isCube) {
  14919. var width = size.width || size;
  14920. return this._createDepthStencilCubeTexture(width, options);
  14921. }
  14922. else {
  14923. return this._createDepthStencilTexture(size, options);
  14924. }
  14925. };
  14926. /**
  14927. * Creates a depth stencil texture.
  14928. * This is only available in WebGL 2 or with the depth texture extension available.
  14929. * @param size The size of face edge in the texture.
  14930. * @param options The options defining the texture.
  14931. * @returns The texture
  14932. */
  14933. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14934. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14935. if (!this._caps.depthTextureExtension) {
  14936. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14937. return internalTexture;
  14938. }
  14939. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14940. var gl = this._gl;
  14941. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14942. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14943. if (this.webGLVersion > 1) {
  14944. if (internalOptions.generateStencil) {
  14945. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14946. }
  14947. else {
  14948. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14949. }
  14950. }
  14951. else {
  14952. if (internalOptions.generateStencil) {
  14953. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14954. }
  14955. else {
  14956. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14957. }
  14958. }
  14959. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14960. return internalTexture;
  14961. };
  14962. /**
  14963. * Creates a depth stencil cube texture.
  14964. * This is only available in WebGL 2.
  14965. * @param size The size of face edge in the cube texture.
  14966. * @param options The options defining the cube texture.
  14967. * @returns The cube texture
  14968. */
  14969. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14970. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14971. internalTexture.isCube = true;
  14972. if (this.webGLVersion === 1) {
  14973. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14974. return internalTexture;
  14975. }
  14976. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14977. var gl = this._gl;
  14978. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14979. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14980. // Create the depth/stencil buffer
  14981. for (var face = 0; face < 6; face++) {
  14982. if (internalOptions.generateStencil) {
  14983. 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);
  14984. }
  14985. else {
  14986. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14987. }
  14988. }
  14989. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14990. return internalTexture;
  14991. };
  14992. /**
  14993. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14994. * @param renderTarget The render target to set the frame buffer for
  14995. */
  14996. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14997. // Create the framebuffer
  14998. var internalTexture = renderTarget.getInternalTexture();
  14999. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15000. return;
  15001. }
  15002. var gl = this._gl;
  15003. var depthStencilTexture = renderTarget.depthStencilTexture;
  15004. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15005. if (depthStencilTexture.isCube) {
  15006. if (depthStencilTexture._generateStencilBuffer) {
  15007. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15008. }
  15009. else {
  15010. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15011. }
  15012. }
  15013. else {
  15014. if (depthStencilTexture._generateStencilBuffer) {
  15015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15016. }
  15017. else {
  15018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15019. }
  15020. }
  15021. this.bindUnboundFramebuffer(null);
  15022. };
  15023. /**
  15024. * Creates a new render target texture
  15025. * @param size defines the size of the texture
  15026. * @param options defines the options used to create the texture
  15027. * @returns a new render target texture stored in an InternalTexture
  15028. */
  15029. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15030. var fullOptions = new RenderTargetCreationOptions();
  15031. if (options !== undefined && typeof options === "object") {
  15032. fullOptions.generateMipMaps = options.generateMipMaps;
  15033. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15034. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15035. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15036. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15037. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15038. }
  15039. else {
  15040. fullOptions.generateMipMaps = options;
  15041. fullOptions.generateDepthBuffer = true;
  15042. fullOptions.generateStencilBuffer = false;
  15043. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15044. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15045. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15046. }
  15047. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15048. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15049. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15050. }
  15051. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15052. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15053. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15054. }
  15055. var gl = this._gl;
  15056. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15057. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15058. var width = size.width || size;
  15059. var height = size.height || size;
  15060. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15061. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15062. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15063. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15064. }
  15065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15069. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15070. // Create the framebuffer
  15071. var currentFrameBuffer = this._currentFramebuffer;
  15072. var framebuffer = gl.createFramebuffer();
  15073. this.bindUnboundFramebuffer(framebuffer);
  15074. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15075. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15076. if (fullOptions.generateMipMaps) {
  15077. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15078. }
  15079. // Unbind
  15080. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15081. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15082. this.bindUnboundFramebuffer(currentFrameBuffer);
  15083. texture._framebuffer = framebuffer;
  15084. texture.baseWidth = width;
  15085. texture.baseHeight = height;
  15086. texture.width = width;
  15087. texture.height = height;
  15088. texture.isReady = true;
  15089. texture.samples = 1;
  15090. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15091. texture.samplingMode = fullOptions.samplingMode;
  15092. texture.type = fullOptions.type;
  15093. texture.format = fullOptions.format;
  15094. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15095. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15096. // this.resetTextureCache();
  15097. this._internalTexturesCache.push(texture);
  15098. return texture;
  15099. };
  15100. /**
  15101. * Create a multi render target texture
  15102. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15103. * @param size defines the size of the texture
  15104. * @param options defines the creation options
  15105. * @returns the cube texture as an InternalTexture
  15106. */
  15107. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15108. var generateMipMaps = false;
  15109. var generateDepthBuffer = true;
  15110. var generateStencilBuffer = false;
  15111. var generateDepthTexture = false;
  15112. var textureCount = 1;
  15113. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15114. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15115. var types = new Array();
  15116. var samplingModes = new Array();
  15117. if (options !== undefined) {
  15118. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15119. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15120. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15121. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15122. textureCount = options.textureCount || 1;
  15123. if (options.types) {
  15124. types = options.types;
  15125. }
  15126. if (options.samplingModes) {
  15127. samplingModes = options.samplingModes;
  15128. }
  15129. }
  15130. var gl = this._gl;
  15131. // Create the framebuffer
  15132. var framebuffer = gl.createFramebuffer();
  15133. this.bindUnboundFramebuffer(framebuffer);
  15134. var width = size.width || size;
  15135. var height = size.height || size;
  15136. var textures = [];
  15137. var attachments = [];
  15138. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15139. for (var i = 0; i < textureCount; i++) {
  15140. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15141. var type = types[i] || defaultType;
  15142. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15143. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15144. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15145. }
  15146. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15147. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15148. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15149. }
  15150. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15151. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15152. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15153. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15154. }
  15155. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15156. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15157. textures.push(texture);
  15158. attachments.push(attachment);
  15159. gl.activeTexture(gl["TEXTURE" + i]);
  15160. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15165. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15166. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15167. if (generateMipMaps) {
  15168. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15169. }
  15170. // Unbind
  15171. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15172. texture._framebuffer = framebuffer;
  15173. texture._depthStencilBuffer = depthStencilBuffer;
  15174. texture.baseWidth = width;
  15175. texture.baseHeight = height;
  15176. texture.width = width;
  15177. texture.height = height;
  15178. texture.isReady = true;
  15179. texture.samples = 1;
  15180. texture.generateMipMaps = generateMipMaps;
  15181. texture.samplingMode = samplingMode;
  15182. texture.type = type;
  15183. texture._generateDepthBuffer = generateDepthBuffer;
  15184. texture._generateStencilBuffer = generateStencilBuffer;
  15185. texture._attachments = attachments;
  15186. this._internalTexturesCache.push(texture);
  15187. }
  15188. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15189. // Depth texture
  15190. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15191. gl.activeTexture(gl.TEXTURE0);
  15192. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15197. 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);
  15198. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15199. depthTexture._framebuffer = framebuffer;
  15200. depthTexture.baseWidth = width;
  15201. depthTexture.baseHeight = height;
  15202. depthTexture.width = width;
  15203. depthTexture.height = height;
  15204. depthTexture.isReady = true;
  15205. depthTexture.samples = 1;
  15206. depthTexture.generateMipMaps = generateMipMaps;
  15207. depthTexture.samplingMode = gl.NEAREST;
  15208. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15209. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15210. textures.push(depthTexture);
  15211. this._internalTexturesCache.push(depthTexture);
  15212. }
  15213. gl.drawBuffers(attachments);
  15214. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15215. this.bindUnboundFramebuffer(null);
  15216. this.resetTextureCache();
  15217. return textures;
  15218. };
  15219. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15220. if (samples === void 0) { samples = 1; }
  15221. var depthStencilBuffer = null;
  15222. var gl = this._gl;
  15223. // Create the depth/stencil buffer
  15224. if (generateStencilBuffer) {
  15225. depthStencilBuffer = gl.createRenderbuffer();
  15226. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15227. if (samples > 1) {
  15228. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15229. }
  15230. else {
  15231. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15232. }
  15233. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15234. }
  15235. else if (generateDepthBuffer) {
  15236. depthStencilBuffer = gl.createRenderbuffer();
  15237. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15238. if (samples > 1) {
  15239. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15240. }
  15241. else {
  15242. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15243. }
  15244. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15245. }
  15246. return depthStencilBuffer;
  15247. };
  15248. /**
  15249. * Updates the sample count of a render target texture
  15250. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15251. * @param texture defines the texture to update
  15252. * @param samples defines the sample count to set
  15253. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15254. */
  15255. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15256. if (this.webGLVersion < 2 || !texture) {
  15257. return 1;
  15258. }
  15259. if (texture.samples === samples) {
  15260. return samples;
  15261. }
  15262. var gl = this._gl;
  15263. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15264. // Dispose previous render buffers
  15265. if (texture._depthStencilBuffer) {
  15266. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15267. texture._depthStencilBuffer = null;
  15268. }
  15269. if (texture._MSAAFramebuffer) {
  15270. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15271. texture._MSAAFramebuffer = null;
  15272. }
  15273. if (texture._MSAARenderBuffer) {
  15274. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15275. texture._MSAARenderBuffer = null;
  15276. }
  15277. if (samples > 1) {
  15278. var framebuffer = gl.createFramebuffer();
  15279. if (!framebuffer) {
  15280. throw new Error("Unable to create multi sampled framebuffer");
  15281. }
  15282. texture._MSAAFramebuffer = framebuffer;
  15283. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15284. var colorRenderbuffer = gl.createRenderbuffer();
  15285. if (!colorRenderbuffer) {
  15286. throw new Error("Unable to create multi sampled framebuffer");
  15287. }
  15288. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15289. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15290. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15291. texture._MSAARenderBuffer = colorRenderbuffer;
  15292. }
  15293. else {
  15294. this.bindUnboundFramebuffer(texture._framebuffer);
  15295. }
  15296. texture.samples = samples;
  15297. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15298. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15299. this.bindUnboundFramebuffer(null);
  15300. return samples;
  15301. };
  15302. /**
  15303. * Update the sample count for a given multiple render target texture
  15304. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15305. * @param textures defines the textures to update
  15306. * @param samples defines the sample count to set
  15307. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15308. */
  15309. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15310. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15311. return 1;
  15312. }
  15313. if (textures[0].samples === samples) {
  15314. return samples;
  15315. }
  15316. var gl = this._gl;
  15317. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15318. // Dispose previous render buffers
  15319. if (textures[0]._depthStencilBuffer) {
  15320. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15321. textures[0]._depthStencilBuffer = null;
  15322. }
  15323. if (textures[0]._MSAAFramebuffer) {
  15324. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15325. textures[0]._MSAAFramebuffer = null;
  15326. }
  15327. for (var i = 0; i < textures.length; i++) {
  15328. if (textures[i]._MSAARenderBuffer) {
  15329. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15330. textures[i]._MSAARenderBuffer = null;
  15331. }
  15332. }
  15333. if (samples > 1) {
  15334. var framebuffer = gl.createFramebuffer();
  15335. if (!framebuffer) {
  15336. throw new Error("Unable to create multi sampled framebuffer");
  15337. }
  15338. this.bindUnboundFramebuffer(framebuffer);
  15339. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15340. var attachments = [];
  15341. for (var i = 0; i < textures.length; i++) {
  15342. var texture = textures[i];
  15343. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15344. var colorRenderbuffer = gl.createRenderbuffer();
  15345. if (!colorRenderbuffer) {
  15346. throw new Error("Unable to create multi sampled framebuffer");
  15347. }
  15348. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15349. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15350. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15351. texture._MSAAFramebuffer = framebuffer;
  15352. texture._MSAARenderBuffer = colorRenderbuffer;
  15353. texture.samples = samples;
  15354. texture._depthStencilBuffer = depthStencilBuffer;
  15355. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15356. attachments.push(attachment);
  15357. }
  15358. gl.drawBuffers(attachments);
  15359. }
  15360. else {
  15361. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15362. }
  15363. this.bindUnboundFramebuffer(null);
  15364. return samples;
  15365. };
  15366. /** @hidden */
  15367. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15368. if (faceIndex === void 0) { faceIndex = 0; }
  15369. if (lod === void 0) { lod = 0; }
  15370. var gl = this._gl;
  15371. var target = gl.TEXTURE_2D;
  15372. if (texture.isCube) {
  15373. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15374. }
  15375. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15376. };
  15377. /** @hidden */
  15378. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15379. if (faceIndex === void 0) { faceIndex = 0; }
  15380. if (lod === void 0) { lod = 0; }
  15381. var gl = this._gl;
  15382. var textureType = this._getWebGLTextureType(texture.type);
  15383. var format = this._getInternalFormat(texture.format);
  15384. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15385. this._unpackFlipY(texture.invertY);
  15386. var target = gl.TEXTURE_2D;
  15387. if (texture.isCube) {
  15388. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15389. }
  15390. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15391. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15392. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15393. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15394. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15395. };
  15396. /** @hidden */
  15397. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15398. if (faceIndex === void 0) { faceIndex = 0; }
  15399. if (lod === void 0) { lod = 0; }
  15400. var gl = this._gl;
  15401. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15402. this._bindTextureDirectly(bindTarget, texture, true);
  15403. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15404. this._bindTextureDirectly(bindTarget, null, true);
  15405. };
  15406. /** @hidden */
  15407. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15408. if (faceIndex === void 0) { faceIndex = 0; }
  15409. if (lod === void 0) { lod = 0; }
  15410. var gl = this._gl;
  15411. var textureType = this._getWebGLTextureType(texture.type);
  15412. var format = this._getInternalFormat(texture.format);
  15413. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15414. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15415. this._bindTextureDirectly(bindTarget, texture, true);
  15416. this._unpackFlipY(texture.invertY);
  15417. var target = gl.TEXTURE_2D;
  15418. if (texture.isCube) {
  15419. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15420. }
  15421. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15422. this._bindTextureDirectly(bindTarget, null, true);
  15423. };
  15424. /**
  15425. * Creates a new render target cube texture
  15426. * @param size defines the size of the texture
  15427. * @param options defines the options used to create the texture
  15428. * @returns a new render target cube texture stored in an InternalTexture
  15429. */
  15430. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15431. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15432. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15433. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15434. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15435. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15436. }
  15437. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15438. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15439. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15440. }
  15441. var gl = this._gl;
  15442. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15443. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15444. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15445. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15446. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15447. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15448. }
  15449. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15450. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15453. for (var face = 0; face < 6; face++) {
  15454. 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);
  15455. }
  15456. // Create the framebuffer
  15457. var framebuffer = gl.createFramebuffer();
  15458. this.bindUnboundFramebuffer(framebuffer);
  15459. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15460. // MipMaps
  15461. if (fullOptions.generateMipMaps) {
  15462. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15463. }
  15464. // Unbind
  15465. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15466. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15467. this.bindUnboundFramebuffer(null);
  15468. texture._framebuffer = framebuffer;
  15469. texture.width = size;
  15470. texture.height = size;
  15471. texture.isReady = true;
  15472. texture.isCube = true;
  15473. texture.samples = 1;
  15474. texture.generateMipMaps = fullOptions.generateMipMaps;
  15475. texture.samplingMode = fullOptions.samplingMode;
  15476. texture.type = fullOptions.type;
  15477. texture.format = fullOptions.format;
  15478. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15479. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15480. this._internalTexturesCache.push(texture);
  15481. return texture;
  15482. };
  15483. /**
  15484. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15485. * @param rootUrl defines the url where the file to load is located
  15486. * @param scene defines the current scene
  15487. * @param lodScale defines scale to apply to the mip map selection
  15488. * @param lodOffset defines offset to apply to the mip map selection
  15489. * @param onLoad defines an optional callback raised when the texture is loaded
  15490. * @param onError defines an optional callback raised if there is an issue to load the texture
  15491. * @param format defines the format of the data
  15492. * @param forcedExtension defines the extension to use to pick the right loader
  15493. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15494. * @returns the cube texture as an InternalTexture
  15495. */
  15496. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15497. var _this = this;
  15498. if (onLoad === void 0) { onLoad = null; }
  15499. if (onError === void 0) { onError = null; }
  15500. if (forcedExtension === void 0) { forcedExtension = null; }
  15501. if (createPolynomials === void 0) { createPolynomials = true; }
  15502. var callback = function (loadData) {
  15503. if (!loadData) {
  15504. if (onLoad) {
  15505. onLoad(null);
  15506. }
  15507. return;
  15508. }
  15509. var texture = loadData.texture;
  15510. if (!createPolynomials) {
  15511. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15512. }
  15513. else if (loadData.info.sphericalPolynomial) {
  15514. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15515. }
  15516. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15517. if (_this._caps.textureLOD) {
  15518. // Do not add extra process if texture lod is supported.
  15519. if (onLoad) {
  15520. onLoad(texture);
  15521. }
  15522. return;
  15523. }
  15524. var mipSlices = 3;
  15525. var gl = _this._gl;
  15526. var width = loadData.width;
  15527. if (!width) {
  15528. return;
  15529. }
  15530. var textures = [];
  15531. for (var i = 0; i < mipSlices; i++) {
  15532. //compute LOD from even spacing in smoothness (matching shader calculation)
  15533. var smoothness = i / (mipSlices - 1);
  15534. var roughness = 1 - smoothness;
  15535. var minLODIndex = lodOffset; // roughness = 0
  15536. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15537. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15538. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15539. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15540. glTextureFromLod.type = texture.type;
  15541. glTextureFromLod.format = texture.format;
  15542. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15543. glTextureFromLod.height = glTextureFromLod.width;
  15544. glTextureFromLod.isCube = true;
  15545. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15550. if (loadData.isDDS) {
  15551. var info = loadData.info;
  15552. var data = loadData.data;
  15553. _this._unpackFlipY(info.isCompressed);
  15554. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15555. }
  15556. else {
  15557. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15558. }
  15559. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15560. // Wrap in a base texture for easy binding.
  15561. var lodTexture = new BABYLON.BaseTexture(scene);
  15562. lodTexture.isCube = true;
  15563. lodTexture._texture = glTextureFromLod;
  15564. glTextureFromLod.isReady = true;
  15565. textures.push(lodTexture);
  15566. }
  15567. texture._lodTextureHigh = textures[2];
  15568. texture._lodTextureMid = textures[1];
  15569. texture._lodTextureLow = textures[0];
  15570. if (onLoad) {
  15571. onLoad(texture);
  15572. }
  15573. };
  15574. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15575. };
  15576. /**
  15577. * Creates a cube texture
  15578. * @param rootUrl defines the url where the files to load is located
  15579. * @param scene defines the current scene
  15580. * @param files defines the list of files to load (1 per face)
  15581. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15582. * @param onLoad defines an optional callback raised when the texture is loaded
  15583. * @param onError defines an optional callback raised if there is an issue to load the texture
  15584. * @param format defines the format of the data
  15585. * @param forcedExtension defines the extension to use to pick the right loader
  15586. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15587. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15588. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15589. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15590. * @returns the cube texture as an InternalTexture
  15591. */
  15592. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15593. var _this = this;
  15594. if (onLoad === void 0) { onLoad = null; }
  15595. if (onError === void 0) { onError = null; }
  15596. if (forcedExtension === void 0) { forcedExtension = null; }
  15597. if (createPolynomials === void 0) { createPolynomials = false; }
  15598. if (lodScale === void 0) { lodScale = 0; }
  15599. if (lodOffset === void 0) { lodOffset = 0; }
  15600. if (fallback === void 0) { fallback = null; }
  15601. var gl = this._gl;
  15602. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15603. texture.isCube = true;
  15604. texture.url = rootUrl;
  15605. texture.generateMipMaps = !noMipmap;
  15606. texture._lodGenerationScale = lodScale;
  15607. texture._lodGenerationOffset = lodOffset;
  15608. if (!this._doNotHandleContextLost) {
  15609. texture._extension = forcedExtension;
  15610. texture._files = files;
  15611. }
  15612. var lastDot = rootUrl.lastIndexOf('.');
  15613. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15614. var loader = null;
  15615. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15616. var availableLoader = _a[_i];
  15617. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15618. loader = availableLoader;
  15619. break;
  15620. }
  15621. }
  15622. var onInternalError = function (request, exception) {
  15623. if (loader) {
  15624. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15625. if (fallbackUrl) {
  15626. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15627. }
  15628. }
  15629. if (onError && request) {
  15630. onError(request.status + " " + request.statusText, exception);
  15631. }
  15632. };
  15633. if (loader) {
  15634. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15635. var onloaddata = function (data) {
  15636. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15637. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15638. };
  15639. if (files && files.length === 6) {
  15640. if (loader.supportCascades) {
  15641. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15642. }
  15643. else if (onError) {
  15644. onError("Textures type does not support cascades.");
  15645. }
  15646. }
  15647. else {
  15648. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15649. }
  15650. }
  15651. else {
  15652. if (!files) {
  15653. throw new Error("Cannot load cubemap because files were not defined");
  15654. }
  15655. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15656. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15657. var height = width;
  15658. _this._prepareWorkingCanvas();
  15659. if (!_this._workingCanvas || !_this._workingContext) {
  15660. return;
  15661. }
  15662. _this._workingCanvas.width = width;
  15663. _this._workingCanvas.height = height;
  15664. var faces = [
  15665. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15666. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15667. ];
  15668. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15669. _this._unpackFlipY(false);
  15670. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15671. for (var index = 0; index < faces.length; index++) {
  15672. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15673. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15674. }
  15675. if (!noMipmap) {
  15676. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15677. }
  15678. _this._setCubeMapTextureParams(!noMipmap);
  15679. texture.width = width;
  15680. texture.height = height;
  15681. texture.isReady = true;
  15682. if (format) {
  15683. texture.format = format;
  15684. }
  15685. texture.onLoadedObservable.notifyObservers(texture);
  15686. texture.onLoadedObservable.clear();
  15687. if (onLoad) {
  15688. onLoad();
  15689. }
  15690. }, files, onError);
  15691. }
  15692. this._internalTexturesCache.push(texture);
  15693. return texture;
  15694. };
  15695. /**
  15696. * @hidden
  15697. */
  15698. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15699. var gl = this._gl;
  15700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15704. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15705. // this.resetTextureCache();
  15706. };
  15707. /**
  15708. * Update a raw cube texture
  15709. * @param texture defines the texture to udpdate
  15710. * @param data defines the data to store
  15711. * @param format defines the data format
  15712. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15713. * @param invertY defines if data must be stored with Y axis inverted
  15714. * @param compression defines the compression used (null by default)
  15715. * @param level defines which level of the texture to update
  15716. */
  15717. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15718. if (compression === void 0) { compression = null; }
  15719. if (level === void 0) { level = 0; }
  15720. texture._bufferViewArray = data;
  15721. texture.format = format;
  15722. texture.type = type;
  15723. texture.invertY = invertY;
  15724. texture._compression = compression;
  15725. var gl = this._gl;
  15726. var textureType = this._getWebGLTextureType(type);
  15727. var internalFormat = this._getInternalFormat(format);
  15728. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15729. var needConversion = false;
  15730. if (internalFormat === gl.RGB) {
  15731. internalFormat = gl.RGBA;
  15732. needConversion = true;
  15733. }
  15734. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15735. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15736. if (texture.width % 4 !== 0) {
  15737. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15738. }
  15739. // Data are known to be in +X +Y +Z -X -Y -Z
  15740. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15741. var faceData = data[faceIndex];
  15742. if (compression) {
  15743. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15744. }
  15745. else {
  15746. if (needConversion) {
  15747. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15748. }
  15749. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15750. }
  15751. }
  15752. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15753. if (isPot && texture.generateMipMaps && level === 0) {
  15754. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15755. }
  15756. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15757. // this.resetTextureCache();
  15758. texture.isReady = true;
  15759. };
  15760. /**
  15761. * Creates a new raw cube texture
  15762. * @param data defines the array of data to use to create each face
  15763. * @param size defines the size of the textures
  15764. * @param format defines the format of the data
  15765. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15766. * @param generateMipMaps defines if the engine should generate the mip levels
  15767. * @param invertY defines if data must be stored with Y axis inverted
  15768. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15769. * @param compression defines the compression used (null by default)
  15770. * @returns the cube texture as an InternalTexture
  15771. */
  15772. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15773. if (compression === void 0) { compression = null; }
  15774. var gl = this._gl;
  15775. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15776. texture.isCube = true;
  15777. texture.format = format;
  15778. texture.type = type;
  15779. if (!this._doNotHandleContextLost) {
  15780. texture._bufferViewArray = data;
  15781. }
  15782. var textureType = this._getWebGLTextureType(type);
  15783. var internalFormat = this._getInternalFormat(format);
  15784. if (internalFormat === gl.RGB) {
  15785. internalFormat = gl.RGBA;
  15786. }
  15787. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15788. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15789. generateMipMaps = false;
  15790. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15791. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15792. }
  15793. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15794. generateMipMaps = false;
  15795. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15796. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15797. }
  15798. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15799. generateMipMaps = false;
  15800. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15801. }
  15802. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15803. generateMipMaps = false;
  15804. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15805. }
  15806. var width = size;
  15807. var height = width;
  15808. texture.width = width;
  15809. texture.height = height;
  15810. // Double check on POT to generate Mips.
  15811. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15812. if (!isPot) {
  15813. generateMipMaps = false;
  15814. }
  15815. // Upload data if needed. The texture won't be ready until then.
  15816. if (data) {
  15817. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15818. }
  15819. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15820. // Filters
  15821. if (data && generateMipMaps) {
  15822. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15823. }
  15824. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  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. texture.generateMipMaps = generateMipMaps;
  15831. return texture;
  15832. };
  15833. /**
  15834. * Creates a new raw cube texture from a specified url
  15835. * @param url defines the url where the data is located
  15836. * @param scene defines the current scene
  15837. * @param size defines the size of the textures
  15838. * @param format defines the format of the data
  15839. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15840. * @param noMipmap defines if the engine should avoid generating the mip levels
  15841. * @param callback defines a callback used to extract texture data from loaded data
  15842. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15843. * @param onLoad defines a callback called when texture is loaded
  15844. * @param onError defines a callback called if there is an error
  15845. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15846. * @param invertY defines if data must be stored with Y axis inverted
  15847. * @returns the cube texture as an InternalTexture
  15848. */
  15849. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15850. var _this = this;
  15851. if (onLoad === void 0) { onLoad = null; }
  15852. if (onError === void 0) { onError = null; }
  15853. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15854. if (invertY === void 0) { invertY = false; }
  15855. var gl = this._gl;
  15856. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15857. scene._addPendingData(texture);
  15858. texture.url = url;
  15859. this._internalTexturesCache.push(texture);
  15860. var onerror = function (request, exception) {
  15861. scene._removePendingData(texture);
  15862. if (onError && request) {
  15863. onError(request.status + " " + request.statusText, exception);
  15864. }
  15865. };
  15866. var internalCallback = function (data) {
  15867. var width = texture.width;
  15868. var faceDataArrays = callback(data);
  15869. if (!faceDataArrays) {
  15870. return;
  15871. }
  15872. if (mipmapGenerator) {
  15873. var textureType = _this._getWebGLTextureType(type);
  15874. var internalFormat = _this._getInternalFormat(format);
  15875. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15876. var needConversion = false;
  15877. if (internalFormat === gl.RGB) {
  15878. internalFormat = gl.RGBA;
  15879. needConversion = true;
  15880. }
  15881. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15882. _this._unpackFlipY(false);
  15883. var mipData = mipmapGenerator(faceDataArrays);
  15884. for (var level = 0; level < mipData.length; level++) {
  15885. var mipSize = width >> level;
  15886. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15887. var mipFaceData = mipData[level][faceIndex];
  15888. if (needConversion) {
  15889. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15890. }
  15891. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15892. }
  15893. }
  15894. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15895. }
  15896. else {
  15897. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15898. }
  15899. texture.isReady = true;
  15900. // this.resetTextureCache();
  15901. scene._removePendingData(texture);
  15902. if (onLoad) {
  15903. onLoad();
  15904. }
  15905. };
  15906. this._loadFile(url, function (data) {
  15907. internalCallback(data);
  15908. }, undefined, scene.database, true, onerror);
  15909. return texture;
  15910. };
  15911. ;
  15912. /**
  15913. * Update a raw 3D texture
  15914. * @param texture defines the texture to update
  15915. * @param data defines the data to store
  15916. * @param format defines the data format
  15917. * @param invertY defines if data must be stored with Y axis inverted
  15918. * @param compression defines the used compression (can be null)
  15919. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15920. */
  15921. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15922. if (compression === void 0) { compression = null; }
  15923. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15924. var internalType = this._getWebGLTextureType(textureType);
  15925. var internalFormat = this._getInternalFormat(format);
  15926. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15927. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15928. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15929. if (!this._doNotHandleContextLost) {
  15930. texture._bufferView = data;
  15931. texture.format = format;
  15932. texture.invertY = invertY;
  15933. texture._compression = compression;
  15934. }
  15935. if (texture.width % 4 !== 0) {
  15936. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15937. }
  15938. if (compression && data) {
  15939. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15940. }
  15941. else {
  15942. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15943. }
  15944. if (texture.generateMipMaps) {
  15945. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15946. }
  15947. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15948. // this.resetTextureCache();
  15949. texture.isReady = true;
  15950. };
  15951. /**
  15952. * Creates a new raw 3D texture
  15953. * @param data defines the data used to create the texture
  15954. * @param width defines the width of the texture
  15955. * @param height defines the height of the texture
  15956. * @param depth defines the depth of the texture
  15957. * @param format defines the format of the texture
  15958. * @param generateMipMaps defines if the engine must generate mip levels
  15959. * @param invertY defines if data must be stored with Y axis inverted
  15960. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15961. * @param compression defines the compressed used (can be null)
  15962. * @param textureType defines the compressed used (can be null)
  15963. * @returns a new raw 3D texture (stored in an InternalTexture)
  15964. */
  15965. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15966. if (compression === void 0) { compression = null; }
  15967. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15968. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15969. texture.baseWidth = width;
  15970. texture.baseHeight = height;
  15971. texture.baseDepth = depth;
  15972. texture.width = width;
  15973. texture.height = height;
  15974. texture.depth = depth;
  15975. texture.format = format;
  15976. texture.type = textureType;
  15977. texture.generateMipMaps = generateMipMaps;
  15978. texture.samplingMode = samplingMode;
  15979. texture.is3D = true;
  15980. if (!this._doNotHandleContextLost) {
  15981. texture._bufferView = data;
  15982. }
  15983. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15984. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15985. // Filters
  15986. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15987. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15988. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15989. if (generateMipMaps) {
  15990. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15991. }
  15992. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15993. this._internalTexturesCache.push(texture);
  15994. return texture;
  15995. };
  15996. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15997. var gl = this._gl;
  15998. if (!gl) {
  15999. return;
  16000. }
  16001. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16003. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16004. if (!noMipmap && !isCompressed) {
  16005. gl.generateMipmap(gl.TEXTURE_2D);
  16006. }
  16007. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16008. // this.resetTextureCache();
  16009. if (scene) {
  16010. scene._removePendingData(texture);
  16011. }
  16012. texture.onLoadedObservable.notifyObservers(texture);
  16013. texture.onLoadedObservable.clear();
  16014. };
  16015. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16016. var _this = this;
  16017. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16018. var maxTextureSize = this.getCaps().maxTextureSize;
  16019. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16020. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16021. var gl = this._gl;
  16022. if (!gl) {
  16023. return;
  16024. }
  16025. if (!texture._webGLTexture) {
  16026. // this.resetTextureCache();
  16027. if (scene) {
  16028. scene._removePendingData(texture);
  16029. }
  16030. return;
  16031. }
  16032. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16033. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16034. texture.baseWidth = width;
  16035. texture.baseHeight = height;
  16036. texture.width = potWidth;
  16037. texture.height = potHeight;
  16038. texture.isReady = true;
  16039. if (processFunction(potWidth, potHeight, function () {
  16040. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16041. })) {
  16042. // Returning as texture needs extra async steps
  16043. return;
  16044. }
  16045. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16046. };
  16047. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16048. // Create new RGBA data container.
  16049. var rgbaData;
  16050. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16051. rgbaData = new Float32Array(width * height * 4);
  16052. }
  16053. else {
  16054. rgbaData = new Uint32Array(width * height * 4);
  16055. }
  16056. // Convert each pixel.
  16057. for (var x = 0; x < width; x++) {
  16058. for (var y = 0; y < height; y++) {
  16059. var index = (y * width + x) * 3;
  16060. var newIndex = (y * width + x) * 4;
  16061. // Map Old Value to new value.
  16062. rgbaData[newIndex + 0] = rgbData[index + 0];
  16063. rgbaData[newIndex + 1] = rgbData[index + 1];
  16064. rgbaData[newIndex + 2] = rgbData[index + 2];
  16065. // Add fully opaque alpha channel.
  16066. rgbaData[newIndex + 3] = 1;
  16067. }
  16068. }
  16069. return rgbaData;
  16070. };
  16071. /** @hidden */
  16072. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16073. var gl = this._gl;
  16074. if (texture._framebuffer) {
  16075. gl.deleteFramebuffer(texture._framebuffer);
  16076. texture._framebuffer = null;
  16077. }
  16078. if (texture._depthStencilBuffer) {
  16079. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16080. texture._depthStencilBuffer = null;
  16081. }
  16082. if (texture._MSAAFramebuffer) {
  16083. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16084. texture._MSAAFramebuffer = null;
  16085. }
  16086. if (texture._MSAARenderBuffer) {
  16087. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16088. texture._MSAARenderBuffer = null;
  16089. }
  16090. };
  16091. /** @hidden */
  16092. Engine.prototype._releaseTexture = function (texture) {
  16093. var gl = this._gl;
  16094. this._releaseFramebufferObjects(texture);
  16095. gl.deleteTexture(texture._webGLTexture);
  16096. // Unbind channels
  16097. this.unbindAllTextures();
  16098. var index = this._internalTexturesCache.indexOf(texture);
  16099. if (index !== -1) {
  16100. this._internalTexturesCache.splice(index, 1);
  16101. }
  16102. // Integrated fixed lod samplers.
  16103. if (texture._lodTextureHigh) {
  16104. texture._lodTextureHigh.dispose();
  16105. }
  16106. if (texture._lodTextureMid) {
  16107. texture._lodTextureMid.dispose();
  16108. }
  16109. if (texture._lodTextureLow) {
  16110. texture._lodTextureLow.dispose();
  16111. }
  16112. // Set output texture of post process to null if the texture has been released/disposed
  16113. this.scenes.forEach(function (scene) {
  16114. scene.postProcesses.forEach(function (postProcess) {
  16115. if (postProcess._outputTexture == texture) {
  16116. postProcess._outputTexture = null;
  16117. }
  16118. });
  16119. scene.cameras.forEach(function (camera) {
  16120. camera._postProcesses.forEach(function (postProcess) {
  16121. if (postProcess) {
  16122. if (postProcess._outputTexture == texture) {
  16123. postProcess._outputTexture = null;
  16124. }
  16125. }
  16126. });
  16127. });
  16128. });
  16129. };
  16130. Engine.prototype.setProgram = function (program) {
  16131. if (this._currentProgram !== program) {
  16132. this._gl.useProgram(program);
  16133. this._currentProgram = program;
  16134. }
  16135. };
  16136. /**
  16137. * Binds an effect to the webGL context
  16138. * @param effect defines the effect to bind
  16139. */
  16140. Engine.prototype.bindSamplers = function (effect) {
  16141. this.setProgram(effect.getProgram());
  16142. var samplers = effect.getSamplers();
  16143. for (var index = 0; index < samplers.length; index++) {
  16144. var uniform = effect.getUniform(samplers[index]);
  16145. if (uniform) {
  16146. this._boundUniforms[index] = uniform;
  16147. }
  16148. }
  16149. this._currentEffect = null;
  16150. };
  16151. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16152. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16153. return;
  16154. }
  16155. // Remove
  16156. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16157. // Bind last to it
  16158. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16159. // Bind to dummy
  16160. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16161. };
  16162. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16163. if (!internalTexture) {
  16164. return -1;
  16165. }
  16166. internalTexture._initialSlot = channel;
  16167. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16168. if (channel !== internalTexture._designatedSlot) {
  16169. this._textureCollisions.addCount(1, false);
  16170. }
  16171. }
  16172. else {
  16173. if (channel !== internalTexture._designatedSlot) {
  16174. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16175. return internalTexture._designatedSlot;
  16176. }
  16177. else {
  16178. // No slot for this texture, let's pick a new one (if we find a free slot)
  16179. if (this._nextFreeTextureSlots.length) {
  16180. return this._nextFreeTextureSlots[0];
  16181. }
  16182. // We need to recycle the oldest bound texture, sorry.
  16183. this._textureCollisions.addCount(1, false);
  16184. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16185. }
  16186. }
  16187. }
  16188. return channel;
  16189. };
  16190. Engine.prototype._linkTrackers = function (previous, next) {
  16191. previous.next = next;
  16192. next.previous = previous;
  16193. };
  16194. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16195. var currentSlot = internalTexture._designatedSlot;
  16196. if (currentSlot === -1) {
  16197. return -1;
  16198. }
  16199. internalTexture._designatedSlot = -1;
  16200. if (this.disableTextureBindingOptimization) {
  16201. return -1;
  16202. }
  16203. // Remove from bound list
  16204. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16205. // Free the slot
  16206. this._boundTexturesCache[currentSlot] = null;
  16207. this._nextFreeTextureSlots.push(currentSlot);
  16208. return currentSlot;
  16209. };
  16210. Engine.prototype._activateCurrentTexture = function () {
  16211. if (this._currentTextureChannel !== this._activeChannel) {
  16212. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16213. this._currentTextureChannel = this._activeChannel;
  16214. }
  16215. };
  16216. /** @hidden */
  16217. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16218. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16219. if (force === void 0) { force = false; }
  16220. var wasPreviouslyBound = false;
  16221. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16222. this._activeChannel = texture._designatedSlot;
  16223. }
  16224. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16225. var isTextureForRendering = texture && texture._initialSlot > -1;
  16226. if (currentTextureBound !== texture || force) {
  16227. if (currentTextureBound) {
  16228. this._removeDesignatedSlot(currentTextureBound);
  16229. }
  16230. this._activateCurrentTexture();
  16231. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16232. this._boundTexturesCache[this._activeChannel] = texture;
  16233. if (texture) {
  16234. if (!this.disableTextureBindingOptimization) {
  16235. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16236. if (slotIndex > -1) {
  16237. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16238. }
  16239. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16240. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16241. }
  16242. texture._designatedSlot = this._activeChannel;
  16243. }
  16244. }
  16245. else if (forTextureDataUpdate) {
  16246. wasPreviouslyBound = true;
  16247. this._activateCurrentTexture();
  16248. }
  16249. if (isTextureForRendering && !forTextureDataUpdate) {
  16250. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16251. }
  16252. return wasPreviouslyBound;
  16253. };
  16254. /** @hidden */
  16255. Engine.prototype._bindTexture = function (channel, texture) {
  16256. if (channel < 0) {
  16257. return;
  16258. }
  16259. if (texture) {
  16260. channel = this._getCorrectTextureChannel(channel, texture);
  16261. }
  16262. this._activeChannel = channel;
  16263. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16264. };
  16265. /**
  16266. * Sets a texture to the webGL context from a postprocess
  16267. * @param channel defines the channel to use
  16268. * @param postProcess defines the source postprocess
  16269. */
  16270. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16271. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16272. };
  16273. /**
  16274. * Binds the output of the passed in post process to the texture channel specified
  16275. * @param channel The channel the texture should be bound to
  16276. * @param postProcess The post process which's output should be bound
  16277. */
  16278. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16279. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16280. };
  16281. /**
  16282. * Unbind all textures from the webGL context
  16283. */
  16284. Engine.prototype.unbindAllTextures = function () {
  16285. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16286. this._activeChannel = channel;
  16287. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16288. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16289. if (this.webGLVersion > 1) {
  16290. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16291. }
  16292. }
  16293. };
  16294. /**
  16295. * Sets a texture to the according uniform.
  16296. * @param channel The texture channel
  16297. * @param uniform The uniform to set
  16298. * @param texture The texture to apply
  16299. */
  16300. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16301. if (channel < 0) {
  16302. return;
  16303. }
  16304. if (uniform) {
  16305. this._boundUniforms[channel] = uniform;
  16306. }
  16307. this._setTexture(channel, texture);
  16308. };
  16309. /**
  16310. * Sets a depth stencil texture from a render target to the according uniform.
  16311. * @param channel The texture channel
  16312. * @param uniform The uniform to set
  16313. * @param texture The render target texture containing the depth stencil texture to apply
  16314. */
  16315. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16316. if (channel < 0) {
  16317. return;
  16318. }
  16319. if (uniform) {
  16320. this._boundUniforms[channel] = uniform;
  16321. }
  16322. if (!texture || !texture.depthStencilTexture) {
  16323. this._setTexture(channel, null);
  16324. }
  16325. else {
  16326. this._setTexture(channel, texture, false, true);
  16327. }
  16328. };
  16329. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16330. var uniform = this._boundUniforms[sourceSlot];
  16331. if (uniform._currentState === destination) {
  16332. return;
  16333. }
  16334. this._gl.uniform1i(uniform, destination);
  16335. uniform._currentState = destination;
  16336. };
  16337. Engine.prototype._getTextureWrapMode = function (mode) {
  16338. switch (mode) {
  16339. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16340. return this._gl.REPEAT;
  16341. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16342. return this._gl.CLAMP_TO_EDGE;
  16343. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16344. return this._gl.MIRRORED_REPEAT;
  16345. }
  16346. return this._gl.REPEAT;
  16347. };
  16348. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16349. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16350. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16351. // Not ready?
  16352. if (!texture) {
  16353. if (this._boundTexturesCache[channel] != null) {
  16354. this._activeChannel = channel;
  16355. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16356. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16357. if (this.webGLVersion > 1) {
  16358. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16359. }
  16360. }
  16361. return false;
  16362. }
  16363. // Video
  16364. if (texture.video) {
  16365. this._activeChannel = channel;
  16366. texture.update();
  16367. }
  16368. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16369. texture.delayLoad();
  16370. return false;
  16371. }
  16372. var internalTexture;
  16373. if (depthStencilTexture) {
  16374. internalTexture = texture.depthStencilTexture;
  16375. }
  16376. else if (texture.isReady()) {
  16377. internalTexture = texture.getInternalTexture();
  16378. }
  16379. else if (texture.isCube) {
  16380. internalTexture = this.emptyCubeTexture;
  16381. }
  16382. else if (texture.is3D) {
  16383. internalTexture = this.emptyTexture3D;
  16384. }
  16385. else {
  16386. internalTexture = this.emptyTexture;
  16387. }
  16388. if (!isPartOfTextureArray) {
  16389. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16390. }
  16391. var needToBind = true;
  16392. if (this._boundTexturesCache[channel] === internalTexture) {
  16393. this._moveBoundTextureOnTop(internalTexture);
  16394. if (!isPartOfTextureArray) {
  16395. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16396. }
  16397. needToBind = false;
  16398. }
  16399. this._activeChannel = channel;
  16400. if (internalTexture && internalTexture.is3D) {
  16401. if (needToBind) {
  16402. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16403. }
  16404. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16405. internalTexture._cachedWrapU = texture.wrapU;
  16406. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16407. }
  16408. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16409. internalTexture._cachedWrapV = texture.wrapV;
  16410. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16411. }
  16412. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16413. internalTexture._cachedWrapR = texture.wrapR;
  16414. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16415. }
  16416. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16417. }
  16418. else if (internalTexture && internalTexture.isCube) {
  16419. if (needToBind) {
  16420. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16421. }
  16422. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16423. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16424. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16425. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16426. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16427. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16428. }
  16429. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16430. }
  16431. else {
  16432. if (needToBind) {
  16433. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16434. }
  16435. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16436. internalTexture._cachedWrapU = texture.wrapU;
  16437. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16438. }
  16439. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16440. internalTexture._cachedWrapV = texture.wrapV;
  16441. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16442. }
  16443. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16444. }
  16445. return true;
  16446. };
  16447. /**
  16448. * Sets an array of texture to the webGL context
  16449. * @param channel defines the channel where the texture array must be set
  16450. * @param uniform defines the associated uniform location
  16451. * @param textures defines the array of textures to bind
  16452. */
  16453. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16454. if (channel < 0 || !uniform) {
  16455. return;
  16456. }
  16457. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16458. this._textureUnits = new Int32Array(textures.length);
  16459. }
  16460. for (var i = 0; i < textures.length; i++) {
  16461. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16462. }
  16463. this._gl.uniform1iv(uniform, this._textureUnits);
  16464. for (var index = 0; index < textures.length; index++) {
  16465. this._setTexture(this._textureUnits[index], textures[index], true);
  16466. }
  16467. };
  16468. /** @hidden */
  16469. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16470. var internalTexture = texture.getInternalTexture();
  16471. if (!internalTexture) {
  16472. return;
  16473. }
  16474. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16475. var value = texture.anisotropicFilteringLevel;
  16476. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16477. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16478. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16479. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16480. }
  16481. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16482. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16483. internalTexture._cachedAnisotropicFilteringLevel = value;
  16484. }
  16485. };
  16486. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16487. this._bindTextureDirectly(target, texture, true, true);
  16488. this._gl.texParameterf(target, parameter, value);
  16489. };
  16490. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16491. if (texture) {
  16492. this._bindTextureDirectly(target, texture, true, true);
  16493. }
  16494. this._gl.texParameteri(target, parameter, value);
  16495. };
  16496. /**
  16497. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16498. * @param x defines the x coordinate of the rectangle where pixels must be read
  16499. * @param y defines the y coordinate of the rectangle where pixels must be read
  16500. * @param width defines the width of the rectangle where pixels must be read
  16501. * @param height defines the height of the rectangle where pixels must be read
  16502. * @returns a Uint8Array containing RGBA colors
  16503. */
  16504. Engine.prototype.readPixels = function (x, y, width, height) {
  16505. var data = new Uint8Array(height * width * 4);
  16506. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16507. return data;
  16508. };
  16509. /**
  16510. * Add an externaly attached data from its key.
  16511. * This method call will fail and return false, if such key already exists.
  16512. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16513. * @param key the unique key that identifies the data
  16514. * @param data the data object to associate to the key for this Engine instance
  16515. * @return true if no such key were already present and the data was added successfully, false otherwise
  16516. */
  16517. Engine.prototype.addExternalData = function (key, data) {
  16518. if (!this._externalData) {
  16519. this._externalData = new BABYLON.StringDictionary();
  16520. }
  16521. return this._externalData.add(key, data);
  16522. };
  16523. /**
  16524. * Get an externaly attached data from its key
  16525. * @param key the unique key that identifies the data
  16526. * @return the associated data, if present (can be null), or undefined if not present
  16527. */
  16528. Engine.prototype.getExternalData = function (key) {
  16529. if (!this._externalData) {
  16530. this._externalData = new BABYLON.StringDictionary();
  16531. }
  16532. return this._externalData.get(key);
  16533. };
  16534. /**
  16535. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16536. * @param key the unique key that identifies the data
  16537. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16538. * @return the associated data, can be null if the factory returned null.
  16539. */
  16540. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16541. if (!this._externalData) {
  16542. this._externalData = new BABYLON.StringDictionary();
  16543. }
  16544. return this._externalData.getOrAddWithFactory(key, factory);
  16545. };
  16546. /**
  16547. * Remove an externaly attached data from the Engine instance
  16548. * @param key the unique key that identifies the data
  16549. * @return true if the data was successfully removed, false if it doesn't exist
  16550. */
  16551. Engine.prototype.removeExternalData = function (key) {
  16552. if (!this._externalData) {
  16553. this._externalData = new BABYLON.StringDictionary();
  16554. }
  16555. return this._externalData.remove(key);
  16556. };
  16557. /**
  16558. * Unbind all vertex attributes from the webGL context
  16559. */
  16560. Engine.prototype.unbindAllAttributes = function () {
  16561. if (this._mustWipeVertexAttributes) {
  16562. this._mustWipeVertexAttributes = false;
  16563. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16564. this._gl.disableVertexAttribArray(i);
  16565. this._vertexAttribArraysEnabled[i] = false;
  16566. this._currentBufferPointers[i].active = false;
  16567. }
  16568. return;
  16569. }
  16570. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16571. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16572. continue;
  16573. }
  16574. this._gl.disableVertexAttribArray(i);
  16575. this._vertexAttribArraysEnabled[i] = false;
  16576. this._currentBufferPointers[i].active = false;
  16577. }
  16578. };
  16579. /**
  16580. * 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
  16581. */
  16582. Engine.prototype.releaseEffects = function () {
  16583. for (var name in this._compiledEffects) {
  16584. this._deleteProgram(this._compiledEffects[name]._program);
  16585. }
  16586. this._compiledEffects = {};
  16587. };
  16588. /**
  16589. * Dispose and release all associated resources
  16590. */
  16591. Engine.prototype.dispose = function () {
  16592. this.hideLoadingUI();
  16593. this.stopRenderLoop();
  16594. // Release postProcesses
  16595. while (this.postProcesses.length) {
  16596. this.postProcesses[0].dispose();
  16597. }
  16598. // Empty texture
  16599. if (this._emptyTexture) {
  16600. this._releaseTexture(this._emptyTexture);
  16601. this._emptyTexture = null;
  16602. }
  16603. if (this._emptyCubeTexture) {
  16604. this._releaseTexture(this._emptyCubeTexture);
  16605. this._emptyCubeTexture = null;
  16606. }
  16607. // Rescale PP
  16608. if (this._rescalePostProcess) {
  16609. this._rescalePostProcess.dispose();
  16610. }
  16611. // Release scenes
  16612. while (this.scenes.length) {
  16613. this.scenes[0].dispose();
  16614. }
  16615. // Release audio engine
  16616. if (Engine.audioEngine) {
  16617. Engine.audioEngine.dispose();
  16618. }
  16619. // Release effects
  16620. this.releaseEffects();
  16621. // Unbind
  16622. this.unbindAllAttributes();
  16623. this._boundUniforms = [];
  16624. if (this._dummyFramebuffer) {
  16625. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16626. }
  16627. //WebVR
  16628. this.disableVR();
  16629. // Events
  16630. if (BABYLON.Tools.IsWindowObjectExist()) {
  16631. window.removeEventListener("blur", this._onBlur);
  16632. window.removeEventListener("focus", this._onFocus);
  16633. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16634. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16635. if (this._renderingCanvas) {
  16636. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16637. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16638. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16639. if (!this._doNotHandleContextLost) {
  16640. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16641. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16642. }
  16643. }
  16644. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16645. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16646. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16647. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16648. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16649. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16650. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16651. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16652. if (this._onVrDisplayConnect) {
  16653. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16654. if (this._onVrDisplayDisconnect) {
  16655. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16656. }
  16657. if (this._onVrDisplayPresentChange) {
  16658. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16659. }
  16660. this._onVrDisplayConnect = null;
  16661. this._onVrDisplayDisconnect = null;
  16662. }
  16663. }
  16664. // Remove from Instances
  16665. var index = Engine.Instances.indexOf(this);
  16666. if (index >= 0) {
  16667. Engine.Instances.splice(index, 1);
  16668. }
  16669. this._workingCanvas = null;
  16670. this._workingContext = null;
  16671. this._currentBufferPointers = [];
  16672. this._renderingCanvas = null;
  16673. this._currentProgram = null;
  16674. this._bindedRenderFunction = null;
  16675. this.onResizeObservable.clear();
  16676. this.onCanvasBlurObservable.clear();
  16677. this.onCanvasFocusObservable.clear();
  16678. this.onCanvasPointerOutObservable.clear();
  16679. this.onBeginFrameObservable.clear();
  16680. this.onEndFrameObservable.clear();
  16681. BABYLON.Effect.ResetCache();
  16682. // Abort active requests
  16683. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16684. var request = _a[_i];
  16685. request.abort();
  16686. }
  16687. };
  16688. // Loading screen
  16689. /**
  16690. * Display the loading screen
  16691. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16692. */
  16693. Engine.prototype.displayLoadingUI = function () {
  16694. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16695. return;
  16696. }
  16697. var loadingScreen = this.loadingScreen;
  16698. if (loadingScreen) {
  16699. loadingScreen.displayLoadingUI();
  16700. }
  16701. };
  16702. /**
  16703. * Hide the loading screen
  16704. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16705. */
  16706. Engine.prototype.hideLoadingUI = function () {
  16707. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16708. return;
  16709. }
  16710. var loadingScreen = this.loadingScreen;
  16711. if (loadingScreen) {
  16712. loadingScreen.hideLoadingUI();
  16713. }
  16714. };
  16715. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16716. /**
  16717. * Gets the current loading screen object
  16718. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16719. */
  16720. get: function () {
  16721. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16722. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16723. return this._loadingScreen;
  16724. },
  16725. /**
  16726. * Sets the current loading screen object
  16727. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16728. */
  16729. set: function (loadingScreen) {
  16730. this._loadingScreen = loadingScreen;
  16731. },
  16732. enumerable: true,
  16733. configurable: true
  16734. });
  16735. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16736. /**
  16737. * Sets the current loading screen text
  16738. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16739. */
  16740. set: function (text) {
  16741. this.loadingScreen.loadingUIText = text;
  16742. },
  16743. enumerable: true,
  16744. configurable: true
  16745. });
  16746. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16747. /**
  16748. * Sets the current loading screen background color
  16749. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16750. */
  16751. set: function (color) {
  16752. this.loadingScreen.loadingUIBackgroundColor = color;
  16753. },
  16754. enumerable: true,
  16755. configurable: true
  16756. });
  16757. /**
  16758. * Attach a new callback raised when context lost event is fired
  16759. * @param callback defines the callback to call
  16760. */
  16761. Engine.prototype.attachContextLostEvent = function (callback) {
  16762. if (this._renderingCanvas) {
  16763. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16764. }
  16765. };
  16766. /**
  16767. * Attach a new callback raised when context restored event is fired
  16768. * @param callback defines the callback to call
  16769. */
  16770. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16771. if (this._renderingCanvas) {
  16772. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16773. }
  16774. };
  16775. /**
  16776. * Gets the source code of the vertex shader associated with a specific webGL program
  16777. * @param program defines the program to use
  16778. * @returns a string containing the source code of the vertex shader associated with the program
  16779. */
  16780. Engine.prototype.getVertexShaderSource = function (program) {
  16781. var shaders = this._gl.getAttachedShaders(program);
  16782. if (!shaders) {
  16783. return null;
  16784. }
  16785. return this._gl.getShaderSource(shaders[0]);
  16786. };
  16787. /**
  16788. * Gets the source code of the fragment shader associated with a specific webGL program
  16789. * @param program defines the program to use
  16790. * @returns a string containing the source code of the fragment shader associated with the program
  16791. */
  16792. Engine.prototype.getFragmentShaderSource = function (program) {
  16793. var shaders = this._gl.getAttachedShaders(program);
  16794. if (!shaders) {
  16795. return null;
  16796. }
  16797. return this._gl.getShaderSource(shaders[1]);
  16798. };
  16799. /**
  16800. * Get the current error code of the webGL context
  16801. * @returns the error code
  16802. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16803. */
  16804. Engine.prototype.getError = function () {
  16805. return this._gl.getError();
  16806. };
  16807. // FPS
  16808. /**
  16809. * Gets the current framerate
  16810. * @returns a number representing the framerate
  16811. */
  16812. Engine.prototype.getFps = function () {
  16813. return this._fps;
  16814. };
  16815. /**
  16816. * Gets the time spent between current and previous frame
  16817. * @returns a number representing the delta time in ms
  16818. */
  16819. Engine.prototype.getDeltaTime = function () {
  16820. return this._deltaTime;
  16821. };
  16822. Engine.prototype._measureFps = function () {
  16823. this._performanceMonitor.sampleFrame();
  16824. this._fps = this._performanceMonitor.averageFPS;
  16825. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16826. };
  16827. /** @hidden */
  16828. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16829. if (faceIndex === void 0) { faceIndex = -1; }
  16830. if (level === void 0) { level = 0; }
  16831. var gl = this._gl;
  16832. if (!this._dummyFramebuffer) {
  16833. var dummy = gl.createFramebuffer();
  16834. if (!dummy) {
  16835. throw new Error("Unable to create dummy framebuffer");
  16836. }
  16837. this._dummyFramebuffer = dummy;
  16838. }
  16839. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16840. if (faceIndex > -1) {
  16841. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16842. }
  16843. else {
  16844. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16845. }
  16846. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16847. var buffer;
  16848. switch (readType) {
  16849. case gl.UNSIGNED_BYTE:
  16850. buffer = new Uint8Array(4 * width * height);
  16851. readType = gl.UNSIGNED_BYTE;
  16852. break;
  16853. default:
  16854. buffer = new Float32Array(4 * width * height);
  16855. readType = gl.FLOAT;
  16856. break;
  16857. }
  16858. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16859. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16860. return buffer;
  16861. };
  16862. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16863. if (this._webGLVersion > 1) {
  16864. return this._caps.colorBufferFloat;
  16865. }
  16866. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16867. };
  16868. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16869. if (this._webGLVersion > 1) {
  16870. return this._caps.colorBufferFloat;
  16871. }
  16872. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16873. };
  16874. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16875. Engine.prototype._canRenderToFramebuffer = function (type) {
  16876. var gl = this._gl;
  16877. //clear existing errors
  16878. while (gl.getError() !== gl.NO_ERROR) { }
  16879. var successful = true;
  16880. var texture = gl.createTexture();
  16881. gl.bindTexture(gl.TEXTURE_2D, texture);
  16882. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16885. var fb = gl.createFramebuffer();
  16886. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16887. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16888. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16889. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16890. successful = successful && (gl.getError() === gl.NO_ERROR);
  16891. //try render by clearing frame buffer's color buffer
  16892. if (successful) {
  16893. gl.clear(gl.COLOR_BUFFER_BIT);
  16894. successful = successful && (gl.getError() === gl.NO_ERROR);
  16895. }
  16896. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16897. if (successful) {
  16898. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16899. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16900. var readFormat = gl.RGBA;
  16901. var readType = gl.UNSIGNED_BYTE;
  16902. var buffer = new Uint8Array(4);
  16903. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16904. successful = successful && (gl.getError() === gl.NO_ERROR);
  16905. }
  16906. //clean up
  16907. gl.deleteTexture(texture);
  16908. gl.deleteFramebuffer(fb);
  16909. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16910. //clear accumulated errors
  16911. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16912. return successful;
  16913. };
  16914. /** @hidden */
  16915. Engine.prototype._getWebGLTextureType = function (type) {
  16916. if (this._webGLVersion === 1) {
  16917. switch (type) {
  16918. case Engine.TEXTURETYPE_FLOAT:
  16919. return this._gl.FLOAT;
  16920. case Engine.TEXTURETYPE_HALF_FLOAT:
  16921. return this._gl.HALF_FLOAT_OES;
  16922. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16923. return this._gl.UNSIGNED_BYTE;
  16924. }
  16925. return this._gl.UNSIGNED_BYTE;
  16926. }
  16927. switch (type) {
  16928. case Engine.TEXTURETYPE_BYTE:
  16929. return this._gl.BYTE;
  16930. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16931. return this._gl.UNSIGNED_BYTE;
  16932. case Engine.TEXTURETYPE_SHORT:
  16933. return this._gl.SHORT;
  16934. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16935. return this._gl.UNSIGNED_SHORT;
  16936. case Engine.TEXTURETYPE_INT:
  16937. return this._gl.INT;
  16938. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16939. return this._gl.UNSIGNED_INT;
  16940. case Engine.TEXTURETYPE_FLOAT:
  16941. return this._gl.FLOAT;
  16942. case Engine.TEXTURETYPE_HALF_FLOAT:
  16943. return this._gl.HALF_FLOAT;
  16944. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16945. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16946. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16947. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16948. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16949. return this._gl.UNSIGNED_SHORT_5_6_5;
  16950. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16951. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16952. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16953. return this._gl.UNSIGNED_INT_24_8;
  16954. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16955. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16956. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16957. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16958. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16959. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16960. }
  16961. return this._gl.UNSIGNED_BYTE;
  16962. };
  16963. ;
  16964. Engine.prototype._getInternalFormat = function (format) {
  16965. var internalFormat = this._gl.RGBA;
  16966. switch (format) {
  16967. case Engine.TEXTUREFORMAT_ALPHA:
  16968. internalFormat = this._gl.ALPHA;
  16969. break;
  16970. case Engine.TEXTUREFORMAT_LUMINANCE:
  16971. internalFormat = this._gl.LUMINANCE;
  16972. break;
  16973. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16974. internalFormat = this._gl.LUMINANCE_ALPHA;
  16975. break;
  16976. case Engine.TEXTUREFORMAT_RED:
  16977. internalFormat = this._gl.RED;
  16978. break;
  16979. case Engine.TEXTUREFORMAT_RG:
  16980. internalFormat = this._gl.RG;
  16981. break;
  16982. case Engine.TEXTUREFORMAT_RGB:
  16983. internalFormat = this._gl.RGB;
  16984. break;
  16985. case Engine.TEXTUREFORMAT_RGBA:
  16986. internalFormat = this._gl.RGBA;
  16987. break;
  16988. }
  16989. if (this._webGLVersion > 1) {
  16990. switch (format) {
  16991. case Engine.TEXTUREFORMAT_RED_INTEGER:
  16992. internalFormat = this._gl.RED_INTEGER;
  16993. break;
  16994. case Engine.TEXTUREFORMAT_RG_INTEGER:
  16995. internalFormat = this._gl.RG_INTEGER;
  16996. break;
  16997. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  16998. internalFormat = this._gl.RGB_INTEGER;
  16999. break;
  17000. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17001. internalFormat = this._gl.RGBA_INTEGER;
  17002. break;
  17003. }
  17004. }
  17005. return internalFormat;
  17006. };
  17007. /** @hidden */
  17008. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17009. if (this._webGLVersion === 1) {
  17010. if (format !== undefined) {
  17011. switch (format) {
  17012. case Engine.TEXTUREFORMAT_ALPHA:
  17013. return this._gl.ALPHA;
  17014. case Engine.TEXTUREFORMAT_LUMINANCE:
  17015. return this._gl.LUMINANCE;
  17016. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17017. return this._gl.LUMINANCE_ALPHA;
  17018. }
  17019. }
  17020. return this._gl.RGBA;
  17021. }
  17022. switch (type) {
  17023. case Engine.TEXTURETYPE_BYTE:
  17024. switch (format) {
  17025. case Engine.TEXTUREFORMAT_RED:
  17026. return this._gl.R8_SNORM;
  17027. case Engine.TEXTUREFORMAT_RG:
  17028. return this._gl.RG8_SNORM;
  17029. case Engine.TEXTUREFORMAT_RGB:
  17030. return this._gl.RGB8_SNORM;
  17031. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17032. return this._gl.R8I;
  17033. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17034. return this._gl.RG8I;
  17035. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17036. return this._gl.RGB8I;
  17037. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17038. return this._gl.RGBA8I;
  17039. default:
  17040. return this._gl.RGBA8_SNORM;
  17041. }
  17042. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17043. switch (format) {
  17044. case Engine.TEXTUREFORMAT_RED:
  17045. return this._gl.R8;
  17046. case Engine.TEXTUREFORMAT_RG:
  17047. return this._gl.RG8;
  17048. case Engine.TEXTUREFORMAT_RGB:
  17049. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17050. case Engine.TEXTUREFORMAT_RGBA:
  17051. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17052. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17053. return this._gl.R8UI;
  17054. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17055. return this._gl.RG8UI;
  17056. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17057. return this._gl.RGB8UI;
  17058. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17059. return this._gl.RGBA8UI;
  17060. default:
  17061. return this._gl.RGBA8;
  17062. }
  17063. case Engine.TEXTURETYPE_SHORT:
  17064. switch (format) {
  17065. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17066. return this._gl.R16I;
  17067. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17068. return this._gl.RG16I;
  17069. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17070. return this._gl.RGB16I;
  17071. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17072. return this._gl.RGBA16I;
  17073. default:
  17074. return this._gl.RGBA16I;
  17075. }
  17076. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17077. switch (format) {
  17078. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17079. return this._gl.R16UI;
  17080. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17081. return this._gl.RG16UI;
  17082. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17083. return this._gl.RGB16UI;
  17084. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17085. return this._gl.RGBA16UI;
  17086. default:
  17087. return this._gl.RGBA16UI;
  17088. }
  17089. case Engine.TEXTURETYPE_INT:
  17090. switch (format) {
  17091. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17092. return this._gl.R32I;
  17093. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17094. return this._gl.RG32I;
  17095. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17096. return this._gl.RGB32I;
  17097. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17098. return this._gl.RGBA32I;
  17099. default:
  17100. return this._gl.RGBA32I;
  17101. }
  17102. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17103. switch (format) {
  17104. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17105. return this._gl.R32UI;
  17106. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17107. return this._gl.RG32UI;
  17108. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17109. return this._gl.RGB32UI;
  17110. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17111. return this._gl.RGBA32UI;
  17112. default:
  17113. return this._gl.RGBA32UI;
  17114. }
  17115. case Engine.TEXTURETYPE_FLOAT:
  17116. switch (format) {
  17117. case Engine.TEXTUREFORMAT_RED:
  17118. return this._gl.R32F; // By default. Other possibility is R16F.
  17119. case Engine.TEXTUREFORMAT_RG:
  17120. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17121. case Engine.TEXTUREFORMAT_RGB:
  17122. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17123. case Engine.TEXTUREFORMAT_RGBA:
  17124. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17125. default:
  17126. return this._gl.RGBA32F;
  17127. }
  17128. case Engine.TEXTURETYPE_HALF_FLOAT:
  17129. switch (format) {
  17130. case Engine.TEXTUREFORMAT_RED:
  17131. return this._gl.R16F;
  17132. case Engine.TEXTUREFORMAT_RG:
  17133. return this._gl.RG16F;
  17134. case Engine.TEXTUREFORMAT_RGB:
  17135. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17136. case Engine.TEXTUREFORMAT_RGBA:
  17137. return this._gl.RGBA16F;
  17138. default:
  17139. return this._gl.RGBA16F;
  17140. }
  17141. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17142. return this._gl.RGB565;
  17143. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17144. return this._gl.R11F_G11F_B10F;
  17145. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17146. return this._gl.RGB9_E5;
  17147. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17148. return this._gl.RGBA4;
  17149. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17150. return this._gl.RGB5_A1;
  17151. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17152. switch (format) {
  17153. case Engine.TEXTUREFORMAT_RGBA:
  17154. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17155. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17156. return this._gl.RGB10_A2UI;
  17157. default:
  17158. return this._gl.RGB10_A2;
  17159. }
  17160. }
  17161. return this._gl.RGBA8;
  17162. };
  17163. ;
  17164. /** @hidden */
  17165. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17166. if (type === Engine.TEXTURETYPE_FLOAT) {
  17167. return this._gl.RGBA32F;
  17168. }
  17169. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17170. return this._gl.RGBA16F;
  17171. }
  17172. return this._gl.RGBA8;
  17173. };
  17174. ;
  17175. /** @hidden */
  17176. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17177. var _this = this;
  17178. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17179. this._activeRequests.push(request);
  17180. request.onCompleteObservable.add(function (request) {
  17181. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17182. });
  17183. return request;
  17184. };
  17185. /** @hidden */
  17186. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17187. var _this = this;
  17188. return new Promise(function (resolve, reject) {
  17189. _this._loadFile(url, function (data) {
  17190. resolve(data);
  17191. }, undefined, database, useArrayBuffer, function (request, exception) {
  17192. reject(exception);
  17193. });
  17194. });
  17195. };
  17196. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17197. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17198. var onload = function (data) {
  17199. loadedFiles[index] = data;
  17200. loadedFiles._internalCount++;
  17201. if (loadedFiles._internalCount === 6) {
  17202. onfinish(loadedFiles);
  17203. }
  17204. };
  17205. var onerror = function (request, exception) {
  17206. if (onErrorCallBack && request) {
  17207. onErrorCallBack(request.status + " " + request.statusText, exception);
  17208. }
  17209. };
  17210. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17211. };
  17212. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17213. if (onError === void 0) { onError = null; }
  17214. var loadedFiles = [];
  17215. loadedFiles._internalCount = 0;
  17216. for (var index = 0; index < 6; index++) {
  17217. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17218. }
  17219. };
  17220. // Statics
  17221. /**
  17222. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17223. * @returns true if the engine can be created
  17224. * @ignorenaming
  17225. */
  17226. Engine.isSupported = function () {
  17227. try {
  17228. var tempcanvas = document.createElement("canvas");
  17229. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17230. return gl != null && !!window.WebGLRenderingContext;
  17231. }
  17232. catch (e) {
  17233. return false;
  17234. }
  17235. };
  17236. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17237. Engine.ExceptionList = [
  17238. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17239. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17240. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17241. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17242. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17243. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17244. ];
  17245. /** Gets the list of created engines */
  17246. Engine.Instances = new Array();
  17247. /**
  17248. * Hidden
  17249. */
  17250. Engine._TextureLoaders = [];
  17251. // Const statics
  17252. /** Defines that alpha blending is disabled */
  17253. Engine.ALPHA_DISABLE = 0;
  17254. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17255. Engine.ALPHA_ADD = 1;
  17256. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17257. Engine.ALPHA_COMBINE = 2;
  17258. /** Defines that alpha blending to DEST - SRC * DEST */
  17259. Engine.ALPHA_SUBTRACT = 3;
  17260. /** Defines that alpha blending to SRC * DEST */
  17261. Engine.ALPHA_MULTIPLY = 4;
  17262. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17263. Engine.ALPHA_MAXIMIZED = 5;
  17264. /** Defines that alpha blending to SRC + DEST */
  17265. Engine.ALPHA_ONEONE = 6;
  17266. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17267. Engine.ALPHA_PREMULTIPLIED = 7;
  17268. /**
  17269. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17270. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17271. */
  17272. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17273. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17274. Engine.ALPHA_INTERPOLATE = 9;
  17275. /**
  17276. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17277. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17278. */
  17279. Engine.ALPHA_SCREENMODE = 10;
  17280. /** Defines that the ressource is not delayed*/
  17281. Engine.DELAYLOADSTATE_NONE = 0;
  17282. /** Defines that the ressource was successfully delay loaded */
  17283. Engine.DELAYLOADSTATE_LOADED = 1;
  17284. /** Defines that the ressource is currently delay loading */
  17285. Engine.DELAYLOADSTATE_LOADING = 2;
  17286. /** Defines that the ressource is delayed and has not started loading */
  17287. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17288. // Depht or Stencil test Constants.
  17289. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17290. Engine.NEVER = 0x0200;
  17291. /** 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 */
  17292. Engine.ALWAYS = 0x0207;
  17293. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17294. Engine.LESS = 0x0201;
  17295. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17296. Engine.EQUAL = 0x0202;
  17297. /** 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 */
  17298. Engine.LEQUAL = 0x0203;
  17299. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17300. Engine.GREATER = 0x0204;
  17301. /** 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 */
  17302. Engine.GEQUAL = 0x0206;
  17303. /** 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 */
  17304. Engine.NOTEQUAL = 0x0205;
  17305. // Stencil Actions Constants.
  17306. /** Passed to stencilOperation to specify that stencil value must be kept */
  17307. Engine.KEEP = 0x1E00;
  17308. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17309. Engine.REPLACE = 0x1E01;
  17310. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17311. Engine.INCR = 0x1E02;
  17312. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17313. Engine.DECR = 0x1E03;
  17314. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17315. Engine.INVERT = 0x150A;
  17316. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17317. Engine.INCR_WRAP = 0x8507;
  17318. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17319. Engine.DECR_WRAP = 0x8508;
  17320. /** Texture is not repeating outside of 0..1 UVs */
  17321. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17322. /** Texture is repeating outside of 0..1 UVs */
  17323. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17324. /** Texture is repeating and mirrored */
  17325. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17326. /** ALPHA */
  17327. Engine.TEXTUREFORMAT_ALPHA = 0;
  17328. /** LUMINANCE */
  17329. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17330. /** LUMINANCE_ALPHA */
  17331. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17332. /** RGB */
  17333. Engine.TEXTUREFORMAT_RGB = 4;
  17334. /** RGBA */
  17335. Engine.TEXTUREFORMAT_RGBA = 5;
  17336. /** RED */
  17337. Engine.TEXTUREFORMAT_RED = 6;
  17338. /** RED (2nd reference) */
  17339. Engine.TEXTUREFORMAT_R = 6;
  17340. /** RG */
  17341. Engine.TEXTUREFORMAT_RG = 7;
  17342. /** RED_INTEGER */
  17343. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17344. /** RED_INTEGER (2nd reference) */
  17345. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17346. /** RG_INTEGER */
  17347. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17348. /** RGB_INTEGER */
  17349. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17350. /** RGBA_INTEGER */
  17351. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17352. /** UNSIGNED_BYTE */
  17353. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17354. /** UNSIGNED_BYTE (2nd reference) */
  17355. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17356. /** FLOAT */
  17357. Engine.TEXTURETYPE_FLOAT = 1;
  17358. /** HALF_FLOAT */
  17359. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17360. /** BYTE */
  17361. Engine.TEXTURETYPE_BYTE = 3;
  17362. /** SHORT */
  17363. Engine.TEXTURETYPE_SHORT = 4;
  17364. /** UNSIGNED_SHORT */
  17365. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17366. /** INT */
  17367. Engine.TEXTURETYPE_INT = 6;
  17368. /** UNSIGNED_INT */
  17369. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17370. /** UNSIGNED_SHORT_4_4_4_4 */
  17371. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17372. /** UNSIGNED_SHORT_5_5_5_1 */
  17373. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17374. /** UNSIGNED_SHORT_5_6_5 */
  17375. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17376. /** UNSIGNED_INT_2_10_10_10_REV */
  17377. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17378. /** UNSIGNED_INT_24_8 */
  17379. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17380. /** UNSIGNED_INT_10F_11F_11F_REV */
  17381. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17382. /** UNSIGNED_INT_5_9_9_9_REV */
  17383. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17384. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17385. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17386. /** nearest is mag = nearest and min = nearest and mip = linear */
  17387. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17388. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17389. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17390. /** Trilinear is mag = linear and min = linear and mip = linear */
  17391. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17392. /** nearest is mag = nearest and min = nearest and mip = linear */
  17393. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17394. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17395. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17396. /** Trilinear is mag = linear and min = linear and mip = linear */
  17397. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17398. /** mag = nearest and min = nearest and mip = nearest */
  17399. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17400. /** mag = nearest and min = linear and mip = nearest */
  17401. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17402. /** mag = nearest and min = linear and mip = linear */
  17403. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17404. /** mag = nearest and min = linear and mip = none */
  17405. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17406. /** mag = nearest and min = nearest and mip = none */
  17407. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17408. /** mag = linear and min = nearest and mip = nearest */
  17409. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17410. /** mag = linear and min = nearest and mip = linear */
  17411. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17412. /** mag = linear and min = linear and mip = none */
  17413. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17414. /** mag = linear and min = nearest and mip = none */
  17415. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17416. /** Explicit coordinates mode */
  17417. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17418. /** Spherical coordinates mode */
  17419. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17420. /** Planar coordinates mode */
  17421. Engine.TEXTURE_PLANAR_MODE = 2;
  17422. /** Cubic coordinates mode */
  17423. Engine.TEXTURE_CUBIC_MODE = 3;
  17424. /** Projection coordinates mode */
  17425. Engine.TEXTURE_PROJECTION_MODE = 4;
  17426. /** Skybox coordinates mode */
  17427. Engine.TEXTURE_SKYBOX_MODE = 5;
  17428. /** Inverse Cubic coordinates mode */
  17429. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17430. /** Equirectangular coordinates mode */
  17431. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17432. /** Equirectangular Fixed coordinates mode */
  17433. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17434. /** Equirectangular Fixed Mirrored coordinates mode */
  17435. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17436. // Texture rescaling mode
  17437. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17438. Engine.SCALEMODE_FLOOR = 1;
  17439. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17440. Engine.SCALEMODE_NEAREST = 2;
  17441. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17442. Engine.SCALEMODE_CEILING = 3;
  17443. // Updatable statics so stick with vars here
  17444. /**
  17445. * Gets or sets the epsilon value used by collision engine
  17446. */
  17447. Engine.CollisionsEpsilon = 0.001;
  17448. /**
  17449. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17450. */
  17451. Engine.CodeRepository = "src/";
  17452. /**
  17453. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17454. */
  17455. Engine.ShadersRepository = "src/Shaders/";
  17456. return Engine;
  17457. }());
  17458. BABYLON.Engine = Engine;
  17459. })(BABYLON || (BABYLON = {}));
  17460. //# sourceMappingURL=babylon.engine.js.map
  17461. var BABYLON;
  17462. (function (BABYLON) {
  17463. /**
  17464. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17465. */
  17466. var Node = /** @class */ (function () {
  17467. /**
  17468. * Creates a new Node
  17469. * @param {string} name - the name and id to be given to this node
  17470. * @param {BABYLON.Scene} the scene this node will be added to
  17471. */
  17472. function Node(name, scene) {
  17473. if (scene === void 0) { scene = null; }
  17474. /**
  17475. * Gets or sets a string used to store user defined state for the node
  17476. */
  17477. this.state = "";
  17478. /**
  17479. * Gets or sets an object used to store user defined information for the node
  17480. */
  17481. this.metadata = null;
  17482. /**
  17483. * Gets or sets a boolean used to define if the node must be serialized
  17484. */
  17485. this.doNotSerialize = false;
  17486. /** @hidden */
  17487. this._isDisposed = false;
  17488. /**
  17489. * Gets a list of Animations associated with the node
  17490. */
  17491. this.animations = new Array();
  17492. this._ranges = {};
  17493. this._isEnabled = true;
  17494. this._isReady = true;
  17495. /** @hidden */
  17496. this._currentRenderId = -1;
  17497. this._parentRenderId = -1;
  17498. this._childRenderId = -1;
  17499. this._animationPropertiesOverride = null;
  17500. /**
  17501. * An event triggered when the mesh is disposed
  17502. */
  17503. this.onDisposeObservable = new BABYLON.Observable();
  17504. // Behaviors
  17505. this._behaviors = new Array();
  17506. this.name = name;
  17507. this.id = name;
  17508. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17509. this.uniqueId = this._scene.getUniqueId();
  17510. this._initCache();
  17511. }
  17512. /**
  17513. * Add a new node constructor
  17514. * @param type defines the type name of the node to construct
  17515. * @param constructorFunc defines the constructor function
  17516. */
  17517. Node.AddNodeConstructor = function (type, constructorFunc) {
  17518. this._NodeConstructors[type] = constructorFunc;
  17519. };
  17520. /**
  17521. * Returns a node constructor based on type name
  17522. * @param type defines the type name
  17523. * @param name defines the new node name
  17524. * @param scene defines the hosting scene
  17525. * @param options defines optional options to transmit to constructors
  17526. * @returns the new constructor or null
  17527. */
  17528. Node.Construct = function (type, name, scene, options) {
  17529. var constructorFunc = this._NodeConstructors[type];
  17530. if (!constructorFunc) {
  17531. return null;
  17532. }
  17533. return constructorFunc(name, scene, options);
  17534. };
  17535. /**
  17536. * Gets a boolean indicating if the node has been disposed
  17537. * @returns true if the node was disposed
  17538. */
  17539. Node.prototype.isDisposed = function () {
  17540. return this._isDisposed;
  17541. };
  17542. Object.defineProperty(Node.prototype, "parent", {
  17543. get: function () {
  17544. return this._parentNode;
  17545. },
  17546. /**
  17547. * Gets or sets the parent of the node
  17548. */
  17549. set: function (parent) {
  17550. if (this._parentNode === parent) {
  17551. return;
  17552. }
  17553. // Remove self from list of children of parent
  17554. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17555. var index = this._parentNode._children.indexOf(this);
  17556. if (index !== -1) {
  17557. this._parentNode._children.splice(index, 1);
  17558. }
  17559. }
  17560. // Store new parent
  17561. this._parentNode = parent;
  17562. // Add as child to new parent
  17563. if (this._parentNode) {
  17564. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17565. this._parentNode._children = new Array();
  17566. }
  17567. this._parentNode._children.push(this);
  17568. }
  17569. },
  17570. enumerable: true,
  17571. configurable: true
  17572. });
  17573. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17574. /**
  17575. * Gets or sets the animation properties override
  17576. */
  17577. get: function () {
  17578. if (!this._animationPropertiesOverride) {
  17579. return this._scene.animationPropertiesOverride;
  17580. }
  17581. return this._animationPropertiesOverride;
  17582. },
  17583. set: function (value) {
  17584. this._animationPropertiesOverride = value;
  17585. },
  17586. enumerable: true,
  17587. configurable: true
  17588. });
  17589. /**
  17590. * Gets a string idenfifying the name of the class
  17591. * @returns "Node" string
  17592. */
  17593. Node.prototype.getClassName = function () {
  17594. return "Node";
  17595. };
  17596. Object.defineProperty(Node.prototype, "onDispose", {
  17597. /**
  17598. * Sets a callback that will be raised when the node will be disposed
  17599. */
  17600. set: function (callback) {
  17601. if (this._onDisposeObserver) {
  17602. this.onDisposeObservable.remove(this._onDisposeObserver);
  17603. }
  17604. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. /**
  17610. * Gets the scene of the node
  17611. * @returns a {BABYLON.Scene}
  17612. */
  17613. Node.prototype.getScene = function () {
  17614. return this._scene;
  17615. };
  17616. /**
  17617. * Gets the engine of the node
  17618. * @returns a {BABYLON.Engine}
  17619. */
  17620. Node.prototype.getEngine = function () {
  17621. return this._scene.getEngine();
  17622. };
  17623. /**
  17624. * Attach a behavior to the node
  17625. * @see http://doc.babylonjs.com/features/behaviour
  17626. * @param behavior defines the behavior to attach
  17627. * @returns the current Node
  17628. */
  17629. Node.prototype.addBehavior = function (behavior) {
  17630. var _this = this;
  17631. var index = this._behaviors.indexOf(behavior);
  17632. if (index !== -1) {
  17633. return this;
  17634. }
  17635. behavior.init();
  17636. if (this._scene.isLoading) {
  17637. // We defer the attach when the scene will be loaded
  17638. this._scene.onDataLoadedObservable.addOnce(function () {
  17639. behavior.attach(_this);
  17640. });
  17641. }
  17642. else {
  17643. behavior.attach(this);
  17644. }
  17645. this._behaviors.push(behavior);
  17646. return this;
  17647. };
  17648. /**
  17649. * Remove an attached behavior
  17650. * @see http://doc.babylonjs.com/features/behaviour
  17651. * @param behavior defines the behavior to attach
  17652. * @returns the current Node
  17653. */
  17654. Node.prototype.removeBehavior = function (behavior) {
  17655. var index = this._behaviors.indexOf(behavior);
  17656. if (index === -1) {
  17657. return this;
  17658. }
  17659. this._behaviors[index].detach();
  17660. this._behaviors.splice(index, 1);
  17661. return this;
  17662. };
  17663. Object.defineProperty(Node.prototype, "behaviors", {
  17664. /**
  17665. * Gets the list of attached behaviors
  17666. * @see http://doc.babylonjs.com/features/behaviour
  17667. */
  17668. get: function () {
  17669. return this._behaviors;
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. /**
  17675. * Gets an attached behavior by name
  17676. * @param name defines the name of the behavior to look for
  17677. * @see http://doc.babylonjs.com/features/behaviour
  17678. * @returns null if behavior was not found else the requested behavior
  17679. */
  17680. Node.prototype.getBehaviorByName = function (name) {
  17681. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17682. var behavior = _a[_i];
  17683. if (behavior.name === name) {
  17684. return behavior;
  17685. }
  17686. }
  17687. return null;
  17688. };
  17689. /**
  17690. * Returns the world matrix of the node
  17691. * @returns a matrix containing the node's world matrix
  17692. */
  17693. Node.prototype.getWorldMatrix = function () {
  17694. return BABYLON.Matrix.Identity();
  17695. };
  17696. /** @hidden */
  17697. Node.prototype._getWorldMatrixDeterminant = function () {
  17698. return 1;
  17699. };
  17700. // override it in derived class if you add new variables to the cache
  17701. // and call the parent class method
  17702. /** @hidden */
  17703. Node.prototype._initCache = function () {
  17704. this._cache = {};
  17705. this._cache.parent = undefined;
  17706. };
  17707. /** @hidden */
  17708. Node.prototype.updateCache = function (force) {
  17709. if (!force && this.isSynchronized())
  17710. return;
  17711. this._cache.parent = this.parent;
  17712. this._updateCache();
  17713. };
  17714. // override it in derived class if you add new variables to the cache
  17715. // and call the parent class method if !ignoreParentClass
  17716. /** @hidden */
  17717. Node.prototype._updateCache = function (ignoreParentClass) {
  17718. };
  17719. // override it in derived class if you add new variables to the cache
  17720. /** @hidden */
  17721. Node.prototype._isSynchronized = function () {
  17722. return true;
  17723. };
  17724. /** @hidden */
  17725. Node.prototype._markSyncedWithParent = function () {
  17726. if (this.parent) {
  17727. this._parentRenderId = this.parent._childRenderId;
  17728. }
  17729. };
  17730. /** @hidden */
  17731. Node.prototype.isSynchronizedWithParent = function () {
  17732. if (!this.parent) {
  17733. return true;
  17734. }
  17735. if (this._parentRenderId !== this.parent._childRenderId) {
  17736. return false;
  17737. }
  17738. return this.parent.isSynchronized();
  17739. };
  17740. /** @hidden */
  17741. Node.prototype.isSynchronized = function (updateCache) {
  17742. var check = this.hasNewParent();
  17743. check = check || !this.isSynchronizedWithParent();
  17744. check = check || !this._isSynchronized();
  17745. if (updateCache)
  17746. this.updateCache(true);
  17747. return !check;
  17748. };
  17749. /** @hidden */
  17750. Node.prototype.hasNewParent = function (update) {
  17751. if (this._cache.parent === this.parent)
  17752. return false;
  17753. if (update)
  17754. this._cache.parent = this.parent;
  17755. return true;
  17756. };
  17757. /**
  17758. * Is this node ready to be used/rendered
  17759. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17760. * @return true if the node is ready
  17761. */
  17762. Node.prototype.isReady = function (completeCheck) {
  17763. if (completeCheck === void 0) { completeCheck = false; }
  17764. return this._isReady;
  17765. };
  17766. /**
  17767. * Is this node enabled?
  17768. * 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
  17769. * @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
  17770. * @return whether this node (and its parent) is enabled
  17771. */
  17772. Node.prototype.isEnabled = function (checkAncestors) {
  17773. if (checkAncestors === void 0) { checkAncestors = true; }
  17774. if (checkAncestors === false) {
  17775. return this._isEnabled;
  17776. }
  17777. if (this._isEnabled === false) {
  17778. return false;
  17779. }
  17780. if (this.parent !== undefined && this.parent !== null) {
  17781. return this.parent.isEnabled(checkAncestors);
  17782. }
  17783. return true;
  17784. };
  17785. /**
  17786. * Set the enabled state of this node
  17787. * @param value defines the new enabled state
  17788. */
  17789. Node.prototype.setEnabled = function (value) {
  17790. this._isEnabled = value;
  17791. };
  17792. /**
  17793. * Is this node a descendant of the given node?
  17794. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17795. * @param ancestor defines the parent node to inspect
  17796. * @returns a boolean indicating if this node is a descendant of the given node
  17797. */
  17798. Node.prototype.isDescendantOf = function (ancestor) {
  17799. if (this.parent) {
  17800. if (this.parent === ancestor) {
  17801. return true;
  17802. }
  17803. return this.parent.isDescendantOf(ancestor);
  17804. }
  17805. return false;
  17806. };
  17807. /** @hidden */
  17808. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17809. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17810. if (!this._children) {
  17811. return;
  17812. }
  17813. for (var index = 0; index < this._children.length; index++) {
  17814. var item = this._children[index];
  17815. if (!predicate || predicate(item)) {
  17816. results.push(item);
  17817. }
  17818. if (!directDescendantsOnly) {
  17819. item._getDescendants(results, false, predicate);
  17820. }
  17821. }
  17822. };
  17823. /**
  17824. * Will return all nodes that have this node as ascendant
  17825. * @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
  17826. * @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
  17827. * @return all children nodes of all types
  17828. */
  17829. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17830. var results = new Array();
  17831. this._getDescendants(results, directDescendantsOnly, predicate);
  17832. return results;
  17833. };
  17834. /**
  17835. * Get all child-meshes of this node
  17836. * @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
  17837. * @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
  17838. * @returns an array of {BABYLON.AbstractMesh}
  17839. */
  17840. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17841. var results = [];
  17842. this._getDescendants(results, directDescendantsOnly, function (node) {
  17843. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17844. });
  17845. return results;
  17846. };
  17847. /**
  17848. * Get all child-transformNodes of this node
  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. * @returns an array of {BABYLON.TransformNode}
  17852. */
  17853. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17854. var results = [];
  17855. this._getDescendants(results, directDescendantsOnly, function (node) {
  17856. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17857. });
  17858. return results;
  17859. };
  17860. /**
  17861. * Get all direct children of this node
  17862. * @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
  17863. * @returns an array of {BABYLON.Node}
  17864. */
  17865. Node.prototype.getChildren = function (predicate) {
  17866. return this.getDescendants(true, predicate);
  17867. };
  17868. /** @hidden */
  17869. Node.prototype._setReady = function (state) {
  17870. if (state === this._isReady) {
  17871. return;
  17872. }
  17873. if (!state) {
  17874. this._isReady = false;
  17875. return;
  17876. }
  17877. if (this.onReady) {
  17878. this.onReady(this);
  17879. }
  17880. this._isReady = true;
  17881. };
  17882. /**
  17883. * Get an animation by name
  17884. * @param name defines the name of the animation to look for
  17885. * @returns null if not found else the requested animation
  17886. */
  17887. Node.prototype.getAnimationByName = function (name) {
  17888. for (var i = 0; i < this.animations.length; i++) {
  17889. var animation = this.animations[i];
  17890. if (animation.name === name) {
  17891. return animation;
  17892. }
  17893. }
  17894. return null;
  17895. };
  17896. /**
  17897. * Creates an animation range for this node
  17898. * @param name defines the name of the range
  17899. * @param from defines the starting key
  17900. * @param to defines the end key
  17901. */
  17902. Node.prototype.createAnimationRange = function (name, from, to) {
  17903. // check name not already in use
  17904. if (!this._ranges[name]) {
  17905. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17906. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17907. if (this.animations[i]) {
  17908. this.animations[i].createRange(name, from, to);
  17909. }
  17910. }
  17911. }
  17912. };
  17913. /**
  17914. * Delete a specific animation range
  17915. * @param name defines the name of the range to delete
  17916. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17917. */
  17918. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17919. if (deleteFrames === void 0) { deleteFrames = true; }
  17920. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17921. if (this.animations[i]) {
  17922. this.animations[i].deleteRange(name, deleteFrames);
  17923. }
  17924. }
  17925. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17926. };
  17927. /**
  17928. * Get an animation range by name
  17929. * @param name defines the name of the animation range to look for
  17930. * @returns null if not found else the requested animation range
  17931. */
  17932. Node.prototype.getAnimationRange = function (name) {
  17933. return this._ranges[name];
  17934. };
  17935. /**
  17936. * Will start the animation sequence
  17937. * @param name defines the range frames for animation sequence
  17938. * @param loop defines if the animation should loop (false by default)
  17939. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17940. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17941. * @returns the object created for this animation. If range does not exist, it will return null
  17942. */
  17943. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17944. var range = this.getAnimationRange(name);
  17945. if (!range) {
  17946. return null;
  17947. }
  17948. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17949. };
  17950. /**
  17951. * Serialize animation ranges into a JSON compatible object
  17952. * @returns serialization object
  17953. */
  17954. Node.prototype.serializeAnimationRanges = function () {
  17955. var serializationRanges = [];
  17956. for (var name in this._ranges) {
  17957. var localRange = this._ranges[name];
  17958. if (!localRange) {
  17959. continue;
  17960. }
  17961. var range = {};
  17962. range.name = name;
  17963. range.from = localRange.from;
  17964. range.to = localRange.to;
  17965. serializationRanges.push(range);
  17966. }
  17967. return serializationRanges;
  17968. };
  17969. /**
  17970. * Computes the world matrix of the node
  17971. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17972. * @returns the world matrix
  17973. */
  17974. Node.prototype.computeWorldMatrix = function (force) {
  17975. return BABYLON.Matrix.Identity();
  17976. };
  17977. /**
  17978. * Releases resources associated with this node.
  17979. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17980. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17981. */
  17982. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17983. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17984. if (!doNotRecurse) {
  17985. var nodes = this.getDescendants(true);
  17986. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17987. var node = nodes_1[_i];
  17988. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17989. }
  17990. }
  17991. else {
  17992. var transformNodes = this.getChildTransformNodes(true);
  17993. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17994. var transformNode = transformNodes_1[_a];
  17995. transformNode.parent = null;
  17996. transformNode.computeWorldMatrix(true);
  17997. }
  17998. }
  17999. this.parent = null;
  18000. // Callback
  18001. this.onDisposeObservable.notifyObservers(this);
  18002. this.onDisposeObservable.clear();
  18003. // Behaviors
  18004. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18005. var behavior = _c[_b];
  18006. behavior.detach();
  18007. }
  18008. this._behaviors = [];
  18009. this._isDisposed = true;
  18010. };
  18011. /**
  18012. * Parse animation range data from a serialization object and store them into a given node
  18013. * @param node defines where to store the animation ranges
  18014. * @param parsedNode defines the serialization object to read data from
  18015. * @param scene defines the hosting scene
  18016. */
  18017. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18018. if (parsedNode.ranges) {
  18019. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18020. var data = parsedNode.ranges[index];
  18021. node.createAnimationRange(data.name, data.from, data.to);
  18022. }
  18023. }
  18024. };
  18025. Node._NodeConstructors = {};
  18026. __decorate([
  18027. BABYLON.serialize()
  18028. ], Node.prototype, "name", void 0);
  18029. __decorate([
  18030. BABYLON.serialize()
  18031. ], Node.prototype, "id", void 0);
  18032. __decorate([
  18033. BABYLON.serialize()
  18034. ], Node.prototype, "uniqueId", void 0);
  18035. __decorate([
  18036. BABYLON.serialize()
  18037. ], Node.prototype, "state", void 0);
  18038. __decorate([
  18039. BABYLON.serialize()
  18040. ], Node.prototype, "metadata", void 0);
  18041. return Node;
  18042. }());
  18043. BABYLON.Node = Node;
  18044. })(BABYLON || (BABYLON = {}));
  18045. //# sourceMappingURL=babylon.node.js.map
  18046. var BABYLON;
  18047. (function (BABYLON) {
  18048. // This matrix is used as a value to reset the bounding box.
  18049. var _identityMatrix = BABYLON.Matrix.Identity();
  18050. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18051. var BoundingSphere = /** @class */ (function () {
  18052. /**
  18053. * Creates a new bounding sphere
  18054. * @param min defines the minimum vector (in local space)
  18055. * @param max defines the maximum vector (in local space)
  18056. */
  18057. function BoundingSphere(min, max) {
  18058. this.center = BABYLON.Vector3.Zero();
  18059. this.centerWorld = BABYLON.Vector3.Zero();
  18060. this.reConstruct(min, max);
  18061. }
  18062. /**
  18063. * Recreates the entire bounding sphere from scratch
  18064. * @param min defines the new minimum vector (in local space)
  18065. * @param max defines the new maximum vector (in local space)
  18066. */
  18067. BoundingSphere.prototype.reConstruct = function (min, max) {
  18068. this.minimum = min.clone();
  18069. this.maximum = max.clone();
  18070. var distance = BABYLON.Vector3.Distance(min, max);
  18071. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18072. this.radius = distance * 0.5;
  18073. this.centerWorld.set(0, 0, 0);
  18074. this._update(_identityMatrix);
  18075. };
  18076. /**
  18077. * Scale the current bounding sphere by applying a scale factor
  18078. * @param factor defines the scale factor to apply
  18079. * @returns the current bounding box
  18080. */
  18081. BoundingSphere.prototype.scale = function (factor) {
  18082. var newRadius = this.radius * factor;
  18083. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18084. var min = this.center.subtract(_tempRadiusVector);
  18085. var max = this.center.add(_tempRadiusVector);
  18086. this.reConstruct(min, max);
  18087. return this;
  18088. };
  18089. // Methods
  18090. /** @hidden */
  18091. BoundingSphere.prototype._update = function (world) {
  18092. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18093. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18094. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18095. };
  18096. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18097. for (var i = 0; i < 6; i++) {
  18098. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18099. return false;
  18100. }
  18101. return true;
  18102. };
  18103. BoundingSphere.prototype.intersectsPoint = function (point) {
  18104. var x = this.centerWorld.x - point.x;
  18105. var y = this.centerWorld.y - point.y;
  18106. var z = this.centerWorld.z - point.z;
  18107. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18108. if (this.radiusWorld < distance)
  18109. return false;
  18110. return true;
  18111. };
  18112. // Statics
  18113. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18114. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18115. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18116. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18117. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18118. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18119. return false;
  18120. return true;
  18121. };
  18122. return BoundingSphere;
  18123. }());
  18124. BABYLON.BoundingSphere = BoundingSphere;
  18125. })(BABYLON || (BABYLON = {}));
  18126. //# sourceMappingURL=babylon.boundingSphere.js.map
  18127. var BABYLON;
  18128. (function (BABYLON) {
  18129. var BoundingBox = /** @class */ (function () {
  18130. /**
  18131. * Creates a new bounding box
  18132. * @param min defines the minimum vector (in local space)
  18133. * @param max defines the maximum vector (in local space)
  18134. */
  18135. function BoundingBox(min, max) {
  18136. this.vectorsWorld = new Array();
  18137. this.reConstruct(min, max);
  18138. }
  18139. // Methods
  18140. /**
  18141. * Recreates the entire bounding box from scratch
  18142. * @param min defines the new minimum vector (in local space)
  18143. * @param max defines the new maximum vector (in local space)
  18144. */
  18145. BoundingBox.prototype.reConstruct = function (min, max) {
  18146. this.minimum = min.clone();
  18147. this.maximum = max.clone();
  18148. // Bounding vectors
  18149. this.vectors = [
  18150. this.minimum.clone(),
  18151. this.maximum.clone(),
  18152. this.minimum.clone(),
  18153. this.minimum.clone(),
  18154. this.minimum.clone(),
  18155. this.maximum.clone(),
  18156. this.maximum.clone(),
  18157. this.maximum.clone()
  18158. ];
  18159. this.vectors[2].x = this.maximum.x;
  18160. this.vectors[3].y = this.maximum.y;
  18161. this.vectors[4].z = this.maximum.z;
  18162. this.vectors[5].z = this.minimum.z;
  18163. this.vectors[6].x = this.minimum.x;
  18164. this.vectors[7].y = this.minimum.y;
  18165. // OBB
  18166. this.center = this.maximum.add(this.minimum).scale(0.5);
  18167. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18168. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18169. // World
  18170. for (var index = 0; index < this.vectors.length; index++) {
  18171. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18172. }
  18173. this.minimumWorld = BABYLON.Vector3.Zero();
  18174. this.maximumWorld = BABYLON.Vector3.Zero();
  18175. this.centerWorld = BABYLON.Vector3.Zero();
  18176. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18177. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18178. };
  18179. /**
  18180. * Scale the current bounding box by applying a scale factor
  18181. * @param factor defines the scale factor to apply
  18182. * @returns the current bounding box
  18183. */
  18184. BoundingBox.prototype.scale = function (factor) {
  18185. var diff = this.maximum.subtract(this.minimum);
  18186. var distance = diff.length() * factor;
  18187. diff.normalize();
  18188. var newRadius = diff.scale(distance / 2);
  18189. var min = this.center.subtract(newRadius);
  18190. var max = this.center.add(newRadius);
  18191. this.reConstruct(min, max);
  18192. return this;
  18193. };
  18194. BoundingBox.prototype.getWorldMatrix = function () {
  18195. return this._worldMatrix;
  18196. };
  18197. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18198. this._worldMatrix.copyFrom(matrix);
  18199. return this;
  18200. };
  18201. /** @hidden */
  18202. BoundingBox.prototype._update = function (world) {
  18203. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18204. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18205. for (var index = 0; index < this.vectors.length; index++) {
  18206. var v = this.vectorsWorld[index];
  18207. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18208. if (v.x < this.minimumWorld.x)
  18209. this.minimumWorld.x = v.x;
  18210. if (v.y < this.minimumWorld.y)
  18211. this.minimumWorld.y = v.y;
  18212. if (v.z < this.minimumWorld.z)
  18213. this.minimumWorld.z = v.z;
  18214. if (v.x > this.maximumWorld.x)
  18215. this.maximumWorld.x = v.x;
  18216. if (v.y > this.maximumWorld.y)
  18217. this.maximumWorld.y = v.y;
  18218. if (v.z > this.maximumWorld.z)
  18219. this.maximumWorld.z = v.z;
  18220. }
  18221. // Extend
  18222. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18223. this.extendSizeWorld.scaleInPlace(0.5);
  18224. // OBB
  18225. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18226. this.centerWorld.scaleInPlace(0.5);
  18227. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18228. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18229. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18230. this._worldMatrix = world;
  18231. };
  18232. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18233. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18234. };
  18235. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18236. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18237. };
  18238. BoundingBox.prototype.intersectsPoint = function (point) {
  18239. var delta = -BABYLON.Epsilon;
  18240. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18241. return false;
  18242. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18243. return false;
  18244. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18245. return false;
  18246. return true;
  18247. };
  18248. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18249. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18250. };
  18251. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18252. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18253. return false;
  18254. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18255. return false;
  18256. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18257. return false;
  18258. return true;
  18259. };
  18260. // Statics
  18261. BoundingBox.Intersects = function (box0, box1) {
  18262. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18263. return false;
  18264. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18265. return false;
  18266. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18267. return false;
  18268. return true;
  18269. };
  18270. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18271. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18272. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18273. return (num <= (sphereRadius * sphereRadius));
  18274. };
  18275. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18276. for (var p = 0; p < 6; p++) {
  18277. for (var i = 0; i < 8; i++) {
  18278. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18279. return false;
  18280. }
  18281. }
  18282. }
  18283. return true;
  18284. };
  18285. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18286. for (var p = 0; p < 6; p++) {
  18287. var inCount = 8;
  18288. for (var i = 0; i < 8; i++) {
  18289. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18290. --inCount;
  18291. }
  18292. else {
  18293. break;
  18294. }
  18295. }
  18296. if (inCount === 0)
  18297. return false;
  18298. }
  18299. return true;
  18300. };
  18301. return BoundingBox;
  18302. }());
  18303. BABYLON.BoundingBox = BoundingBox;
  18304. })(BABYLON || (BABYLON = {}));
  18305. //# sourceMappingURL=babylon.boundingBox.js.map
  18306. var BABYLON;
  18307. (function (BABYLON) {
  18308. var computeBoxExtents = function (axis, box) {
  18309. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18310. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18311. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18312. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18313. var r = r0 + r1 + r2;
  18314. return {
  18315. min: p - r,
  18316. max: p + r
  18317. };
  18318. };
  18319. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18320. var axisOverlap = function (axis, box0, box1) {
  18321. var result0 = computeBoxExtents(axis, box0);
  18322. var result1 = computeBoxExtents(axis, box1);
  18323. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18324. };
  18325. var BoundingInfo = /** @class */ (function () {
  18326. function BoundingInfo(minimum, maximum) {
  18327. this.minimum = minimum;
  18328. this.maximum = maximum;
  18329. this._isLocked = false;
  18330. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18331. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18332. }
  18333. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18334. get: function () {
  18335. return this._isLocked;
  18336. },
  18337. set: function (value) {
  18338. this._isLocked = value;
  18339. },
  18340. enumerable: true,
  18341. configurable: true
  18342. });
  18343. // Methods
  18344. BoundingInfo.prototype.update = function (world) {
  18345. if (this._isLocked) {
  18346. return;
  18347. }
  18348. this.boundingBox._update(world);
  18349. this.boundingSphere._update(world);
  18350. };
  18351. /**
  18352. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18353. * @param center New center of the bounding info
  18354. * @param extend New extend of the bounding info
  18355. */
  18356. BoundingInfo.prototype.centerOn = function (center, extend) {
  18357. this.minimum = center.subtract(extend);
  18358. this.maximum = center.add(extend);
  18359. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18360. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18361. return this;
  18362. };
  18363. /**
  18364. * Scale the current bounding info by applying a scale factor
  18365. * @param factor defines the scale factor to apply
  18366. * @returns the current bounding info
  18367. */
  18368. BoundingInfo.prototype.scale = function (factor) {
  18369. this.boundingBox.scale(factor);
  18370. this.boundingSphere.scale(factor);
  18371. return this;
  18372. };
  18373. /**
  18374. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18375. * @param frustumPlanes defines the frustum to test
  18376. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18377. * @returns true if the bounding info is in the frustum planes
  18378. */
  18379. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18380. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18381. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18382. return false;
  18383. }
  18384. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18385. return true;
  18386. }
  18387. return this.boundingBox.isInFrustum(frustumPlanes);
  18388. };
  18389. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18390. /**
  18391. * Gets the world distance between the min and max points of the bounding box
  18392. */
  18393. get: function () {
  18394. var boundingBox = this.boundingBox;
  18395. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18396. return size.length();
  18397. },
  18398. enumerable: true,
  18399. configurable: true
  18400. });
  18401. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18402. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18403. };
  18404. /** @hidden */
  18405. BoundingInfo.prototype._checkCollision = function (collider) {
  18406. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18407. };
  18408. BoundingInfo.prototype.intersectsPoint = function (point) {
  18409. if (!this.boundingSphere.centerWorld) {
  18410. return false;
  18411. }
  18412. if (!this.boundingSphere.intersectsPoint(point)) {
  18413. return false;
  18414. }
  18415. if (!this.boundingBox.intersectsPoint(point)) {
  18416. return false;
  18417. }
  18418. return true;
  18419. };
  18420. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18421. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18422. return false;
  18423. }
  18424. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18425. return false;
  18426. }
  18427. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18428. return false;
  18429. }
  18430. if (!precise) {
  18431. return true;
  18432. }
  18433. var box0 = this.boundingBox;
  18434. var box1 = boundingInfo.boundingBox;
  18435. if (!axisOverlap(box0.directions[0], box0, box1))
  18436. return false;
  18437. if (!axisOverlap(box0.directions[1], box0, box1))
  18438. return false;
  18439. if (!axisOverlap(box0.directions[2], box0, box1))
  18440. return false;
  18441. if (!axisOverlap(box1.directions[0], box0, box1))
  18442. return false;
  18443. if (!axisOverlap(box1.directions[1], box0, box1))
  18444. return false;
  18445. if (!axisOverlap(box1.directions[2], box0, box1))
  18446. return false;
  18447. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18448. return false;
  18449. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18450. return false;
  18451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18452. return false;
  18453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18454. return false;
  18455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18456. return false;
  18457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18458. return false;
  18459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18460. return false;
  18461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18462. return false;
  18463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18464. return false;
  18465. return true;
  18466. };
  18467. return BoundingInfo;
  18468. }());
  18469. BABYLON.BoundingInfo = BoundingInfo;
  18470. })(BABYLON || (BABYLON = {}));
  18471. //# sourceMappingURL=babylon.boundingInfo.js.map
  18472. var BABYLON;
  18473. (function (BABYLON) {
  18474. var TransformNode = /** @class */ (function (_super) {
  18475. __extends(TransformNode, _super);
  18476. function TransformNode(name, scene, isPure) {
  18477. if (scene === void 0) { scene = null; }
  18478. if (isPure === void 0) { isPure = true; }
  18479. var _this = _super.call(this, name, scene) || this;
  18480. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18481. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18482. _this._up = new BABYLON.Vector3(0, 1, 0);
  18483. _this._right = new BABYLON.Vector3(1, 0, 0);
  18484. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18485. // Properties
  18486. _this._rotation = BABYLON.Vector3.Zero();
  18487. _this._scaling = BABYLON.Vector3.One();
  18488. _this._isDirty = false;
  18489. /**
  18490. * Set the billboard mode. Default is 0.
  18491. *
  18492. * | Value | Type | Description |
  18493. * | --- | --- | --- |
  18494. * | 0 | BILLBOARDMODE_NONE | |
  18495. * | 1 | BILLBOARDMODE_X | |
  18496. * | 2 | BILLBOARDMODE_Y | |
  18497. * | 4 | BILLBOARDMODE_Z | |
  18498. * | 7 | BILLBOARDMODE_ALL | |
  18499. *
  18500. */
  18501. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18502. _this.scalingDeterminant = 1;
  18503. _this.infiniteDistance = false;
  18504. /**
  18505. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18506. * By default the system will update normals to compensate
  18507. */
  18508. _this.ignoreNonUniformScaling = false;
  18509. _this.position = BABYLON.Vector3.Zero();
  18510. _this._localWorld = BABYLON.Matrix.Zero();
  18511. /** @hidden */
  18512. _this._worldMatrix = BABYLON.Matrix.Zero();
  18513. /** @hidden */
  18514. _this._worldMatrixDeterminant = 0;
  18515. _this._absolutePosition = BABYLON.Vector3.Zero();
  18516. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18517. _this._postMultiplyPivotMatrix = false;
  18518. _this._isWorldMatrixFrozen = false;
  18519. /**
  18520. * An event triggered after the world matrix is updated
  18521. */
  18522. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18523. _this._nonUniformScaling = false;
  18524. if (isPure) {
  18525. _this.getScene().addTransformNode(_this);
  18526. }
  18527. return _this;
  18528. }
  18529. /**
  18530. * Gets a string identifying the name of the class
  18531. * @returns "TransformNode" string
  18532. */
  18533. TransformNode.prototype.getClassName = function () {
  18534. return "TransformNode";
  18535. };
  18536. Object.defineProperty(TransformNode.prototype, "rotation", {
  18537. /**
  18538. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18539. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18540. * Default : (0.0, 0.0, 0.0)
  18541. */
  18542. get: function () {
  18543. return this._rotation;
  18544. },
  18545. set: function (newRotation) {
  18546. this._rotation = newRotation;
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. Object.defineProperty(TransformNode.prototype, "scaling", {
  18552. /**
  18553. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18554. * Default : (1.0, 1.0, 1.0)
  18555. */
  18556. get: function () {
  18557. return this._scaling;
  18558. },
  18559. /**
  18560. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18561. * Default : (1.0, 1.0, 1.0)
  18562. */
  18563. set: function (newScaling) {
  18564. this._scaling = newScaling;
  18565. },
  18566. enumerable: true,
  18567. configurable: true
  18568. });
  18569. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18570. /**
  18571. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18572. * It's null by default.
  18573. * 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)
  18574. */
  18575. get: function () {
  18576. return this._rotationQuaternion;
  18577. },
  18578. set: function (quaternion) {
  18579. this._rotationQuaternion = quaternion;
  18580. //reset the rotation vector.
  18581. if (quaternion && this.rotation.length()) {
  18582. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18583. }
  18584. },
  18585. enumerable: true,
  18586. configurable: true
  18587. });
  18588. Object.defineProperty(TransformNode.prototype, "forward", {
  18589. /**
  18590. * The forward direction of that transform in world space.
  18591. */
  18592. get: function () {
  18593. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. Object.defineProperty(TransformNode.prototype, "up", {
  18599. /**
  18600. * The up direction of that transform in world space.
  18601. */
  18602. get: function () {
  18603. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18604. },
  18605. enumerable: true,
  18606. configurable: true
  18607. });
  18608. Object.defineProperty(TransformNode.prototype, "right", {
  18609. /**
  18610. * The right direction of that transform in world space.
  18611. */
  18612. get: function () {
  18613. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18614. },
  18615. enumerable: true,
  18616. configurable: true
  18617. });
  18618. /**
  18619. * Returns the latest update of the World matrix
  18620. * Returns a Matrix.
  18621. */
  18622. TransformNode.prototype.getWorldMatrix = function () {
  18623. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18624. this.computeWorldMatrix();
  18625. }
  18626. return this._worldMatrix;
  18627. };
  18628. /** @hidden */
  18629. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18630. return this._worldMatrixDeterminant;
  18631. };
  18632. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18633. /**
  18634. * Returns directly the latest state of the mesh World matrix.
  18635. * A Matrix is returned.
  18636. */
  18637. get: function () {
  18638. return this._worldMatrix;
  18639. },
  18640. enumerable: true,
  18641. configurable: true
  18642. });
  18643. /**
  18644. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18645. * Returns the TransformNode.
  18646. */
  18647. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18648. this._poseMatrix.copyFrom(matrix);
  18649. return this;
  18650. };
  18651. /**
  18652. * Returns the mesh Pose matrix.
  18653. * Returned object : Matrix
  18654. */
  18655. TransformNode.prototype.getPoseMatrix = function () {
  18656. return this._poseMatrix;
  18657. };
  18658. /** @hidden */
  18659. TransformNode.prototype._isSynchronized = function () {
  18660. if (this._isDirty) {
  18661. return false;
  18662. }
  18663. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18664. return false;
  18665. if (this._cache.pivotMatrixUpdated) {
  18666. return false;
  18667. }
  18668. if (this.infiniteDistance) {
  18669. return false;
  18670. }
  18671. if (!this._cache.position.equals(this.position))
  18672. return false;
  18673. if (this._rotationQuaternion) {
  18674. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18675. return false;
  18676. }
  18677. if (!this._cache.rotation.equals(this.rotation))
  18678. return false;
  18679. if (!this._cache.scaling.equals(this.scaling))
  18680. return false;
  18681. return true;
  18682. };
  18683. /** @hidden */
  18684. TransformNode.prototype._initCache = function () {
  18685. _super.prototype._initCache.call(this);
  18686. this._cache.localMatrixUpdated = false;
  18687. this._cache.position = BABYLON.Vector3.Zero();
  18688. this._cache.scaling = BABYLON.Vector3.Zero();
  18689. this._cache.rotation = BABYLON.Vector3.Zero();
  18690. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18691. this._cache.billboardMode = -1;
  18692. };
  18693. TransformNode.prototype.markAsDirty = function (property) {
  18694. if (property === "rotation") {
  18695. this.rotationQuaternion = null;
  18696. }
  18697. this._currentRenderId = Number.MAX_VALUE;
  18698. this._isDirty = true;
  18699. return this;
  18700. };
  18701. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18702. /**
  18703. * Returns the current mesh absolute position.
  18704. * Returns a Vector3.
  18705. */
  18706. get: function () {
  18707. return this._absolutePosition;
  18708. },
  18709. enumerable: true,
  18710. configurable: true
  18711. });
  18712. /**
  18713. * Sets a new matrix to apply before all other transformation
  18714. * @param matrix defines the transform matrix
  18715. * @returns the current TransformNode
  18716. */
  18717. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18718. return this.setPivotMatrix(matrix, false);
  18719. };
  18720. /**
  18721. * Sets a new pivot matrix to the current node
  18722. * @param matrix defines the new pivot matrix to use
  18723. * @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
  18724. * @returns the current TransformNode
  18725. */
  18726. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18727. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18728. this._pivotMatrix = matrix.clone();
  18729. this._cache.pivotMatrixUpdated = true;
  18730. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18731. if (this._postMultiplyPivotMatrix) {
  18732. if (!this._pivotMatrixInverse) {
  18733. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18734. }
  18735. else {
  18736. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18737. }
  18738. }
  18739. return this;
  18740. };
  18741. /**
  18742. * Returns the mesh pivot matrix.
  18743. * Default : Identity.
  18744. * A Matrix is returned.
  18745. */
  18746. TransformNode.prototype.getPivotMatrix = function () {
  18747. return this._pivotMatrix;
  18748. };
  18749. /**
  18750. * Prevents the World matrix to be computed any longer.
  18751. * Returns the TransformNode.
  18752. */
  18753. TransformNode.prototype.freezeWorldMatrix = function () {
  18754. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18755. this.computeWorldMatrix(true);
  18756. this._isWorldMatrixFrozen = true;
  18757. return this;
  18758. };
  18759. /**
  18760. * Allows back the World matrix computation.
  18761. * Returns the TransformNode.
  18762. */
  18763. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18764. this._isWorldMatrixFrozen = false;
  18765. this.computeWorldMatrix(true);
  18766. return this;
  18767. };
  18768. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18769. /**
  18770. * True if the World matrix has been frozen.
  18771. * Returns a boolean.
  18772. */
  18773. get: function () {
  18774. return this._isWorldMatrixFrozen;
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. /**
  18780. * Retuns the mesh absolute position in the World.
  18781. * Returns a Vector3.
  18782. */
  18783. TransformNode.prototype.getAbsolutePosition = function () {
  18784. this.computeWorldMatrix();
  18785. return this._absolutePosition;
  18786. };
  18787. /**
  18788. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18789. * Returns the TransformNode.
  18790. */
  18791. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18792. if (!absolutePosition) {
  18793. return this;
  18794. }
  18795. var absolutePositionX;
  18796. var absolutePositionY;
  18797. var absolutePositionZ;
  18798. if (absolutePosition.x === undefined) {
  18799. if (arguments.length < 3) {
  18800. return this;
  18801. }
  18802. absolutePositionX = arguments[0];
  18803. absolutePositionY = arguments[1];
  18804. absolutePositionZ = arguments[2];
  18805. }
  18806. else {
  18807. absolutePositionX = absolutePosition.x;
  18808. absolutePositionY = absolutePosition.y;
  18809. absolutePositionZ = absolutePosition.z;
  18810. }
  18811. if (this.parent) {
  18812. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18813. invertParentWorldMatrix.invert();
  18814. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18815. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18816. }
  18817. else {
  18818. this.position.x = absolutePositionX;
  18819. this.position.y = absolutePositionY;
  18820. this.position.z = absolutePositionZ;
  18821. }
  18822. return this;
  18823. };
  18824. /**
  18825. * Sets the mesh position in its local space.
  18826. * Returns the TransformNode.
  18827. */
  18828. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18829. this.computeWorldMatrix();
  18830. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18831. return this;
  18832. };
  18833. /**
  18834. * Returns the mesh position in the local space from the current World matrix values.
  18835. * Returns a new Vector3.
  18836. */
  18837. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18838. this.computeWorldMatrix();
  18839. var invLocalWorldMatrix = this._localWorld.clone();
  18840. invLocalWorldMatrix.invert();
  18841. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18842. };
  18843. /**
  18844. * Translates the mesh along the passed Vector3 in its local space.
  18845. * Returns the TransformNode.
  18846. */
  18847. TransformNode.prototype.locallyTranslate = function (vector3) {
  18848. this.computeWorldMatrix(true);
  18849. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18850. return this;
  18851. };
  18852. /**
  18853. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18854. * @param targetPoint the position (must be in same space as current mesh) to look at
  18855. * @param yawCor optional yaw (y-axis) correction in radians
  18856. * @param pitchCor optional pitch (x-axis) correction in radians
  18857. * @param rollCor optional roll (z-axis) correction in radians
  18858. * @param space the choosen space of the target
  18859. * @returns the TransformNode.
  18860. */
  18861. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18862. if (yawCor === void 0) { yawCor = 0; }
  18863. if (pitchCor === void 0) { pitchCor = 0; }
  18864. if (rollCor === void 0) { rollCor = 0; }
  18865. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18866. var dv = TransformNode._lookAtVectorCache;
  18867. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18868. targetPoint.subtractToRef(pos, dv);
  18869. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18870. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18871. var pitch = Math.atan2(dv.y, len);
  18872. if (this.rotationQuaternion) {
  18873. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18874. }
  18875. else {
  18876. this.rotation.x = pitch + pitchCor;
  18877. this.rotation.y = yaw + yawCor;
  18878. this.rotation.z = rollCor;
  18879. }
  18880. return this;
  18881. };
  18882. /**
  18883. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18884. * This Vector3 is expressed in the World space.
  18885. */
  18886. TransformNode.prototype.getDirection = function (localAxis) {
  18887. var result = BABYLON.Vector3.Zero();
  18888. this.getDirectionToRef(localAxis, result);
  18889. return result;
  18890. };
  18891. /**
  18892. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18893. * localAxis is expressed in the mesh local space.
  18894. * result is computed in the Wordl space from the mesh World matrix.
  18895. * Returns the TransformNode.
  18896. */
  18897. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18898. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18899. return this;
  18900. };
  18901. /**
  18902. * Sets a new pivot point to the current node
  18903. * @param point defines the new pivot point to use
  18904. * @param space defines if the point is in world or local space (local by default)
  18905. * @returns the current TransformNode
  18906. */
  18907. TransformNode.prototype.setPivotPoint = function (point, space) {
  18908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18909. if (this.getScene().getRenderId() == 0) {
  18910. this.computeWorldMatrix(true);
  18911. }
  18912. var wm = this.getWorldMatrix();
  18913. if (space == BABYLON.Space.WORLD) {
  18914. var tmat = BABYLON.Tmp.Matrix[0];
  18915. wm.invertToRef(tmat);
  18916. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18917. }
  18918. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18919. };
  18920. /**
  18921. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18922. */
  18923. TransformNode.prototype.getPivotPoint = function () {
  18924. var point = BABYLON.Vector3.Zero();
  18925. this.getPivotPointToRef(point);
  18926. return point;
  18927. };
  18928. /**
  18929. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.getPivotPointToRef = function (result) {
  18933. result.x = -this._pivotMatrix.m[12];
  18934. result.y = -this._pivotMatrix.m[13];
  18935. result.z = -this._pivotMatrix.m[14];
  18936. return this;
  18937. };
  18938. /**
  18939. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18940. */
  18941. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18942. var point = BABYLON.Vector3.Zero();
  18943. this.getAbsolutePivotPointToRef(point);
  18944. return point;
  18945. };
  18946. /**
  18947. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18948. * Returns the TransformNode.
  18949. */
  18950. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18951. result.x = this._pivotMatrix.m[12];
  18952. result.y = this._pivotMatrix.m[13];
  18953. result.z = this._pivotMatrix.m[14];
  18954. this.getPivotPointToRef(result);
  18955. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18956. return this;
  18957. };
  18958. /**
  18959. * Defines the passed node as the parent of the current node.
  18960. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18961. * Returns the TransformNode.
  18962. */
  18963. TransformNode.prototype.setParent = function (node) {
  18964. if (!node && !this.parent) {
  18965. return this;
  18966. }
  18967. if (!node) {
  18968. var rotation = BABYLON.Tmp.Quaternion[0];
  18969. var position = BABYLON.Tmp.Vector3[0];
  18970. var scale = BABYLON.Tmp.Vector3[1];
  18971. if (this.parent && this.parent.computeWorldMatrix) {
  18972. this.parent.computeWorldMatrix(true);
  18973. }
  18974. this.computeWorldMatrix(true);
  18975. this.getWorldMatrix().decompose(scale, rotation, position);
  18976. if (this.rotationQuaternion) {
  18977. this.rotationQuaternion.copyFrom(rotation);
  18978. }
  18979. else {
  18980. rotation.toEulerAnglesToRef(this.rotation);
  18981. }
  18982. this.scaling.x = scale.x;
  18983. this.scaling.y = scale.y;
  18984. this.scaling.z = scale.z;
  18985. this.position.x = position.x;
  18986. this.position.y = position.y;
  18987. this.position.z = position.z;
  18988. }
  18989. else {
  18990. var rotation = BABYLON.Tmp.Quaternion[0];
  18991. var position = BABYLON.Tmp.Vector3[0];
  18992. var scale = BABYLON.Tmp.Vector3[1];
  18993. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18994. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18995. this.computeWorldMatrix(true);
  18996. node.computeWorldMatrix(true);
  18997. node.getWorldMatrix().invertToRef(invParentMatrix);
  18998. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18999. diffMatrix.decompose(scale, rotation, position);
  19000. if (this.rotationQuaternion) {
  19001. this.rotationQuaternion.copyFrom(rotation);
  19002. }
  19003. else {
  19004. rotation.toEulerAnglesToRef(this.rotation);
  19005. }
  19006. this.position.x = position.x;
  19007. this.position.y = position.y;
  19008. this.position.z = position.z;
  19009. this.scaling.x = scale.x;
  19010. this.scaling.y = scale.y;
  19011. this.scaling.z = scale.z;
  19012. }
  19013. this.parent = node;
  19014. return this;
  19015. };
  19016. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19017. get: function () {
  19018. return this._nonUniformScaling;
  19019. },
  19020. enumerable: true,
  19021. configurable: true
  19022. });
  19023. /** @hidden */
  19024. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19025. if (this._nonUniformScaling === value) {
  19026. return false;
  19027. }
  19028. this._nonUniformScaling = value;
  19029. return true;
  19030. };
  19031. /**
  19032. * Attach the current TransformNode to another TransformNode associated with a bone
  19033. * @param bone Bone affecting the TransformNode
  19034. * @param affectedTransformNode TransformNode associated with the bone
  19035. */
  19036. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19037. this._transformToBoneReferal = affectedTransformNode;
  19038. this.parent = bone;
  19039. if (bone.getWorldMatrix().determinant() < 0) {
  19040. this.scalingDeterminant *= -1;
  19041. }
  19042. return this;
  19043. };
  19044. TransformNode.prototype.detachFromBone = function () {
  19045. if (!this.parent) {
  19046. return this;
  19047. }
  19048. if (this.parent.getWorldMatrix().determinant() < 0) {
  19049. this.scalingDeterminant *= -1;
  19050. }
  19051. this._transformToBoneReferal = null;
  19052. this.parent = null;
  19053. return this;
  19054. };
  19055. /**
  19056. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19057. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19058. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19059. * The passed axis is also normalized.
  19060. * Returns the TransformNode.
  19061. */
  19062. TransformNode.prototype.rotate = function (axis, amount, space) {
  19063. axis.normalize();
  19064. if (!this.rotationQuaternion) {
  19065. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19066. this.rotation = BABYLON.Vector3.Zero();
  19067. }
  19068. var rotationQuaternion;
  19069. if (!space || space === BABYLON.Space.LOCAL) {
  19070. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19071. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19072. }
  19073. else {
  19074. if (this.parent) {
  19075. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19076. invertParentWorldMatrix.invert();
  19077. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19078. }
  19079. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19080. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19081. }
  19082. return this;
  19083. };
  19084. /**
  19085. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19086. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19087. * The passed axis is also normalized.
  19088. * Returns the TransformNode.
  19089. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19090. */
  19091. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19092. axis.normalize();
  19093. if (!this.rotationQuaternion) {
  19094. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19095. this.rotation.copyFromFloats(0, 0, 0);
  19096. }
  19097. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19098. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19099. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19100. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19101. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19102. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19103. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19104. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19105. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19106. return this;
  19107. };
  19108. /**
  19109. * Translates the mesh along the axis vector for the passed distance in the given space.
  19110. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19111. * Returns the TransformNode.
  19112. */
  19113. TransformNode.prototype.translate = function (axis, distance, space) {
  19114. var displacementVector = axis.scale(distance);
  19115. if (!space || space === BABYLON.Space.LOCAL) {
  19116. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19117. this.setPositionWithLocalVector(tempV3);
  19118. }
  19119. else {
  19120. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19121. }
  19122. return this;
  19123. };
  19124. /**
  19125. * Adds a rotation step to the mesh current rotation.
  19126. * x, y, z are Euler angles expressed in radians.
  19127. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19128. * This means this rotation is made in the mesh local space only.
  19129. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19130. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19131. * ```javascript
  19132. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19133. * ```
  19134. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19135. * 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.
  19136. * Returns the TransformNode.
  19137. */
  19138. TransformNode.prototype.addRotation = function (x, y, z) {
  19139. var rotationQuaternion;
  19140. if (this.rotationQuaternion) {
  19141. rotationQuaternion = this.rotationQuaternion;
  19142. }
  19143. else {
  19144. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19145. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19146. }
  19147. var accumulation = BABYLON.Tmp.Quaternion[0];
  19148. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19149. rotationQuaternion.multiplyInPlace(accumulation);
  19150. if (!this.rotationQuaternion) {
  19151. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19152. }
  19153. return this;
  19154. };
  19155. /**
  19156. * Computes the mesh World matrix and returns it.
  19157. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19158. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19159. * If the parameter `force`is set to `true`, the actual computation is done.
  19160. * Returns the mesh World Matrix.
  19161. */
  19162. TransformNode.prototype.computeWorldMatrix = function (force) {
  19163. if (this._isWorldMatrixFrozen) {
  19164. return this._worldMatrix;
  19165. }
  19166. if (!force && this.isSynchronized(true)) {
  19167. this._currentRenderId = this.getScene().getRenderId();
  19168. return this._worldMatrix;
  19169. }
  19170. this._cache.position.copyFrom(this.position);
  19171. this._cache.scaling.copyFrom(this.scaling);
  19172. this._cache.pivotMatrixUpdated = false;
  19173. this._cache.billboardMode = this.billboardMode;
  19174. this._currentRenderId = this.getScene().getRenderId();
  19175. this._childRenderId = this.getScene().getRenderId();
  19176. this._isDirty = false;
  19177. // Scaling
  19178. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19179. // Rotation
  19180. //rotate, if quaternion is set and rotation was used
  19181. if (this.rotationQuaternion) {
  19182. var len = this.rotation.length();
  19183. if (len) {
  19184. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19185. this.rotation.copyFromFloats(0, 0, 0);
  19186. }
  19187. }
  19188. if (this.rotationQuaternion) {
  19189. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19190. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19191. }
  19192. else {
  19193. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19194. this._cache.rotation.copyFrom(this.rotation);
  19195. }
  19196. // Translation
  19197. var camera = this.getScene().activeCamera;
  19198. if (this.infiniteDistance && !this.parent && camera) {
  19199. var cameraWorldMatrix = camera.getWorldMatrix();
  19200. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19201. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19202. }
  19203. else {
  19204. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19205. }
  19206. // Composing transformations
  19207. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19208. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19209. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19210. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19211. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19212. // Need to decompose each rotation here
  19213. var currentPosition = BABYLON.Tmp.Vector3[3];
  19214. if (this.parent && this.parent.getWorldMatrix) {
  19215. if (this._transformToBoneReferal) {
  19216. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19217. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19218. }
  19219. else {
  19220. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19221. }
  19222. }
  19223. else {
  19224. currentPosition.copyFrom(this.position);
  19225. }
  19226. currentPosition.subtractInPlace(camera.globalPosition);
  19227. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19228. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19229. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19230. }
  19231. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19232. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19233. }
  19234. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19235. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19236. }
  19237. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19238. }
  19239. else {
  19240. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19241. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19242. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19243. }
  19244. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19245. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19246. }
  19247. // Post multiply inverse of pivotMatrix
  19248. if (this._postMultiplyPivotMatrix) {
  19249. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19250. }
  19251. // Local world
  19252. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19253. // Parent
  19254. if (this.parent && this.parent.getWorldMatrix) {
  19255. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19256. if (this._transformToBoneReferal) {
  19257. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19258. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19259. }
  19260. else {
  19261. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19262. }
  19263. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19264. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19265. this._worldMatrix.copyFrom(this._localWorld);
  19266. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19267. }
  19268. else {
  19269. if (this._transformToBoneReferal) {
  19270. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19271. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19272. }
  19273. else {
  19274. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19275. }
  19276. }
  19277. this._markSyncedWithParent();
  19278. }
  19279. else {
  19280. this._worldMatrix.copyFrom(this._localWorld);
  19281. }
  19282. // Normal matrix
  19283. if (!this.ignoreNonUniformScaling) {
  19284. if (this.scaling.isNonUniform) {
  19285. this._updateNonUniformScalingState(true);
  19286. }
  19287. else if (this.parent && this.parent._nonUniformScaling) {
  19288. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19289. }
  19290. else {
  19291. this._updateNonUniformScalingState(false);
  19292. }
  19293. }
  19294. else {
  19295. this._updateNonUniformScalingState(false);
  19296. }
  19297. this._afterComputeWorldMatrix();
  19298. // Absolute position
  19299. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19300. // Callbacks
  19301. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19302. if (!this._poseMatrix) {
  19303. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19304. }
  19305. // Cache the determinant
  19306. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19307. return this._worldMatrix;
  19308. };
  19309. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19310. };
  19311. /**
  19312. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19313. * @param func: callback function to add
  19314. *
  19315. * Returns the TransformNode.
  19316. */
  19317. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19318. this.onAfterWorldMatrixUpdateObservable.add(func);
  19319. return this;
  19320. };
  19321. /**
  19322. * Removes a registered callback function.
  19323. * Returns the TransformNode.
  19324. */
  19325. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19326. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19327. return this;
  19328. };
  19329. /**
  19330. * Clone the current transform node
  19331. * Returns the new transform node
  19332. * @param name Name of the new clone
  19333. * @param newParent New parent for the clone
  19334. * @param doNotCloneChildren Do not clone children hierarchy
  19335. */
  19336. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19337. var _this = this;
  19338. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19339. result.name = name;
  19340. result.id = name;
  19341. if (newParent) {
  19342. result.parent = newParent;
  19343. }
  19344. if (!doNotCloneChildren) {
  19345. // Children
  19346. var directDescendants = this.getDescendants(true);
  19347. for (var index = 0; index < directDescendants.length; index++) {
  19348. var child = directDescendants[index];
  19349. if (child.clone) {
  19350. child.clone(name + "." + child.name, result);
  19351. }
  19352. }
  19353. }
  19354. return result;
  19355. };
  19356. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19357. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19358. serializationObject.type = this.getClassName();
  19359. // Parent
  19360. if (this.parent) {
  19361. serializationObject.parentId = this.parent.id;
  19362. }
  19363. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19364. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19365. }
  19366. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19367. serializationObject.isEnabled = this.isEnabled();
  19368. // Parent
  19369. if (this.parent) {
  19370. serializationObject.parentId = this.parent.id;
  19371. }
  19372. return serializationObject;
  19373. };
  19374. // Statics
  19375. /**
  19376. * Returns a new TransformNode object parsed from the source provided.
  19377. * The parameter `parsedMesh` is the source.
  19378. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19379. */
  19380. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19381. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19382. if (BABYLON.Tags) {
  19383. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19384. }
  19385. if (parsedTransformNode.localMatrix) {
  19386. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19387. }
  19388. else if (parsedTransformNode.pivotMatrix) {
  19389. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19390. }
  19391. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19392. // Parent
  19393. if (parsedTransformNode.parentId) {
  19394. transformNode._waitingParentId = parsedTransformNode.parentId;
  19395. }
  19396. return transformNode;
  19397. };
  19398. /**
  19399. * Releases resources associated with this transform node.
  19400. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19401. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19402. */
  19403. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19404. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19405. // Animations
  19406. this.getScene().stopAnimation(this);
  19407. // Remove from scene
  19408. this.getScene().removeTransformNode(this);
  19409. this.onAfterWorldMatrixUpdateObservable.clear();
  19410. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19411. };
  19412. // Statics
  19413. TransformNode.BILLBOARDMODE_NONE = 0;
  19414. TransformNode.BILLBOARDMODE_X = 1;
  19415. TransformNode.BILLBOARDMODE_Y = 2;
  19416. TransformNode.BILLBOARDMODE_Z = 4;
  19417. TransformNode.BILLBOARDMODE_ALL = 7;
  19418. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19419. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19420. __decorate([
  19421. BABYLON.serializeAsVector3()
  19422. ], TransformNode.prototype, "_rotation", void 0);
  19423. __decorate([
  19424. BABYLON.serializeAsQuaternion()
  19425. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19426. __decorate([
  19427. BABYLON.serializeAsVector3()
  19428. ], TransformNode.prototype, "_scaling", void 0);
  19429. __decorate([
  19430. BABYLON.serialize()
  19431. ], TransformNode.prototype, "billboardMode", void 0);
  19432. __decorate([
  19433. BABYLON.serialize()
  19434. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19435. __decorate([
  19436. BABYLON.serialize()
  19437. ], TransformNode.prototype, "infiniteDistance", void 0);
  19438. __decorate([
  19439. BABYLON.serialize()
  19440. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19441. __decorate([
  19442. BABYLON.serializeAsVector3()
  19443. ], TransformNode.prototype, "position", void 0);
  19444. return TransformNode;
  19445. }(BABYLON.Node));
  19446. BABYLON.TransformNode = TransformNode;
  19447. })(BABYLON || (BABYLON = {}));
  19448. //# sourceMappingURL=babylon.transformNode.js.map
  19449. var BABYLON;
  19450. (function (BABYLON) {
  19451. /**
  19452. * Class used to store all common mesh properties
  19453. */
  19454. var AbstractMesh = /** @class */ (function (_super) {
  19455. __extends(AbstractMesh, _super);
  19456. // Constructor
  19457. /**
  19458. * Creates a new AbstractMesh
  19459. * @param name defines the name of the mesh
  19460. * @param scene defines the hosting scene
  19461. */
  19462. function AbstractMesh(name, scene) {
  19463. if (scene === void 0) { scene = null; }
  19464. var _this = _super.call(this, name, scene, false) || this;
  19465. _this._facetNb = 0; // facet number
  19466. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19467. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19468. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19469. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19470. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19471. _this._subDiv = {
  19472. max: 1,
  19473. X: 1,
  19474. Y: 1,
  19475. Z: 1
  19476. };
  19477. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19478. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19479. /** Gets ot sets the culling strategy to use to find visible meshes */
  19480. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19481. // Events
  19482. /**
  19483. * An event triggered when this mesh collides with another one
  19484. */
  19485. _this.onCollideObservable = new BABYLON.Observable();
  19486. /**
  19487. * An event triggered when the collision's position changes
  19488. */
  19489. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19490. /**
  19491. * An event triggered when material is changed
  19492. */
  19493. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19494. // Properties
  19495. /**
  19496. * Gets or sets the orientation for POV movement & rotation
  19497. */
  19498. _this.definedFacingForward = true;
  19499. /**
  19500. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19501. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19502. * * 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.
  19503. * @see http://doc.babylonjs.com/features/occlusionquery
  19504. */
  19505. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19506. /**
  19507. * 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:
  19508. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19509. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19510. * * 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.
  19511. * @see http://doc.babylonjs.com/features/occlusionquery
  19512. */
  19513. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19514. /**
  19515. * 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.
  19516. * The default value is -1 which means don't break the query and wait till the result
  19517. * @see http://doc.babylonjs.com/features/occlusionquery
  19518. */
  19519. _this.occlusionRetryCount = -1;
  19520. /** @hidden */
  19521. _this._occlusionInternalRetryCounter = 0;
  19522. /** @hidden */
  19523. _this._isOccluded = false;
  19524. /** @hidden */
  19525. _this._isOcclusionQueryInProgress = false;
  19526. _this._visibility = 1.0;
  19527. /** Gets or sets the alpha index used to sort transparent meshes
  19528. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19529. */
  19530. _this.alphaIndex = Number.MAX_VALUE;
  19531. /**
  19532. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19533. */
  19534. _this.isVisible = true;
  19535. /**
  19536. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19537. */
  19538. _this.isPickable = true;
  19539. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19540. _this.showSubMeshesBoundingBox = false;
  19541. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19542. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19543. */
  19544. _this.isBlocker = false;
  19545. /**
  19546. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19547. */
  19548. _this.enablePointerMoveEvents = false;
  19549. /**
  19550. * Specifies the rendering group id for this mesh (0 by default)
  19551. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19552. */
  19553. _this.renderingGroupId = 0;
  19554. _this._receiveShadows = false;
  19555. /**
  19556. * Gets or sets a boolean indicating if the outline must be rendered as well
  19557. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19558. */
  19559. _this.renderOutline = false;
  19560. /** Defines color to use when rendering outline */
  19561. _this.outlineColor = BABYLON.Color3.Red();
  19562. /** Define width to use when rendering outline */
  19563. _this.outlineWidth = 0.02;
  19564. /**
  19565. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19566. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19567. */
  19568. _this.renderOverlay = false;
  19569. /** Defines color to use when rendering overlay */
  19570. _this.overlayColor = BABYLON.Color3.Red();
  19571. /** Defines alpha to use when rendering overlay */
  19572. _this.overlayAlpha = 0.5;
  19573. _this._hasVertexAlpha = false;
  19574. _this._useVertexColors = true;
  19575. _this._computeBonesUsingShaders = true;
  19576. _this._numBoneInfluencers = 4;
  19577. _this._applyFog = true;
  19578. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19579. _this.useOctreeForRenderingSelection = true;
  19580. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19581. _this.useOctreeForPicking = true;
  19582. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19583. _this.useOctreeForCollisions = true;
  19584. _this._layerMask = 0x0FFFFFFF;
  19585. /**
  19586. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19587. */
  19588. _this.alwaysSelectAsActiveMesh = false;
  19589. /**
  19590. * Gets or sets the current action manager
  19591. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19592. */
  19593. _this.actionManager = null;
  19594. /**
  19595. * Gets or sets impostor used for physic simulation
  19596. * @see http://doc.babylonjs.com/features/physics_engine
  19597. */
  19598. _this.physicsImpostor = null;
  19599. // Collisions
  19600. _this._checkCollisions = false;
  19601. _this._collisionMask = -1;
  19602. _this._collisionGroup = -1;
  19603. /**
  19604. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19605. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19606. */
  19607. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19608. /**
  19609. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19610. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19611. */
  19612. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19613. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19614. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19615. // Edges
  19616. /**
  19617. * Defines edge width used when edgesRenderer is enabled
  19618. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19619. */
  19620. _this.edgesWidth = 1;
  19621. /**
  19622. * Defines edge color used when edgesRenderer is enabled
  19623. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19624. */
  19625. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19626. // Cache
  19627. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19628. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19629. /** @hidden */
  19630. _this._renderId = 0;
  19631. /** @hidden */
  19632. _this._intersectionsInProgress = new Array();
  19633. /** @hidden */
  19634. _this._unIndexed = false;
  19635. /** @hidden */
  19636. _this._lightSources = new Array();
  19637. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19638. if (collidedMesh === void 0) { collidedMesh = null; }
  19639. //TODO move this to the collision coordinator!
  19640. if (_this.getScene().workerCollisions)
  19641. newPosition.multiplyInPlace(_this._collider._radius);
  19642. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19643. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19644. _this.position.addInPlace(_this._diffPositionForCollisions);
  19645. }
  19646. if (collidedMesh) {
  19647. _this.onCollideObservable.notifyObservers(collidedMesh);
  19648. }
  19649. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19650. };
  19651. _this.getScene().addMesh(_this);
  19652. _this._resyncLightSources();
  19653. return _this;
  19654. }
  19655. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19656. /**
  19657. * No billboard
  19658. */
  19659. get: function () {
  19660. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19666. /** Billboard on X axis */
  19667. get: function () {
  19668. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19674. /** Billboard on Y axis */
  19675. get: function () {
  19676. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19682. /** Billboard on Z axis */
  19683. get: function () {
  19684. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19690. /** Billboard on all axes */
  19691. get: function () {
  19692. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19698. /**
  19699. * Gets the number of facets in the mesh
  19700. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19701. */
  19702. get: function () {
  19703. return this._facetNb;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19709. /**
  19710. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19711. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19712. */
  19713. get: function () {
  19714. return this._partitioningSubdivisions;
  19715. },
  19716. set: function (nb) {
  19717. this._partitioningSubdivisions = nb;
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19723. /**
  19724. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19725. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19726. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19727. */
  19728. get: function () {
  19729. return this._partitioningBBoxRatio;
  19730. },
  19731. set: function (ratio) {
  19732. this._partitioningBBoxRatio = ratio;
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19738. /**
  19739. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19740. * Works only for updatable meshes.
  19741. * Doesn't work with multi-materials
  19742. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19743. */
  19744. get: function () {
  19745. return this._facetDepthSort;
  19746. },
  19747. set: function (sort) {
  19748. this._facetDepthSort = sort;
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19754. /**
  19755. * The location (Vector3) where the facet depth sort must be computed from.
  19756. * By default, the active camera position.
  19757. * Used only when facet depth sort is enabled
  19758. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19759. */
  19760. get: function () {
  19761. return this._facetDepthSortFrom;
  19762. },
  19763. set: function (location) {
  19764. this._facetDepthSortFrom = location;
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19770. /**
  19771. * gets a boolean indicating if facetData is enabled
  19772. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19773. */
  19774. get: function () {
  19775. return this._facetDataEnabled;
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. /** @hidden */
  19781. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19782. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19783. return false;
  19784. }
  19785. this._markSubMeshesAsMiscDirty();
  19786. return true;
  19787. };
  19788. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19789. /** Set a function to call when this mesh collides with another one */
  19790. set: function (callback) {
  19791. if (this._onCollideObserver) {
  19792. this.onCollideObservable.remove(this._onCollideObserver);
  19793. }
  19794. this._onCollideObserver = this.onCollideObservable.add(callback);
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19800. /** Set a function to call when the collision's position changes */
  19801. set: function (callback) {
  19802. if (this._onCollisionPositionChangeObserver) {
  19803. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19804. }
  19805. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19811. /**
  19812. * 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
  19813. * @see http://doc.babylonjs.com/features/occlusionquery
  19814. */
  19815. get: function () {
  19816. return this._isOccluded;
  19817. },
  19818. set: function (value) {
  19819. this._isOccluded = value;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19825. /**
  19826. * Flag to check the progress status of the query
  19827. * @see http://doc.babylonjs.com/features/occlusionquery
  19828. */
  19829. get: function () {
  19830. return this._isOcclusionQueryInProgress;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19836. /**
  19837. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19838. */
  19839. get: function () {
  19840. return this._visibility;
  19841. },
  19842. /**
  19843. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19844. */
  19845. set: function (value) {
  19846. if (this._visibility === value) {
  19847. return;
  19848. }
  19849. this._visibility = value;
  19850. this._markSubMeshesAsMiscDirty();
  19851. },
  19852. enumerable: true,
  19853. configurable: true
  19854. });
  19855. Object.defineProperty(AbstractMesh.prototype, "material", {
  19856. /** Gets or sets current material */
  19857. get: function () {
  19858. return this._material;
  19859. },
  19860. set: function (value) {
  19861. if (this._material === value) {
  19862. return;
  19863. }
  19864. this._material = value;
  19865. if (this.onMaterialChangedObservable.hasObservers) {
  19866. this.onMaterialChangedObservable.notifyObservers(this);
  19867. }
  19868. if (!this.subMeshes) {
  19869. return;
  19870. }
  19871. this._unBindEffect();
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19877. /**
  19878. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19879. * @see http://doc.babylonjs.com/babylon101/shadows
  19880. */
  19881. get: function () {
  19882. return this._receiveShadows;
  19883. },
  19884. set: function (value) {
  19885. if (this._receiveShadows === value) {
  19886. return;
  19887. }
  19888. this._receiveShadows = value;
  19889. this._markSubMeshesAsLightDirty();
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19895. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19896. get: function () {
  19897. return this._hasVertexAlpha;
  19898. },
  19899. set: function (value) {
  19900. if (this._hasVertexAlpha === value) {
  19901. return;
  19902. }
  19903. this._hasVertexAlpha = value;
  19904. this._markSubMeshesAsAttributesDirty();
  19905. this._markSubMeshesAsMiscDirty();
  19906. },
  19907. enumerable: true,
  19908. configurable: true
  19909. });
  19910. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19911. /** 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) */
  19912. get: function () {
  19913. return this._useVertexColors;
  19914. },
  19915. set: function (value) {
  19916. if (this._useVertexColors === value) {
  19917. return;
  19918. }
  19919. this._useVertexColors = value;
  19920. this._markSubMeshesAsAttributesDirty();
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19926. /**
  19927. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19928. */
  19929. get: function () {
  19930. return this._computeBonesUsingShaders;
  19931. },
  19932. set: function (value) {
  19933. if (this._computeBonesUsingShaders === value) {
  19934. return;
  19935. }
  19936. this._computeBonesUsingShaders = value;
  19937. this._markSubMeshesAsAttributesDirty();
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19943. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19944. get: function () {
  19945. return this._numBoneInfluencers;
  19946. },
  19947. set: function (value) {
  19948. if (this._numBoneInfluencers === value) {
  19949. return;
  19950. }
  19951. this._numBoneInfluencers = value;
  19952. this._markSubMeshesAsAttributesDirty();
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19958. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19959. get: function () {
  19960. return this._applyFog;
  19961. },
  19962. set: function (value) {
  19963. if (this._applyFog === value) {
  19964. return;
  19965. }
  19966. this._applyFog = value;
  19967. this._markSubMeshesAsMiscDirty();
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19973. /**
  19974. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19975. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19976. */
  19977. get: function () {
  19978. return this._layerMask;
  19979. },
  19980. set: function (value) {
  19981. if (value === this._layerMask) {
  19982. return;
  19983. }
  19984. this._layerMask = value;
  19985. this._resyncLightSources();
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19991. /**
  19992. * Gets or sets a collision mask used to mask collisions (default is -1).
  19993. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19994. */
  19995. get: function () {
  19996. return this._collisionMask;
  19997. },
  19998. set: function (mask) {
  19999. this._collisionMask = !isNaN(mask) ? mask : -1;
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20005. /**
  20006. * Gets or sets the current collision group mask (-1 by default).
  20007. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20008. */
  20009. get: function () {
  20010. return this._collisionGroup;
  20011. },
  20012. set: function (mask) {
  20013. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20019. /** @hidden */
  20020. get: function () {
  20021. return null;
  20022. },
  20023. enumerable: true,
  20024. configurable: true
  20025. });
  20026. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20027. get: function () {
  20028. return this._skeleton;
  20029. },
  20030. /**
  20031. * Gets or sets a skeleton to apply skining transformations
  20032. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20033. */
  20034. set: function (value) {
  20035. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20036. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20037. }
  20038. if (value && value.needInitialSkinMatrix) {
  20039. value._registerMeshWithPoseMatrix(this);
  20040. }
  20041. this._skeleton = value;
  20042. if (!this._skeleton) {
  20043. this._bonesTransformMatrices = null;
  20044. }
  20045. this._markSubMeshesAsAttributesDirty();
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. /**
  20051. * Returns the string "AbstractMesh"
  20052. * @returns "AbstractMesh"
  20053. */
  20054. AbstractMesh.prototype.getClassName = function () {
  20055. return "AbstractMesh";
  20056. };
  20057. /**
  20058. * Gets a string representation of the current mesh
  20059. * @param fullDetails defines a boolean indicating if full details must be included
  20060. * @returns a string representation of the current mesh
  20061. */
  20062. AbstractMesh.prototype.toString = function (fullDetails) {
  20063. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20064. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20065. if (this._skeleton) {
  20066. ret += ", skeleton: " + this._skeleton.name;
  20067. }
  20068. if (fullDetails) {
  20069. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20070. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20071. }
  20072. return ret;
  20073. };
  20074. /** @hidden */
  20075. AbstractMesh.prototype._rebuild = function () {
  20076. if (this._occlusionQuery) {
  20077. this._occlusionQuery = null;
  20078. }
  20079. if (this._edgesRenderer) {
  20080. this._edgesRenderer._rebuild();
  20081. }
  20082. if (!this.subMeshes) {
  20083. return;
  20084. }
  20085. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20086. var subMesh = _a[_i];
  20087. subMesh._rebuild();
  20088. }
  20089. };
  20090. /** @hidden */
  20091. AbstractMesh.prototype._resyncLightSources = function () {
  20092. this._lightSources.length = 0;
  20093. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20094. var light = _a[_i];
  20095. if (!light.isEnabled()) {
  20096. continue;
  20097. }
  20098. if (light.canAffectMesh(this)) {
  20099. this._lightSources.push(light);
  20100. }
  20101. }
  20102. this._markSubMeshesAsLightDirty();
  20103. };
  20104. /** @hidden */
  20105. AbstractMesh.prototype._resyncLighSource = function (light) {
  20106. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20107. var index = this._lightSources.indexOf(light);
  20108. if (index === -1) {
  20109. if (!isIn) {
  20110. return;
  20111. }
  20112. this._lightSources.push(light);
  20113. }
  20114. else {
  20115. if (isIn) {
  20116. return;
  20117. }
  20118. this._lightSources.splice(index, 1);
  20119. }
  20120. this._markSubMeshesAsLightDirty();
  20121. };
  20122. /** @hidden */
  20123. AbstractMesh.prototype._unBindEffect = function () {
  20124. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20125. var subMesh = _a[_i];
  20126. subMesh.setEffect(null);
  20127. }
  20128. };
  20129. /** @hidden */
  20130. AbstractMesh.prototype._removeLightSource = function (light) {
  20131. var index = this._lightSources.indexOf(light);
  20132. if (index === -1) {
  20133. return;
  20134. }
  20135. this._lightSources.splice(index, 1);
  20136. this._markSubMeshesAsLightDirty();
  20137. };
  20138. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20139. if (!this.subMeshes) {
  20140. return;
  20141. }
  20142. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20143. var subMesh = _a[_i];
  20144. if (subMesh._materialDefines) {
  20145. func(subMesh._materialDefines);
  20146. }
  20147. }
  20148. };
  20149. /** @hidden */
  20150. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20151. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20152. };
  20153. /** @hidden */
  20154. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20155. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20156. };
  20157. /** @hidden */
  20158. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20159. if (!this.subMeshes) {
  20160. return;
  20161. }
  20162. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20163. var subMesh = _a[_i];
  20164. var material = subMesh.getMaterial();
  20165. if (material) {
  20166. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20167. }
  20168. }
  20169. };
  20170. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20171. /**
  20172. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20173. */
  20174. get: function () {
  20175. return this._scaling;
  20176. },
  20177. set: function (newScaling) {
  20178. this._scaling = newScaling;
  20179. if (this.physicsImpostor) {
  20180. this.physicsImpostor.forceUpdate();
  20181. }
  20182. },
  20183. enumerable: true,
  20184. configurable: true
  20185. });
  20186. // Methods
  20187. /**
  20188. * Disables the mesh edge rendering mode
  20189. * @returns the currentAbstractMesh
  20190. */
  20191. AbstractMesh.prototype.disableEdgesRendering = function () {
  20192. if (this._edgesRenderer) {
  20193. this._edgesRenderer.dispose();
  20194. this._edgesRenderer = null;
  20195. }
  20196. return this;
  20197. };
  20198. /**
  20199. * Enables the edge rendering mode on the mesh.
  20200. * This mode makes the mesh edges visible
  20201. * @param epsilon defines the maximal distance between two angles to detect a face
  20202. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20203. * @returns the currentAbstractMesh
  20204. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20205. */
  20206. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20207. if (epsilon === void 0) { epsilon = 0.95; }
  20208. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20209. this.disableEdgesRendering();
  20210. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20211. return this;
  20212. };
  20213. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20214. /**
  20215. * Gets the edgesRenderer associated with the mesh
  20216. */
  20217. get: function () {
  20218. return this._edgesRenderer;
  20219. },
  20220. enumerable: true,
  20221. configurable: true
  20222. });
  20223. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20224. /**
  20225. * Returns true if the mesh is blocked. Implemented by child classes
  20226. */
  20227. get: function () {
  20228. return false;
  20229. },
  20230. enumerable: true,
  20231. configurable: true
  20232. });
  20233. /**
  20234. * Returns the mesh itself by default. Implemented by child classes
  20235. * @param camera defines the camera to use to pick the right LOD level
  20236. * @returns the currentAbstractMesh
  20237. */
  20238. AbstractMesh.prototype.getLOD = function (camera) {
  20239. return this;
  20240. };
  20241. /**
  20242. * Returns 0 by default. Implemented by child classes
  20243. * @returns an integer
  20244. */
  20245. AbstractMesh.prototype.getTotalVertices = function () {
  20246. return 0;
  20247. };
  20248. /**
  20249. * Returns null by default. Implemented by child classes
  20250. * @returns null
  20251. */
  20252. AbstractMesh.prototype.getIndices = function () {
  20253. return null;
  20254. };
  20255. /**
  20256. * Returns the array of the requested vertex data kind. Implemented by child classes
  20257. * @param kind defines the vertex data kind to use
  20258. * @returns null
  20259. */
  20260. AbstractMesh.prototype.getVerticesData = function (kind) {
  20261. return null;
  20262. };
  20263. /**
  20264. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20265. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20266. * Note that a new underlying VertexBuffer object is created each call.
  20267. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20268. * @param kind defines vertex data kind:
  20269. * * BABYLON.VertexBuffer.PositionKind
  20270. * * BABYLON.VertexBuffer.UVKind
  20271. * * BABYLON.VertexBuffer.UV2Kind
  20272. * * BABYLON.VertexBuffer.UV3Kind
  20273. * * BABYLON.VertexBuffer.UV4Kind
  20274. * * BABYLON.VertexBuffer.UV5Kind
  20275. * * BABYLON.VertexBuffer.UV6Kind
  20276. * * BABYLON.VertexBuffer.ColorKind
  20277. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20278. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20279. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20280. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20281. * @param data defines the data source
  20282. * @param updatable defines if the data must be flagged as updatable (or static)
  20283. * @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
  20284. * @returns the current mesh
  20285. */
  20286. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20287. return this;
  20288. };
  20289. /**
  20290. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20291. * If the mesh has no geometry, it is simply returned as it is.
  20292. * @param kind defines vertex data kind:
  20293. * * BABYLON.VertexBuffer.PositionKind
  20294. * * BABYLON.VertexBuffer.UVKind
  20295. * * BABYLON.VertexBuffer.UV2Kind
  20296. * * BABYLON.VertexBuffer.UV3Kind
  20297. * * BABYLON.VertexBuffer.UV4Kind
  20298. * * BABYLON.VertexBuffer.UV5Kind
  20299. * * BABYLON.VertexBuffer.UV6Kind
  20300. * * BABYLON.VertexBuffer.ColorKind
  20301. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20302. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20303. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20304. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20305. * @param data defines the data source
  20306. * @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
  20307. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20308. * @returns the current mesh
  20309. */
  20310. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20311. return this;
  20312. };
  20313. /**
  20314. * Sets the mesh indices,
  20315. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20316. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20317. * @param totalVertices Defines the total number of vertices
  20318. * @returns the current mesh
  20319. */
  20320. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20321. return this;
  20322. };
  20323. /**
  20324. * Gets a boolean indicating if specific vertex data is present
  20325. * @param kind defines the vertex data kind to use
  20326. * @returns true is data kind is present
  20327. */
  20328. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20329. return false;
  20330. };
  20331. /**
  20332. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20333. * @returns a BoundingInfo
  20334. */
  20335. AbstractMesh.prototype.getBoundingInfo = function () {
  20336. if (this._masterMesh) {
  20337. return this._masterMesh.getBoundingInfo();
  20338. }
  20339. if (!this._boundingInfo) {
  20340. // this._boundingInfo is being created here
  20341. this._updateBoundingInfo();
  20342. }
  20343. // cannot be null.
  20344. return this._boundingInfo;
  20345. };
  20346. /**
  20347. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20348. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20349. * @returns the current mesh
  20350. */
  20351. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20352. if (includeDescendants === void 0) { includeDescendants = true; }
  20353. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20354. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20355. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20356. if (maxDimension === 0) {
  20357. return this;
  20358. }
  20359. var scale = 1 / maxDimension;
  20360. this.scaling.scaleInPlace(scale);
  20361. return this;
  20362. };
  20363. /**
  20364. * Overwrite the current bounding info
  20365. * @param boundingInfo defines the new bounding info
  20366. * @returns the current mesh
  20367. */
  20368. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20369. this._boundingInfo = boundingInfo;
  20370. return this;
  20371. };
  20372. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20373. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20374. get: function () {
  20375. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20376. },
  20377. enumerable: true,
  20378. configurable: true
  20379. });
  20380. /** @hidden */
  20381. AbstractMesh.prototype._preActivate = function () {
  20382. };
  20383. /** @hidden */
  20384. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20385. };
  20386. /** @hidden */
  20387. AbstractMesh.prototype._activate = function (renderId) {
  20388. this._renderId = renderId;
  20389. };
  20390. /**
  20391. * Gets the current world matrix
  20392. * @returns a Matrix
  20393. */
  20394. AbstractMesh.prototype.getWorldMatrix = function () {
  20395. if (this._masterMesh) {
  20396. return this._masterMesh.getWorldMatrix();
  20397. }
  20398. return _super.prototype.getWorldMatrix.call(this);
  20399. };
  20400. /** @hidden */
  20401. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20402. if (this._masterMesh) {
  20403. return this._masterMesh._getWorldMatrixDeterminant();
  20404. }
  20405. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20406. };
  20407. // ================================== Point of View Movement =================================
  20408. /**
  20409. * Perform relative position change from the point of view of behind the front of the mesh.
  20410. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20411. * Supports definition of mesh facing forward or backward
  20412. * @param amountRight defines the distance on the right axis
  20413. * @param amountUp defines the distance on the up axis
  20414. * @param amountForward defines the distance on the forward axis
  20415. * @returns the current mesh
  20416. */
  20417. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20418. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20419. return this;
  20420. };
  20421. /**
  20422. * Calculate relative position change from the point of view of behind the front of the mesh.
  20423. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20424. * Supports definition of mesh facing forward or backward
  20425. * @param amountRight defines the distance on the right axis
  20426. * @param amountUp defines the distance on the up axis
  20427. * @param amountForward defines the distance on the forward axis
  20428. * @returns the new displacement vector
  20429. */
  20430. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20431. var rotMatrix = new BABYLON.Matrix();
  20432. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20433. rotQuaternion.toRotationMatrix(rotMatrix);
  20434. var translationDelta = BABYLON.Vector3.Zero();
  20435. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20437. return translationDelta;
  20438. };
  20439. // ================================== Point of View Rotation =================================
  20440. /**
  20441. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20442. * Supports definition of mesh facing forward or backward
  20443. * @param flipBack defines the flip
  20444. * @param twirlClockwise defines the twirl
  20445. * @param tiltRight defines the tilt
  20446. * @returns the current mesh
  20447. */
  20448. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20449. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20450. return this;
  20451. };
  20452. /**
  20453. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20454. * Supports definition of mesh facing forward or backward.
  20455. * @param flipBack defines the flip
  20456. * @param twirlClockwise defines the twirl
  20457. * @param tiltRight defines the tilt
  20458. * @returns the new rotation vector
  20459. */
  20460. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20461. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20462. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20463. };
  20464. /**
  20465. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20466. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20467. * @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
  20468. * @returns the new bounding vectors
  20469. */
  20470. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20471. if (includeDescendants === void 0) { includeDescendants = true; }
  20472. if (predicate === void 0) { predicate = null; }
  20473. // Ensures that all world matrix will be recomputed.
  20474. this.getScene().incrementRenderId();
  20475. this.computeWorldMatrix(true);
  20476. var min;
  20477. var max;
  20478. var boundingInfo = this.getBoundingInfo();
  20479. if (!this.subMeshes) {
  20480. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20481. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20482. }
  20483. else {
  20484. min = boundingInfo.boundingBox.minimumWorld;
  20485. max = boundingInfo.boundingBox.maximumWorld;
  20486. }
  20487. if (includeDescendants) {
  20488. var descendants = this.getDescendants(false);
  20489. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20490. var descendant = descendants_1[_i];
  20491. var childMesh = descendant;
  20492. childMesh.computeWorldMatrix(true);
  20493. // Filters meshes based on custom predicate function.
  20494. if (predicate && !predicate(childMesh)) {
  20495. continue;
  20496. }
  20497. //make sure we have the needed params to get mix and max
  20498. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20499. continue;
  20500. }
  20501. var childBoundingInfo = childMesh.getBoundingInfo();
  20502. var boundingBox = childBoundingInfo.boundingBox;
  20503. var minBox = boundingBox.minimumWorld;
  20504. var maxBox = boundingBox.maximumWorld;
  20505. BABYLON.Tools.CheckExtends(minBox, min, max);
  20506. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20507. }
  20508. }
  20509. return {
  20510. min: min,
  20511. max: max
  20512. };
  20513. };
  20514. /** @hidden */
  20515. AbstractMesh.prototype._updateBoundingInfo = function () {
  20516. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20517. this._boundingInfo.update(this.worldMatrixFromCache);
  20518. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20519. return this;
  20520. };
  20521. /** @hidden */
  20522. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20523. if (!this.subMeshes) {
  20524. return this;
  20525. }
  20526. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20527. var subMesh = this.subMeshes[subIndex];
  20528. if (!subMesh.IsGlobal) {
  20529. subMesh.updateBoundingInfo(matrix);
  20530. }
  20531. }
  20532. return this;
  20533. };
  20534. /** @hidden */
  20535. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20536. // Bounding info
  20537. this._updateBoundingInfo();
  20538. };
  20539. /**
  20540. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20541. * A mesh is in the frustum if its bounding box intersects the frustum
  20542. * @param frustumPlanes defines the frustum to test
  20543. * @returns true if the mesh is in the frustum planes
  20544. */
  20545. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20546. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20547. };
  20548. /**
  20549. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20550. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20551. * @param frustumPlanes defines the frustum to test
  20552. * @returns true if the mesh is completely in the frustum planes
  20553. */
  20554. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20555. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20556. };
  20557. /**
  20558. * True if the mesh intersects another mesh or a SolidParticle object
  20559. * @param mesh defines a target mesh or SolidParticle to test
  20560. * @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)
  20561. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20562. * @returns true if there is an intersection
  20563. */
  20564. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20565. if (precise === void 0) { precise = false; }
  20566. if (!this._boundingInfo || !mesh._boundingInfo) {
  20567. return false;
  20568. }
  20569. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20570. return true;
  20571. }
  20572. if (includeDescendants) {
  20573. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20574. var child = _a[_i];
  20575. if (child.intersectsMesh(mesh, precise, true)) {
  20576. return true;
  20577. }
  20578. }
  20579. }
  20580. return false;
  20581. };
  20582. /**
  20583. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20584. * @param point defines the point to test
  20585. * @returns true if there is an intersection
  20586. */
  20587. AbstractMesh.prototype.intersectsPoint = function (point) {
  20588. if (!this._boundingInfo) {
  20589. return false;
  20590. }
  20591. return this._boundingInfo.intersectsPoint(point);
  20592. };
  20593. /**
  20594. * Gets the current physics impostor
  20595. * @see http://doc.babylonjs.com/features/physics_engine
  20596. * @returns a physics impostor or null
  20597. */
  20598. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20599. return this.physicsImpostor;
  20600. };
  20601. /**
  20602. * Gets the position of the current mesh in camera space
  20603. * @param camera defines the camera to use
  20604. * @returns a position
  20605. */
  20606. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20607. if (camera === void 0) { camera = null; }
  20608. if (!camera) {
  20609. camera = this.getScene().activeCamera;
  20610. }
  20611. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20612. };
  20613. /**
  20614. * Returns the distance from the mesh to the active camera
  20615. * @param camera defines the camera to use
  20616. * @returns the distance
  20617. */
  20618. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20619. if (camera === void 0) { camera = null; }
  20620. if (!camera) {
  20621. camera = this.getScene().activeCamera;
  20622. }
  20623. return this.absolutePosition.subtract(camera.position).length();
  20624. };
  20625. /**
  20626. * Apply a physic impulse to the mesh
  20627. * @param force defines the force to apply
  20628. * @param contactPoint defines where to apply the force
  20629. * @returns the current mesh
  20630. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20631. */
  20632. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20633. if (!this.physicsImpostor) {
  20634. return this;
  20635. }
  20636. this.physicsImpostor.applyImpulse(force, contactPoint);
  20637. return this;
  20638. };
  20639. /**
  20640. * Creates a physic joint between two meshes
  20641. * @param otherMesh defines the other mesh to use
  20642. * @param pivot1 defines the pivot to use on this mesh
  20643. * @param pivot2 defines the pivot to use on the other mesh
  20644. * @param options defines additional options (can be plugin dependent)
  20645. * @returns the current mesh
  20646. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20647. */
  20648. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20649. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20650. return this;
  20651. }
  20652. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20653. mainPivot: pivot1,
  20654. connectedPivot: pivot2,
  20655. nativeParams: options
  20656. });
  20657. return this;
  20658. };
  20659. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20660. // Collisions
  20661. /**
  20662. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20663. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20664. */
  20665. get: function () {
  20666. return this._checkCollisions;
  20667. },
  20668. set: function (collisionEnabled) {
  20669. this._checkCollisions = collisionEnabled;
  20670. if (this.getScene().workerCollisions) {
  20671. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20672. }
  20673. },
  20674. enumerable: true,
  20675. configurable: true
  20676. });
  20677. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20678. /**
  20679. * Gets Collider object used to compute collisions (not physics)
  20680. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20681. */
  20682. get: function () {
  20683. return this._collider;
  20684. },
  20685. enumerable: true,
  20686. configurable: true
  20687. });
  20688. /**
  20689. * Move the mesh using collision engine
  20690. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20691. * @param displacement defines the requested displacement vector
  20692. * @returns the current mesh
  20693. */
  20694. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20695. var globalPosition = this.getAbsolutePosition();
  20696. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20697. if (!this._collider) {
  20698. this._collider = new BABYLON.Collider();
  20699. }
  20700. this._collider._radius = this.ellipsoid;
  20701. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20702. return this;
  20703. };
  20704. // Submeshes octree
  20705. /**
  20706. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20707. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20708. * @param maxCapacity defines the maximum size of each block (64 by default)
  20709. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20710. * @returns the new octree
  20711. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20712. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20713. */
  20714. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20715. if (maxCapacity === void 0) { maxCapacity = 64; }
  20716. if (maxDepth === void 0) { maxDepth = 2; }
  20717. if (!this._submeshesOctree) {
  20718. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20719. }
  20720. this.computeWorldMatrix(true);
  20721. var boundingInfo = this.getBoundingInfo();
  20722. // Update octree
  20723. var bbox = boundingInfo.boundingBox;
  20724. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20725. return this._submeshesOctree;
  20726. };
  20727. // Collisions
  20728. /** @hidden */
  20729. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20730. this._generatePointsArray();
  20731. if (!this._positions) {
  20732. return this;
  20733. }
  20734. // Transformation
  20735. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20736. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20737. subMesh._lastColliderWorldVertices = [];
  20738. subMesh._trianglePlanes = [];
  20739. var start = subMesh.verticesStart;
  20740. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20741. for (var i = start; i < end; i++) {
  20742. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20743. }
  20744. }
  20745. // Collide
  20746. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20747. if (collider.collisionFound) {
  20748. collider.collidedMesh = this;
  20749. }
  20750. return this;
  20751. };
  20752. /** @hidden */
  20753. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20754. var subMeshes;
  20755. var len;
  20756. // Octrees
  20757. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20758. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20759. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20760. len = intersections.length;
  20761. subMeshes = intersections.data;
  20762. }
  20763. else {
  20764. subMeshes = this.subMeshes;
  20765. len = subMeshes.length;
  20766. }
  20767. for (var index = 0; index < len; index++) {
  20768. var subMesh = subMeshes[index];
  20769. // Bounding test
  20770. if (len > 1 && !subMesh._checkCollision(collider))
  20771. continue;
  20772. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20773. }
  20774. return this;
  20775. };
  20776. /** @hidden */
  20777. AbstractMesh.prototype._checkCollision = function (collider) {
  20778. // Bounding box test
  20779. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20780. return this;
  20781. // Transformation matrix
  20782. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20783. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20784. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20785. return this;
  20786. };
  20787. // Picking
  20788. /** @hidden */
  20789. AbstractMesh.prototype._generatePointsArray = function () {
  20790. return false;
  20791. };
  20792. /**
  20793. * Checks if the passed Ray intersects with the mesh
  20794. * @param ray defines the ray to use
  20795. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20796. * @returns the picking info
  20797. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20798. */
  20799. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20800. var pickingInfo = new BABYLON.PickingInfo();
  20801. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20802. return pickingInfo;
  20803. }
  20804. if (!this._generatePointsArray()) {
  20805. return pickingInfo;
  20806. }
  20807. var intersectInfo = null;
  20808. // Octrees
  20809. var subMeshes;
  20810. var len;
  20811. if (this._submeshesOctree && this.useOctreeForPicking) {
  20812. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20813. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20814. len = intersections.length;
  20815. subMeshes = intersections.data;
  20816. }
  20817. else {
  20818. subMeshes = this.subMeshes;
  20819. len = subMeshes.length;
  20820. }
  20821. for (var index = 0; index < len; index++) {
  20822. var subMesh = subMeshes[index];
  20823. // Bounding test
  20824. if (len > 1 && !subMesh.canIntersects(ray))
  20825. continue;
  20826. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20827. if (currentIntersectInfo) {
  20828. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20829. intersectInfo = currentIntersectInfo;
  20830. intersectInfo.subMeshId = index;
  20831. if (fastCheck) {
  20832. break;
  20833. }
  20834. }
  20835. }
  20836. }
  20837. if (intersectInfo) {
  20838. // Get picked point
  20839. var world = this.getWorldMatrix();
  20840. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20841. var direction = ray.direction.clone();
  20842. direction = direction.scale(intersectInfo.distance);
  20843. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20844. var pickedPoint = worldOrigin.add(worldDirection);
  20845. // Return result
  20846. pickingInfo.hit = true;
  20847. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20848. pickingInfo.pickedPoint = pickedPoint;
  20849. pickingInfo.pickedMesh = this;
  20850. pickingInfo.bu = intersectInfo.bu || 0;
  20851. pickingInfo.bv = intersectInfo.bv || 0;
  20852. pickingInfo.faceId = intersectInfo.faceId;
  20853. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20854. return pickingInfo;
  20855. }
  20856. return pickingInfo;
  20857. };
  20858. /**
  20859. * Clones the current mesh
  20860. * @param name defines the mesh name
  20861. * @param newParent defines the new mesh parent
  20862. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20863. * @returns the new mesh
  20864. */
  20865. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20866. return null;
  20867. };
  20868. /**
  20869. * Disposes all the submeshes of the current meshnp
  20870. * @returns the current mesh
  20871. */
  20872. AbstractMesh.prototype.releaseSubMeshes = function () {
  20873. if (this.subMeshes) {
  20874. while (this.subMeshes.length) {
  20875. this.subMeshes[0].dispose();
  20876. }
  20877. }
  20878. else {
  20879. this.subMeshes = new Array();
  20880. }
  20881. return this;
  20882. };
  20883. /**
  20884. * Releases resources associated with this abstract mesh.
  20885. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20886. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20887. */
  20888. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20889. var _this = this;
  20890. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20891. var index;
  20892. // Smart Array Retainers.
  20893. this.getScene().freeActiveMeshes();
  20894. this.getScene().freeRenderingGroups();
  20895. // Action manager
  20896. if (this.actionManager !== undefined && this.actionManager !== null) {
  20897. this.actionManager.dispose();
  20898. this.actionManager = null;
  20899. }
  20900. // Skeleton
  20901. this._skeleton = null;
  20902. // Physics
  20903. if (this.physicsImpostor) {
  20904. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20905. }
  20906. // Intersections in progress
  20907. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20908. var other = this._intersectionsInProgress[index];
  20909. var pos = other._intersectionsInProgress.indexOf(this);
  20910. other._intersectionsInProgress.splice(pos, 1);
  20911. }
  20912. this._intersectionsInProgress = [];
  20913. // Lights
  20914. var lights = this.getScene().lights;
  20915. lights.forEach(function (light) {
  20916. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20917. if (meshIndex !== -1) {
  20918. light.includedOnlyMeshes.splice(meshIndex, 1);
  20919. }
  20920. meshIndex = light.excludedMeshes.indexOf(_this);
  20921. if (meshIndex !== -1) {
  20922. light.excludedMeshes.splice(meshIndex, 1);
  20923. }
  20924. // Shadow generators
  20925. var generator = light.getShadowGenerator();
  20926. if (generator) {
  20927. var shadowMap = generator.getShadowMap();
  20928. if (shadowMap && shadowMap.renderList) {
  20929. meshIndex = shadowMap.renderList.indexOf(_this);
  20930. if (meshIndex !== -1) {
  20931. shadowMap.renderList.splice(meshIndex, 1);
  20932. }
  20933. }
  20934. }
  20935. });
  20936. // Edges
  20937. if (this._edgesRenderer) {
  20938. this._edgesRenderer.dispose();
  20939. this._edgesRenderer = null;
  20940. }
  20941. // SubMeshes
  20942. if (this.getClassName() !== "InstancedMesh") {
  20943. this.releaseSubMeshes();
  20944. }
  20945. // Octree
  20946. var sceneOctree = this.getScene().selectionOctree;
  20947. if (sceneOctree !== undefined && sceneOctree !== null) {
  20948. var index = sceneOctree.dynamicContent.indexOf(this);
  20949. if (index !== -1) {
  20950. sceneOctree.dynamicContent.splice(index, 1);
  20951. }
  20952. }
  20953. // Query
  20954. var engine = this.getScene().getEngine();
  20955. if (this._occlusionQuery) {
  20956. this._isOcclusionQueryInProgress = false;
  20957. engine.deleteQuery(this._occlusionQuery);
  20958. this._occlusionQuery = null;
  20959. }
  20960. // Engine
  20961. engine.wipeCaches();
  20962. // Remove from scene
  20963. this.getScene().removeMesh(this);
  20964. if (disposeMaterialAndTextures) {
  20965. if (this.material) {
  20966. this.material.dispose(false, true);
  20967. }
  20968. }
  20969. if (!doNotRecurse) {
  20970. // Particles
  20971. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20972. if (this.getScene().particleSystems[index].emitter === this) {
  20973. this.getScene().particleSystems[index].dispose();
  20974. index--;
  20975. }
  20976. }
  20977. }
  20978. // facet data
  20979. if (this._facetDataEnabled) {
  20980. this.disableFacetData();
  20981. }
  20982. this.onAfterWorldMatrixUpdateObservable.clear();
  20983. this.onCollideObservable.clear();
  20984. this.onCollisionPositionChangeObservable.clear();
  20985. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20986. };
  20987. /**
  20988. * Adds the passed mesh as a child to the current mesh
  20989. * @param mesh defines the child mesh
  20990. * @returns the current mesh
  20991. */
  20992. AbstractMesh.prototype.addChild = function (mesh) {
  20993. mesh.setParent(this);
  20994. return this;
  20995. };
  20996. /**
  20997. * Removes the passed mesh from the current mesh children list
  20998. * @param mesh defines the child mesh
  20999. * @returns the current mesh
  21000. */
  21001. AbstractMesh.prototype.removeChild = function (mesh) {
  21002. mesh.setParent(null);
  21003. return this;
  21004. };
  21005. // Facet data
  21006. /** @hidden */
  21007. AbstractMesh.prototype._initFacetData = function () {
  21008. if (!this._facetNormals) {
  21009. this._facetNormals = new Array();
  21010. }
  21011. if (!this._facetPositions) {
  21012. this._facetPositions = new Array();
  21013. }
  21014. if (!this._facetPartitioning) {
  21015. this._facetPartitioning = new Array();
  21016. }
  21017. this._facetNb = (this.getIndices().length / 3) | 0;
  21018. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21019. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21020. for (var f = 0; f < this._facetNb; f++) {
  21021. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21022. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21023. }
  21024. this._facetDataEnabled = true;
  21025. return this;
  21026. };
  21027. /**
  21028. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21029. * This method can be called within the render loop.
  21030. * 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
  21031. * @returns the current mesh
  21032. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21033. */
  21034. AbstractMesh.prototype.updateFacetData = function () {
  21035. if (!this._facetDataEnabled) {
  21036. this._initFacetData();
  21037. }
  21038. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21039. var indices = this.getIndices();
  21040. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21041. var bInfo = this.getBoundingInfo();
  21042. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21043. // init arrays, matrix and sort function on first call
  21044. this._facetDepthSortEnabled = true;
  21045. if (indices instanceof Uint16Array) {
  21046. this._depthSortedIndices = new Uint16Array(indices);
  21047. }
  21048. else if (indices instanceof Uint32Array) {
  21049. this._depthSortedIndices = new Uint32Array(indices);
  21050. }
  21051. else {
  21052. var needs32bits = false;
  21053. for (var i = 0; i < indices.length; i++) {
  21054. if (indices[i] > 65535) {
  21055. needs32bits = true;
  21056. break;
  21057. }
  21058. }
  21059. if (needs32bits) {
  21060. this._depthSortedIndices = new Uint32Array(indices);
  21061. }
  21062. else {
  21063. this._depthSortedIndices = new Uint16Array(indices);
  21064. }
  21065. }
  21066. this._facetDepthSortFunction = function (f1, f2) {
  21067. return (f2.sqDistance - f1.sqDistance);
  21068. };
  21069. if (!this._facetDepthSortFrom) {
  21070. var camera = this.getScene().activeCamera;
  21071. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21072. }
  21073. this._depthSortedFacets = [];
  21074. for (var f = 0; f < this._facetNb; f++) {
  21075. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21076. this._depthSortedFacets.push(depthSortedFacet);
  21077. }
  21078. this._invertedMatrix = BABYLON.Matrix.Identity();
  21079. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21080. }
  21081. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21082. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21083. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21084. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21085. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21086. this._subDiv.max = this._partitioningSubdivisions;
  21087. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21088. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21089. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21090. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21091. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21092. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21093. // set the parameters for ComputeNormals()
  21094. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21095. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21096. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21097. this._facetParameters.bInfo = bInfo;
  21098. this._facetParameters.bbSize = this._bbSize;
  21099. this._facetParameters.subDiv = this._subDiv;
  21100. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21101. this._facetParameters.depthSort = this._facetDepthSort;
  21102. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21103. this.computeWorldMatrix(true);
  21104. this._worldMatrix.invertToRef(this._invertedMatrix);
  21105. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21106. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21107. }
  21108. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21109. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21110. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21111. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21112. var l = (this._depthSortedIndices.length / 3) | 0;
  21113. for (var f = 0; f < l; f++) {
  21114. var sind = this._depthSortedFacets[f].ind;
  21115. this._depthSortedIndices[f * 3] = indices[sind];
  21116. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21117. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21118. }
  21119. this.updateIndices(this._depthSortedIndices);
  21120. }
  21121. return this;
  21122. };
  21123. /**
  21124. * Returns the facetLocalNormals array.
  21125. * The normals are expressed in the mesh local spac
  21126. * @returns an array of Vector3
  21127. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21128. */
  21129. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21130. if (!this._facetNormals) {
  21131. this.updateFacetData();
  21132. }
  21133. return this._facetNormals;
  21134. };
  21135. /**
  21136. * Returns the facetLocalPositions array.
  21137. * The facet positions are expressed in the mesh local space
  21138. * @returns an array of Vector3
  21139. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21140. */
  21141. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21142. if (!this._facetPositions) {
  21143. this.updateFacetData();
  21144. }
  21145. return this._facetPositions;
  21146. };
  21147. /**
  21148. * Returns the facetLocalPartioning array
  21149. * @returns an array of array of numbers
  21150. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21151. */
  21152. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21153. if (!this._facetPartitioning) {
  21154. this.updateFacetData();
  21155. }
  21156. return this._facetPartitioning;
  21157. };
  21158. /**
  21159. * Returns the i-th facet position in the world system.
  21160. * This method allocates a new Vector3 per call
  21161. * @param i defines the facet index
  21162. * @returns a new Vector3
  21163. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21164. */
  21165. AbstractMesh.prototype.getFacetPosition = function (i) {
  21166. var pos = BABYLON.Vector3.Zero();
  21167. this.getFacetPositionToRef(i, pos);
  21168. return pos;
  21169. };
  21170. /**
  21171. * Sets the reference Vector3 with the i-th facet position in the world system
  21172. * @param i defines the facet index
  21173. * @param ref defines the target vector
  21174. * @returns the current mesh
  21175. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21176. */
  21177. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21178. var localPos = (this.getFacetLocalPositions())[i];
  21179. var world = this.getWorldMatrix();
  21180. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21181. return this;
  21182. };
  21183. /**
  21184. * Returns the i-th facet normal in the world system.
  21185. * This method allocates a new Vector3 per call
  21186. * @param i defines the facet index
  21187. * @returns a new Vector3
  21188. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21189. */
  21190. AbstractMesh.prototype.getFacetNormal = function (i) {
  21191. var norm = BABYLON.Vector3.Zero();
  21192. this.getFacetNormalToRef(i, norm);
  21193. return norm;
  21194. };
  21195. /**
  21196. * Sets the reference Vector3 with the i-th facet normal in the world system
  21197. * @param i defines the facet index
  21198. * @param ref defines the target vector
  21199. * @returns the current mesh
  21200. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21201. */
  21202. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21203. var localNorm = (this.getFacetLocalNormals())[i];
  21204. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21205. return this;
  21206. };
  21207. /**
  21208. * 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)
  21209. * @param x defines x coordinate
  21210. * @param y defines y coordinate
  21211. * @param z defines z coordinate
  21212. * @returns the array of facet indexes
  21213. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21214. */
  21215. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21216. var bInfo = this.getBoundingInfo();
  21217. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21218. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21219. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21220. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21221. return null;
  21222. }
  21223. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21224. };
  21225. /**
  21226. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21227. * @param projected sets as the (x,y,z) world projection on the facet
  21228. * @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
  21229. * @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
  21230. * @param x defines x coordinate
  21231. * @param y defines y coordinate
  21232. * @param z defines z coordinate
  21233. * @returns the face index if found (or null instead)
  21234. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21235. */
  21236. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21237. if (checkFace === void 0) { checkFace = false; }
  21238. if (facing === void 0) { facing = true; }
  21239. var world = this.getWorldMatrix();
  21240. var invMat = BABYLON.Tmp.Matrix[5];
  21241. world.invertToRef(invMat);
  21242. var invVect = BABYLON.Tmp.Vector3[8];
  21243. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21244. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21245. if (projected) {
  21246. // tranform the local computed projected vector to world coordinates
  21247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21248. }
  21249. return closest;
  21250. };
  21251. /**
  21252. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21253. * @param projected sets as the (x,y,z) local projection on the facet
  21254. * @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
  21255. * @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
  21256. * @param x defines x coordinate
  21257. * @param y defines y coordinate
  21258. * @param z defines z coordinate
  21259. * @returns the face index if found (or null instead)
  21260. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21261. */
  21262. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21263. if (checkFace === void 0) { checkFace = false; }
  21264. if (facing === void 0) { facing = true; }
  21265. var closest = null;
  21266. var tmpx = 0.0;
  21267. var tmpy = 0.0;
  21268. var tmpz = 0.0;
  21269. var d = 0.0; // tmp dot facet normal * facet position
  21270. var t0 = 0.0;
  21271. var projx = 0.0;
  21272. var projy = 0.0;
  21273. var projz = 0.0;
  21274. // Get all the facets in the same partitioning block than (x, y, z)
  21275. var facetPositions = this.getFacetLocalPositions();
  21276. var facetNormals = this.getFacetLocalNormals();
  21277. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21278. if (!facetsInBlock) {
  21279. return null;
  21280. }
  21281. // Get the closest facet to (x, y, z)
  21282. var shortest = Number.MAX_VALUE; // init distance vars
  21283. var tmpDistance = shortest;
  21284. var fib; // current facet in the block
  21285. var norm; // current facet normal
  21286. var p0; // current facet barycenter position
  21287. // loop on all the facets in the current partitioning block
  21288. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21289. fib = facetsInBlock[idx];
  21290. norm = facetNormals[fib];
  21291. p0 = facetPositions[fib];
  21292. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21293. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21294. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21295. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21296. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21297. projx = x + norm.x * t0;
  21298. projy = y + norm.y * t0;
  21299. projz = z + norm.z * t0;
  21300. tmpx = projx - x;
  21301. tmpy = projy - y;
  21302. tmpz = projz - z;
  21303. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21304. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21305. shortest = tmpDistance;
  21306. closest = fib;
  21307. if (projected) {
  21308. projected.x = projx;
  21309. projected.y = projy;
  21310. projected.z = projz;
  21311. }
  21312. }
  21313. }
  21314. }
  21315. return closest;
  21316. };
  21317. /**
  21318. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21319. * @returns the parameters
  21320. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21321. */
  21322. AbstractMesh.prototype.getFacetDataParameters = function () {
  21323. return this._facetParameters;
  21324. };
  21325. /**
  21326. * Disables the feature FacetData and frees the related memory
  21327. * @returns the current mesh
  21328. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21329. */
  21330. AbstractMesh.prototype.disableFacetData = function () {
  21331. if (this._facetDataEnabled) {
  21332. this._facetDataEnabled = false;
  21333. this._facetPositions = new Array();
  21334. this._facetNormals = new Array();
  21335. this._facetPartitioning = new Array();
  21336. this._facetParameters = null;
  21337. this._depthSortedIndices = new Uint32Array(0);
  21338. }
  21339. return this;
  21340. };
  21341. /**
  21342. * Updates the AbstractMesh indices array
  21343. * @param indices defines the data source
  21344. * @returns the current mesh
  21345. */
  21346. AbstractMesh.prototype.updateIndices = function (indices) {
  21347. return this;
  21348. };
  21349. /**
  21350. * Creates new normals data for the mesh
  21351. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21352. * @returns the current mesh
  21353. */
  21354. AbstractMesh.prototype.createNormals = function (updatable) {
  21355. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21356. var indices = this.getIndices();
  21357. var normals;
  21358. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21359. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21360. }
  21361. else {
  21362. normals = [];
  21363. }
  21364. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21365. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21366. return this;
  21367. };
  21368. /**
  21369. * Align the mesh with a normal
  21370. * @param normal defines the normal to use
  21371. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21372. * @returns the current mesh
  21373. */
  21374. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21375. if (!upDirection) {
  21376. upDirection = BABYLON.Axis.Y;
  21377. }
  21378. var axisX = BABYLON.Tmp.Vector3[0];
  21379. var axisZ = BABYLON.Tmp.Vector3[1];
  21380. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21381. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21382. if (this.rotationQuaternion) {
  21383. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21384. }
  21385. else {
  21386. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21387. }
  21388. return this;
  21389. };
  21390. /** @hidden */
  21391. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21392. this._isOccluded = false;
  21393. };
  21394. /** No occlusion */
  21395. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21396. /** Occlusion set to optimisitic */
  21397. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21398. /** Occlusion set to strict */
  21399. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21400. /** Use an accurante occlusion algorithm */
  21401. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21402. /** Use a conservative occlusion algorithm */
  21403. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21404. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21405. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21406. /** Culling strategy with bounding sphere only and then frustum culling */
  21407. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21408. return AbstractMesh;
  21409. }(BABYLON.TransformNode));
  21410. BABYLON.AbstractMesh = AbstractMesh;
  21411. })(BABYLON || (BABYLON = {}));
  21412. //# sourceMappingURL=babylon.abstractMesh.js.map
  21413. var BABYLON;
  21414. (function (BABYLON) {
  21415. /**
  21416. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21417. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21418. * 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.
  21419. */
  21420. var Light = /** @class */ (function (_super) {
  21421. __extends(Light, _super);
  21422. /**
  21423. * Creates a Light object in the scene.
  21424. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21425. * @param name The firendly name of the light
  21426. * @param scene The scene the light belongs too
  21427. */
  21428. function Light(name, scene) {
  21429. var _this = _super.call(this, name, scene) || this;
  21430. /**
  21431. * Diffuse gives the basic color to an object.
  21432. */
  21433. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21434. /**
  21435. * Specular produces a highlight color on an object.
  21436. * Note: This is note affecting PBR materials.
  21437. */
  21438. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21439. /**
  21440. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21441. * falling off base on range or angle.
  21442. * This can be set to any values in Light.FALLOFF_x.
  21443. *
  21444. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21445. * other types of materials.
  21446. */
  21447. _this.falloffType = Light.FALLOFF_DEFAULT;
  21448. /**
  21449. * Strength of the light.
  21450. * Note: By default it is define in the framework own unit.
  21451. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21452. */
  21453. _this.intensity = 1.0;
  21454. _this._range = Number.MAX_VALUE;
  21455. _this._inverseSquaredRange = 0;
  21456. /**
  21457. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21458. * of light.
  21459. */
  21460. _this._photometricScale = 1.0;
  21461. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21462. _this._radius = 0.00001;
  21463. /**
  21464. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21465. * exceeding the number allowed of the materials.
  21466. */
  21467. _this.renderPriority = 0;
  21468. _this._shadowEnabled = true;
  21469. _this._excludeWithLayerMask = 0;
  21470. _this._includeOnlyWithLayerMask = 0;
  21471. _this._lightmapMode = 0;
  21472. /**
  21473. * @hidden Internal use only.
  21474. */
  21475. _this._excludedMeshesIds = new Array();
  21476. /**
  21477. * @hidden Internal use only.
  21478. */
  21479. _this._includedOnlyMeshesIds = new Array();
  21480. _this.getScene().addLight(_this);
  21481. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21482. _this._buildUniformLayout();
  21483. _this.includedOnlyMeshes = new Array();
  21484. _this.excludedMeshes = new Array();
  21485. _this._resyncMeshes();
  21486. return _this;
  21487. }
  21488. Object.defineProperty(Light.prototype, "range", {
  21489. /**
  21490. * Defines how far from the source the light is impacting in scene units.
  21491. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21492. */
  21493. get: function () {
  21494. return this._range;
  21495. },
  21496. /**
  21497. * Defines how far from the source the light is impacting in scene units.
  21498. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21499. */
  21500. set: function (value) {
  21501. this._range = value;
  21502. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(Light.prototype, "intensityMode", {
  21508. /**
  21509. * Gets the photometric scale used to interpret the intensity.
  21510. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21511. */
  21512. get: function () {
  21513. return this._intensityMode;
  21514. },
  21515. /**
  21516. * Sets the photometric scale used to interpret the intensity.
  21517. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21518. */
  21519. set: function (value) {
  21520. this._intensityMode = value;
  21521. this._computePhotometricScale();
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. ;
  21527. ;
  21528. Object.defineProperty(Light.prototype, "radius", {
  21529. /**
  21530. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21531. */
  21532. get: function () {
  21533. return this._radius;
  21534. },
  21535. /**
  21536. * sets the light radius used by PBR Materials to simulate soft area lights.
  21537. */
  21538. set: function (value) {
  21539. this._radius = value;
  21540. this._computePhotometricScale();
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. ;
  21546. ;
  21547. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21548. /**
  21549. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21550. * the current shadow generator.
  21551. */
  21552. get: function () {
  21553. return this._shadowEnabled;
  21554. },
  21555. /**
  21556. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21557. * the current shadow generator.
  21558. */
  21559. set: function (value) {
  21560. if (this._shadowEnabled === value) {
  21561. return;
  21562. }
  21563. this._shadowEnabled = value;
  21564. this._markMeshesAsLightDirty();
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21570. /**
  21571. * Gets the only meshes impacted by this light.
  21572. */
  21573. get: function () {
  21574. return this._includedOnlyMeshes;
  21575. },
  21576. /**
  21577. * Sets the only meshes impacted by this light.
  21578. */
  21579. set: function (value) {
  21580. this._includedOnlyMeshes = value;
  21581. this._hookArrayForIncludedOnly(value);
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21587. /**
  21588. * Gets the meshes not impacted by this light.
  21589. */
  21590. get: function () {
  21591. return this._excludedMeshes;
  21592. },
  21593. /**
  21594. * Sets the meshes not impacted by this light.
  21595. */
  21596. set: function (value) {
  21597. this._excludedMeshes = value;
  21598. this._hookArrayForExcluded(value);
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21604. /**
  21605. * Gets the layer id use to find what meshes are not impacted by the light.
  21606. * Inactive if 0
  21607. */
  21608. get: function () {
  21609. return this._excludeWithLayerMask;
  21610. },
  21611. /**
  21612. * Sets the layer id use to find what meshes are not impacted by the light.
  21613. * Inactive if 0
  21614. */
  21615. set: function (value) {
  21616. this._excludeWithLayerMask = value;
  21617. this._resyncMeshes();
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21623. /**
  21624. * Gets the layer id use to find what meshes are impacted by the light.
  21625. * Inactive if 0
  21626. */
  21627. get: function () {
  21628. return this._includeOnlyWithLayerMask;
  21629. },
  21630. /**
  21631. * Sets the layer id use to find what meshes are impacted by the light.
  21632. * Inactive if 0
  21633. */
  21634. set: function (value) {
  21635. this._includeOnlyWithLayerMask = value;
  21636. this._resyncMeshes();
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(Light.prototype, "lightmapMode", {
  21642. /**
  21643. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21644. */
  21645. get: function () {
  21646. return this._lightmapMode;
  21647. },
  21648. /**
  21649. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21650. */
  21651. set: function (value) {
  21652. if (this._lightmapMode === value) {
  21653. return;
  21654. }
  21655. this._lightmapMode = value;
  21656. this._markMeshesAsLightDirty();
  21657. },
  21658. enumerable: true,
  21659. configurable: true
  21660. });
  21661. /**
  21662. * Returns the string "Light".
  21663. * @returns the class name
  21664. */
  21665. Light.prototype.getClassName = function () {
  21666. return "Light";
  21667. };
  21668. /**
  21669. * Converts the light information to a readable string for debug purpose.
  21670. * @param fullDetails Supports for multiple levels of logging within scene loading
  21671. * @returns the human readable light info
  21672. */
  21673. Light.prototype.toString = function (fullDetails) {
  21674. var ret = "Name: " + this.name;
  21675. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21676. if (this.animations) {
  21677. for (var i = 0; i < this.animations.length; i++) {
  21678. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21679. }
  21680. }
  21681. if (fullDetails) {
  21682. }
  21683. return ret;
  21684. };
  21685. /**
  21686. * Set the enabled state of this node.
  21687. * @param value - the new enabled state
  21688. */
  21689. Light.prototype.setEnabled = function (value) {
  21690. _super.prototype.setEnabled.call(this, value);
  21691. this._resyncMeshes();
  21692. };
  21693. /**
  21694. * Returns the Light associated shadow generator if any.
  21695. * @return the associated shadow generator.
  21696. */
  21697. Light.prototype.getShadowGenerator = function () {
  21698. return this._shadowGenerator;
  21699. };
  21700. /**
  21701. * Returns a Vector3, the absolute light position in the World.
  21702. * @returns the world space position of the light
  21703. */
  21704. Light.prototype.getAbsolutePosition = function () {
  21705. return BABYLON.Vector3.Zero();
  21706. };
  21707. /**
  21708. * Specifies if the light will affect the passed mesh.
  21709. * @param mesh The mesh to test against the light
  21710. * @return true the mesh is affected otherwise, false.
  21711. */
  21712. Light.prototype.canAffectMesh = function (mesh) {
  21713. if (!mesh) {
  21714. return true;
  21715. }
  21716. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21717. return false;
  21718. }
  21719. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21720. return false;
  21721. }
  21722. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21723. return false;
  21724. }
  21725. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21726. return false;
  21727. }
  21728. return true;
  21729. };
  21730. /**
  21731. * Computes and Returns the light World matrix.
  21732. * @returns the world matrix
  21733. */
  21734. Light.prototype.getWorldMatrix = function () {
  21735. this._currentRenderId = this.getScene().getRenderId();
  21736. this._childRenderId = this._currentRenderId;
  21737. var worldMatrix = this._getWorldMatrix();
  21738. if (this.parent && this.parent.getWorldMatrix) {
  21739. if (!this._parentedWorldMatrix) {
  21740. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21741. }
  21742. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21743. this._markSyncedWithParent();
  21744. return this._parentedWorldMatrix;
  21745. }
  21746. return worldMatrix;
  21747. };
  21748. /**
  21749. * Sort function to order lights for rendering.
  21750. * @param a First Light object to compare to second.
  21751. * @param b Second Light object to compare first.
  21752. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21753. */
  21754. Light.CompareLightsPriority = function (a, b) {
  21755. //shadow-casting lights have priority over non-shadow-casting lights
  21756. //the renderPrioirty is a secondary sort criterion
  21757. if (a.shadowEnabled !== b.shadowEnabled) {
  21758. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21759. }
  21760. return b.renderPriority - a.renderPriority;
  21761. };
  21762. /**
  21763. * Releases resources associated with this node.
  21764. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21765. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21766. */
  21767. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21768. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21769. if (this._shadowGenerator) {
  21770. this._shadowGenerator.dispose();
  21771. this._shadowGenerator = null;
  21772. }
  21773. // Animations
  21774. this.getScene().stopAnimation(this);
  21775. // Remove from meshes
  21776. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21777. var mesh = _a[_i];
  21778. mesh._removeLightSource(this);
  21779. }
  21780. this._uniformBuffer.dispose();
  21781. // Remove from scene
  21782. this.getScene().removeLight(this);
  21783. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21784. };
  21785. /**
  21786. * Returns the light type ID (integer).
  21787. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21788. */
  21789. Light.prototype.getTypeID = function () {
  21790. return 0;
  21791. };
  21792. /**
  21793. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21794. * @returns the scaled intensity in intensity mode unit
  21795. */
  21796. Light.prototype.getScaledIntensity = function () {
  21797. return this._photometricScale * this.intensity;
  21798. };
  21799. /**
  21800. * Returns a new Light object, named "name", from the current one.
  21801. * @param name The name of the cloned light
  21802. * @returns the new created light
  21803. */
  21804. Light.prototype.clone = function (name) {
  21805. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21806. if (!constructor) {
  21807. return null;
  21808. }
  21809. return BABYLON.SerializationHelper.Clone(constructor, this);
  21810. };
  21811. /**
  21812. * Serializes the current light into a Serialization object.
  21813. * @returns the serialized object.
  21814. */
  21815. Light.prototype.serialize = function () {
  21816. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21817. // Type
  21818. serializationObject.type = this.getTypeID();
  21819. // Parent
  21820. if (this.parent) {
  21821. serializationObject.parentId = this.parent.id;
  21822. }
  21823. // Inclusion / exclusions
  21824. if (this.excludedMeshes.length > 0) {
  21825. serializationObject.excludedMeshesIds = [];
  21826. this.excludedMeshes.forEach(function (mesh) {
  21827. serializationObject.excludedMeshesIds.push(mesh.id);
  21828. });
  21829. }
  21830. if (this.includedOnlyMeshes.length > 0) {
  21831. serializationObject.includedOnlyMeshesIds = [];
  21832. this.includedOnlyMeshes.forEach(function (mesh) {
  21833. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21834. });
  21835. }
  21836. // Animations
  21837. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21838. serializationObject.ranges = this.serializeAnimationRanges();
  21839. return serializationObject;
  21840. };
  21841. /**
  21842. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21843. * This new light is named "name" and added to the passed scene.
  21844. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21845. * @param name The friendly name of the light
  21846. * @param scene The scene the new light will belong to
  21847. * @returns the constructor function
  21848. */
  21849. Light.GetConstructorFromName = function (type, name, scene) {
  21850. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21851. if (constructorFunc) {
  21852. return constructorFunc;
  21853. }
  21854. // Default to no light for none present once.
  21855. return null;
  21856. };
  21857. /**
  21858. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21859. * @param parsedLight The JSON representation of the light
  21860. * @param scene The scene to create the parsed light in
  21861. * @returns the created light after parsing
  21862. */
  21863. Light.Parse = function (parsedLight, scene) {
  21864. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21865. if (!constructor) {
  21866. return null;
  21867. }
  21868. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21869. // Inclusion / exclusions
  21870. if (parsedLight.excludedMeshesIds) {
  21871. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21872. }
  21873. if (parsedLight.includedOnlyMeshesIds) {
  21874. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21875. }
  21876. // Parent
  21877. if (parsedLight.parentId) {
  21878. light._waitingParentId = parsedLight.parentId;
  21879. }
  21880. // Animations
  21881. if (parsedLight.animations) {
  21882. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21883. var parsedAnimation = parsedLight.animations[animationIndex];
  21884. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21885. }
  21886. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21887. }
  21888. if (parsedLight.autoAnimate) {
  21889. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21890. }
  21891. return light;
  21892. };
  21893. Light.prototype._hookArrayForExcluded = function (array) {
  21894. var _this = this;
  21895. var oldPush = array.push;
  21896. array.push = function () {
  21897. var items = [];
  21898. for (var _i = 0; _i < arguments.length; _i++) {
  21899. items[_i] = arguments[_i];
  21900. }
  21901. var result = oldPush.apply(array, items);
  21902. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21903. var item = items_1[_a];
  21904. item._resyncLighSource(_this);
  21905. }
  21906. return result;
  21907. };
  21908. var oldSplice = array.splice;
  21909. array.splice = function (index, deleteCount) {
  21910. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21911. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21912. var item = deleted_1[_i];
  21913. item._resyncLighSource(_this);
  21914. }
  21915. return deleted;
  21916. };
  21917. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21918. var item = array_1[_i];
  21919. item._resyncLighSource(this);
  21920. }
  21921. };
  21922. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21923. var _this = this;
  21924. var oldPush = array.push;
  21925. array.push = function () {
  21926. var items = [];
  21927. for (var _i = 0; _i < arguments.length; _i++) {
  21928. items[_i] = arguments[_i];
  21929. }
  21930. var result = oldPush.apply(array, items);
  21931. _this._resyncMeshes();
  21932. return result;
  21933. };
  21934. var oldSplice = array.splice;
  21935. array.splice = function (index, deleteCount) {
  21936. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21937. _this._resyncMeshes();
  21938. return deleted;
  21939. };
  21940. this._resyncMeshes();
  21941. };
  21942. Light.prototype._resyncMeshes = function () {
  21943. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21944. var mesh = _a[_i];
  21945. mesh._resyncLighSource(this);
  21946. }
  21947. };
  21948. /**
  21949. * Forces the meshes to update their light related information in their rendering used effects
  21950. * @hidden Internal Use Only
  21951. */
  21952. Light.prototype._markMeshesAsLightDirty = function () {
  21953. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21954. var mesh = _a[_i];
  21955. if (mesh._lightSources.indexOf(this) !== -1) {
  21956. mesh._markSubMeshesAsLightDirty();
  21957. }
  21958. }
  21959. };
  21960. /**
  21961. * Recomputes the cached photometric scale if needed.
  21962. */
  21963. Light.prototype._computePhotometricScale = function () {
  21964. this._photometricScale = this._getPhotometricScale();
  21965. this.getScene().resetCachedMaterial();
  21966. };
  21967. /**
  21968. * Returns the Photometric Scale according to the light type and intensity mode.
  21969. */
  21970. Light.prototype._getPhotometricScale = function () {
  21971. var photometricScale = 0.0;
  21972. var lightTypeID = this.getTypeID();
  21973. //get photometric mode
  21974. var photometricMode = this.intensityMode;
  21975. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21976. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21977. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21978. }
  21979. else {
  21980. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21981. }
  21982. }
  21983. //compute photometric scale
  21984. switch (lightTypeID) {
  21985. case Light.LIGHTTYPEID_POINTLIGHT:
  21986. case Light.LIGHTTYPEID_SPOTLIGHT:
  21987. switch (photometricMode) {
  21988. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21989. photometricScale = 1.0 / (4.0 * Math.PI);
  21990. break;
  21991. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21992. photometricScale = 1.0;
  21993. break;
  21994. case Light.INTENSITYMODE_LUMINANCE:
  21995. photometricScale = this.radius * this.radius;
  21996. break;
  21997. }
  21998. break;
  21999. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22000. switch (photometricMode) {
  22001. case Light.INTENSITYMODE_ILLUMINANCE:
  22002. photometricScale = 1.0;
  22003. break;
  22004. case Light.INTENSITYMODE_LUMINANCE:
  22005. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22006. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22007. var apexAngleRadians = this.radius;
  22008. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22009. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22010. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22011. photometricScale = solidAngle;
  22012. break;
  22013. }
  22014. break;
  22015. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22016. // No fall off in hemisperic light.
  22017. photometricScale = 1.0;
  22018. break;
  22019. }
  22020. return photometricScale;
  22021. };
  22022. /**
  22023. * Reorder the light in the scene according to their defined priority.
  22024. * @hidden Internal Use Only
  22025. */
  22026. Light.prototype._reorderLightsInScene = function () {
  22027. var scene = this.getScene();
  22028. if (this._renderPriority != 0) {
  22029. scene.requireLightSorting = true;
  22030. }
  22031. this.getScene().sortLightsByPriority();
  22032. };
  22033. /**
  22034. * Falloff Default: light is falling off following the material specification:
  22035. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22036. */
  22037. Light.FALLOFF_DEFAULT = 0;
  22038. /**
  22039. * Falloff Physical: light is falling off following the inverse squared distance law.
  22040. */
  22041. Light.FALLOFF_PHYSICAL = 1;
  22042. /**
  22043. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22044. * to enhance interoperability with other engines.
  22045. */
  22046. Light.FALLOFF_GLTF = 2;
  22047. /**
  22048. * Falloff Standard: light is falling off like in the standard material
  22049. * to enhance interoperability with other materials.
  22050. */
  22051. Light.FALLOFF_STANDARD = 3;
  22052. //lightmapMode Consts
  22053. /**
  22054. * If every light affecting the material is in this lightmapMode,
  22055. * material.lightmapTexture adds or multiplies
  22056. * (depends on material.useLightmapAsShadowmap)
  22057. * after every other light calculations.
  22058. */
  22059. Light.LIGHTMAP_DEFAULT = 0;
  22060. /**
  22061. * material.lightmapTexture as only diffuse lighting from this light
  22062. * adds only specular lighting from this light
  22063. * adds dynamic shadows
  22064. */
  22065. Light.LIGHTMAP_SPECULAR = 1;
  22066. /**
  22067. * material.lightmapTexture as only lighting
  22068. * no light calculation from this light
  22069. * only adds dynamic shadows from this light
  22070. */
  22071. Light.LIGHTMAP_SHADOWSONLY = 2;
  22072. // Intensity Mode Consts
  22073. /**
  22074. * Each light type uses the default quantity according to its type:
  22075. * point/spot lights use luminous intensity
  22076. * directional lights use illuminance
  22077. */
  22078. Light.INTENSITYMODE_AUTOMATIC = 0;
  22079. /**
  22080. * lumen (lm)
  22081. */
  22082. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22083. /**
  22084. * candela (lm/sr)
  22085. */
  22086. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22087. /**
  22088. * lux (lm/m^2)
  22089. */
  22090. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22091. /**
  22092. * nit (cd/m^2)
  22093. */
  22094. Light.INTENSITYMODE_LUMINANCE = 4;
  22095. // Light types ids const.
  22096. /**
  22097. * Light type const id of the point light.
  22098. */
  22099. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22100. /**
  22101. * Light type const id of the directional light.
  22102. */
  22103. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22104. /**
  22105. * Light type const id of the spot light.
  22106. */
  22107. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22108. /**
  22109. * Light type const id of the hemispheric light.
  22110. */
  22111. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22112. __decorate([
  22113. BABYLON.serializeAsColor3()
  22114. ], Light.prototype, "diffuse", void 0);
  22115. __decorate([
  22116. BABYLON.serializeAsColor3()
  22117. ], Light.prototype, "specular", void 0);
  22118. __decorate([
  22119. BABYLON.serialize()
  22120. ], Light.prototype, "falloffType", void 0);
  22121. __decorate([
  22122. BABYLON.serialize()
  22123. ], Light.prototype, "intensity", void 0);
  22124. __decorate([
  22125. BABYLON.serialize()
  22126. ], Light.prototype, "range", null);
  22127. __decorate([
  22128. BABYLON.serialize()
  22129. ], Light.prototype, "intensityMode", null);
  22130. __decorate([
  22131. BABYLON.serialize()
  22132. ], Light.prototype, "radius", null);
  22133. __decorate([
  22134. BABYLON.serialize()
  22135. ], Light.prototype, "_renderPriority", void 0);
  22136. __decorate([
  22137. BABYLON.expandToProperty("_reorderLightsInScene")
  22138. ], Light.prototype, "renderPriority", void 0);
  22139. __decorate([
  22140. BABYLON.serialize("shadowEnabled")
  22141. ], Light.prototype, "_shadowEnabled", void 0);
  22142. __decorate([
  22143. BABYLON.serialize("excludeWithLayerMask")
  22144. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22145. __decorate([
  22146. BABYLON.serialize("includeOnlyWithLayerMask")
  22147. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22148. __decorate([
  22149. BABYLON.serialize("lightmapMode")
  22150. ], Light.prototype, "_lightmapMode", void 0);
  22151. return Light;
  22152. }(BABYLON.Node));
  22153. BABYLON.Light = Light;
  22154. })(BABYLON || (BABYLON = {}));
  22155. //# sourceMappingURL=babylon.light.js.map
  22156. var BABYLON;
  22157. (function (BABYLON) {
  22158. var Camera = /** @class */ (function (_super) {
  22159. __extends(Camera, _super);
  22160. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22161. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22162. var _this = _super.call(this, name, scene) || this;
  22163. /**
  22164. * The vector the camera should consider as up.
  22165. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22166. */
  22167. _this.upVector = BABYLON.Vector3.Up();
  22168. _this.orthoLeft = null;
  22169. _this.orthoRight = null;
  22170. _this.orthoBottom = null;
  22171. _this.orthoTop = null;
  22172. /**
  22173. * FOV is set in Radians. (default is 0.8)
  22174. */
  22175. _this.fov = 0.8;
  22176. _this.minZ = 1;
  22177. _this.maxZ = 10000.0;
  22178. _this.inertia = 0.9;
  22179. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22180. _this.isIntermediate = false;
  22181. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22182. /**
  22183. * Restricts the camera to viewing objects with the same layerMask.
  22184. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22185. */
  22186. _this.layerMask = 0x0FFFFFFF;
  22187. /**
  22188. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22189. */
  22190. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22191. // Camera rig members
  22192. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22193. /** @hidden */
  22194. _this._rigCameras = new Array();
  22195. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22196. /** @hidden */
  22197. _this._skipRendering = false;
  22198. _this.customRenderTargets = new Array();
  22199. // Observables
  22200. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22201. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22202. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22203. _this.onRestoreStateObservable = new BABYLON.Observable();
  22204. // Cache
  22205. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22206. _this._projectionMatrix = new BABYLON.Matrix();
  22207. _this._doNotComputeProjectionMatrix = false;
  22208. _this._worldMatrix = BABYLON.Matrix.Identity();
  22209. _this._postProcesses = new Array();
  22210. _this._transformMatrix = BABYLON.Matrix.Zero();
  22211. _this._activeMeshes = new BABYLON.SmartArray(256);
  22212. _this._globalPosition = BABYLON.Vector3.Zero();
  22213. _this._refreshFrustumPlanes = true;
  22214. _this.getScene().addCamera(_this);
  22215. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22216. _this.getScene().activeCamera = _this;
  22217. }
  22218. _this.position = position;
  22219. return _this;
  22220. }
  22221. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22222. get: function () {
  22223. return Camera._PERSPECTIVE_CAMERA;
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22229. get: function () {
  22230. return Camera._ORTHOGRAPHIC_CAMERA;
  22231. },
  22232. enumerable: true,
  22233. configurable: true
  22234. });
  22235. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22236. /**
  22237. * This is the default FOV mode for perspective cameras.
  22238. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22239. *
  22240. */
  22241. get: function () {
  22242. return Camera._FOVMODE_VERTICAL_FIXED;
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22248. /**
  22249. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22250. *
  22251. */
  22252. get: function () {
  22253. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22254. },
  22255. enumerable: true,
  22256. configurable: true
  22257. });
  22258. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22259. get: function () {
  22260. return Camera._RIG_MODE_NONE;
  22261. },
  22262. enumerable: true,
  22263. configurable: true
  22264. });
  22265. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22266. get: function () {
  22267. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22268. },
  22269. enumerable: true,
  22270. configurable: true
  22271. });
  22272. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22273. get: function () {
  22274. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22280. get: function () {
  22281. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22282. },
  22283. enumerable: true,
  22284. configurable: true
  22285. });
  22286. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22287. get: function () {
  22288. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22294. get: function () {
  22295. return Camera._RIG_MODE_VR;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22301. get: function () {
  22302. return Camera._RIG_MODE_WEBVR;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. /**
  22308. * Store current camera state (fov, position, etc..)
  22309. */
  22310. Camera.prototype.storeState = function () {
  22311. this._stateStored = true;
  22312. this._storedFov = this.fov;
  22313. return this;
  22314. };
  22315. /**
  22316. * Restores the camera state values if it has been stored. You must call storeState() first
  22317. */
  22318. Camera.prototype._restoreStateValues = function () {
  22319. if (!this._stateStored) {
  22320. return false;
  22321. }
  22322. this.fov = this._storedFov;
  22323. return true;
  22324. };
  22325. /**
  22326. * Restored camera state. You must call storeState() first
  22327. */
  22328. Camera.prototype.restoreState = function () {
  22329. if (this._restoreStateValues()) {
  22330. this.onRestoreStateObservable.notifyObservers(this);
  22331. return true;
  22332. }
  22333. return false;
  22334. };
  22335. Camera.prototype.getClassName = function () {
  22336. return "Camera";
  22337. };
  22338. /**
  22339. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22340. */
  22341. Camera.prototype.toString = function (fullDetails) {
  22342. var ret = "Name: " + this.name;
  22343. ret += ", type: " + this.getClassName();
  22344. if (this.animations) {
  22345. for (var i = 0; i < this.animations.length; i++) {
  22346. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22347. }
  22348. }
  22349. if (fullDetails) {
  22350. }
  22351. return ret;
  22352. };
  22353. Object.defineProperty(Camera.prototype, "globalPosition", {
  22354. get: function () {
  22355. return this._globalPosition;
  22356. },
  22357. enumerable: true,
  22358. configurable: true
  22359. });
  22360. Camera.prototype.getActiveMeshes = function () {
  22361. return this._activeMeshes;
  22362. };
  22363. Camera.prototype.isActiveMesh = function (mesh) {
  22364. return (this._activeMeshes.indexOf(mesh) !== -1);
  22365. };
  22366. /**
  22367. * Is this camera ready to be used/rendered
  22368. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22369. * @return true if the camera is ready
  22370. */
  22371. Camera.prototype.isReady = function (completeCheck) {
  22372. if (completeCheck === void 0) { completeCheck = false; }
  22373. if (completeCheck) {
  22374. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22375. var pp = _a[_i];
  22376. if (pp && !pp.isReady()) {
  22377. return false;
  22378. }
  22379. }
  22380. }
  22381. return _super.prototype.isReady.call(this, completeCheck);
  22382. };
  22383. //Cache
  22384. /** @hidden */
  22385. Camera.prototype._initCache = function () {
  22386. _super.prototype._initCache.call(this);
  22387. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22388. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22389. this._cache.mode = undefined;
  22390. this._cache.minZ = undefined;
  22391. this._cache.maxZ = undefined;
  22392. this._cache.fov = undefined;
  22393. this._cache.fovMode = undefined;
  22394. this._cache.aspectRatio = undefined;
  22395. this._cache.orthoLeft = undefined;
  22396. this._cache.orthoRight = undefined;
  22397. this._cache.orthoBottom = undefined;
  22398. this._cache.orthoTop = undefined;
  22399. this._cache.renderWidth = undefined;
  22400. this._cache.renderHeight = undefined;
  22401. };
  22402. /** @hidden */
  22403. Camera.prototype._updateCache = function (ignoreParentClass) {
  22404. if (!ignoreParentClass) {
  22405. _super.prototype._updateCache.call(this);
  22406. }
  22407. this._cache.position.copyFrom(this.position);
  22408. this._cache.upVector.copyFrom(this.upVector);
  22409. };
  22410. // Synchronized
  22411. /** @hidden */
  22412. Camera.prototype._isSynchronized = function () {
  22413. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22414. };
  22415. /** @hidden */
  22416. Camera.prototype._isSynchronizedViewMatrix = function () {
  22417. if (!_super.prototype._isSynchronized.call(this))
  22418. return false;
  22419. return this._cache.position.equals(this.position)
  22420. && this._cache.upVector.equals(this.upVector)
  22421. && this.isSynchronizedWithParent();
  22422. };
  22423. /** @hidden */
  22424. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22425. var check = this._cache.mode === this.mode
  22426. && this._cache.minZ === this.minZ
  22427. && this._cache.maxZ === this.maxZ;
  22428. if (!check) {
  22429. return false;
  22430. }
  22431. var engine = this.getEngine();
  22432. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22433. check = this._cache.fov === this.fov
  22434. && this._cache.fovMode === this.fovMode
  22435. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22436. }
  22437. else {
  22438. check = this._cache.orthoLeft === this.orthoLeft
  22439. && this._cache.orthoRight === this.orthoRight
  22440. && this._cache.orthoBottom === this.orthoBottom
  22441. && this._cache.orthoTop === this.orthoTop
  22442. && this._cache.renderWidth === engine.getRenderWidth()
  22443. && this._cache.renderHeight === engine.getRenderHeight();
  22444. }
  22445. return check;
  22446. };
  22447. // Controls
  22448. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22449. };
  22450. Camera.prototype.detachControl = function (element) {
  22451. };
  22452. Camera.prototype.update = function () {
  22453. this._checkInputs();
  22454. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22455. this._updateRigCameras();
  22456. }
  22457. };
  22458. /** @hidden */
  22459. Camera.prototype._checkInputs = function () {
  22460. this.onAfterCheckInputsObservable.notifyObservers(this);
  22461. };
  22462. Object.defineProperty(Camera.prototype, "rigCameras", {
  22463. get: function () {
  22464. return this._rigCameras;
  22465. },
  22466. enumerable: true,
  22467. configurable: true
  22468. });
  22469. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22470. get: function () {
  22471. return this._rigPostProcess;
  22472. },
  22473. enumerable: true,
  22474. configurable: true
  22475. });
  22476. /**
  22477. * Internal, gets the first post proces.
  22478. * @returns the first post process to be run on this camera.
  22479. */
  22480. Camera.prototype._getFirstPostProcess = function () {
  22481. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22482. if (this._postProcesses[ppIndex] !== null) {
  22483. return this._postProcesses[ppIndex];
  22484. }
  22485. }
  22486. return null;
  22487. };
  22488. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22489. // invalidate framebuffer
  22490. var firstPostProcess = this._getFirstPostProcess();
  22491. if (firstPostProcess) {
  22492. firstPostProcess.markTextureDirty();
  22493. }
  22494. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22495. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22496. var cam = this._rigCameras[i];
  22497. var rigPostProcess = cam._rigPostProcess;
  22498. // for VR rig, there does not have to be a post process
  22499. if (rigPostProcess) {
  22500. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22501. if (isPass) {
  22502. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22503. cam.isIntermediate = this._postProcesses.length === 0;
  22504. }
  22505. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22506. rigPostProcess.markTextureDirty();
  22507. }
  22508. else {
  22509. cam._postProcesses = this._postProcesses.slice(0);
  22510. }
  22511. }
  22512. };
  22513. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22514. if (insertAt === void 0) { insertAt = null; }
  22515. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22516. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22517. return 0;
  22518. }
  22519. if (insertAt == null || insertAt < 0) {
  22520. this._postProcesses.push(postProcess);
  22521. }
  22522. else if (this._postProcesses[insertAt] === null) {
  22523. this._postProcesses[insertAt] = postProcess;
  22524. }
  22525. else {
  22526. this._postProcesses.splice(insertAt, 0, postProcess);
  22527. }
  22528. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22529. return this._postProcesses.indexOf(postProcess);
  22530. };
  22531. Camera.prototype.detachPostProcess = function (postProcess) {
  22532. var idx = this._postProcesses.indexOf(postProcess);
  22533. if (idx !== -1) {
  22534. this._postProcesses[idx] = null;
  22535. }
  22536. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22537. };
  22538. Camera.prototype.getWorldMatrix = function () {
  22539. if (this._isSynchronizedViewMatrix()) {
  22540. return this._worldMatrix;
  22541. }
  22542. // Getting the the view matrix will also compute the world matrix.
  22543. this.getViewMatrix();
  22544. return this._worldMatrix;
  22545. };
  22546. /** @hidden */
  22547. Camera.prototype._getViewMatrix = function () {
  22548. return BABYLON.Matrix.Identity();
  22549. };
  22550. Camera.prototype.getViewMatrix = function (force) {
  22551. if (!force && this._isSynchronizedViewMatrix()) {
  22552. return this._computedViewMatrix;
  22553. }
  22554. this.updateCache();
  22555. this._computedViewMatrix = this._getViewMatrix();
  22556. this._currentRenderId = this.getScene().getRenderId();
  22557. this._childRenderId = this._currentRenderId;
  22558. this._refreshFrustumPlanes = true;
  22559. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22560. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22561. }
  22562. this.onViewMatrixChangedObservable.notifyObservers(this);
  22563. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22564. return this._computedViewMatrix;
  22565. };
  22566. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22567. this._doNotComputeProjectionMatrix = true;
  22568. if (projection !== undefined) {
  22569. this._projectionMatrix = projection;
  22570. }
  22571. };
  22572. ;
  22573. Camera.prototype.unfreezeProjectionMatrix = function () {
  22574. this._doNotComputeProjectionMatrix = false;
  22575. };
  22576. ;
  22577. Camera.prototype.getProjectionMatrix = function (force) {
  22578. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22579. return this._projectionMatrix;
  22580. }
  22581. // Cache
  22582. this._cache.mode = this.mode;
  22583. this._cache.minZ = this.minZ;
  22584. this._cache.maxZ = this.maxZ;
  22585. // Matrix
  22586. this._refreshFrustumPlanes = true;
  22587. var engine = this.getEngine();
  22588. var scene = this.getScene();
  22589. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22590. this._cache.fov = this.fov;
  22591. this._cache.fovMode = this.fovMode;
  22592. this._cache.aspectRatio = engine.getAspectRatio(this);
  22593. if (this.minZ <= 0) {
  22594. this.minZ = 0.1;
  22595. }
  22596. if (scene.useRightHandedSystem) {
  22597. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22598. }
  22599. else {
  22600. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22601. }
  22602. }
  22603. else {
  22604. var halfWidth = engine.getRenderWidth() / 2.0;
  22605. var halfHeight = engine.getRenderHeight() / 2.0;
  22606. if (scene.useRightHandedSystem) {
  22607. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22608. }
  22609. else {
  22610. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22611. }
  22612. this._cache.orthoLeft = this.orthoLeft;
  22613. this._cache.orthoRight = this.orthoRight;
  22614. this._cache.orthoBottom = this.orthoBottom;
  22615. this._cache.orthoTop = this.orthoTop;
  22616. this._cache.renderWidth = engine.getRenderWidth();
  22617. this._cache.renderHeight = engine.getRenderHeight();
  22618. }
  22619. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22620. return this._projectionMatrix;
  22621. };
  22622. /**
  22623. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22624. * @returns a Matrix
  22625. */
  22626. Camera.prototype.getTransformationMatrix = function () {
  22627. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22628. return this._transformMatrix;
  22629. };
  22630. Camera.prototype.updateFrustumPlanes = function () {
  22631. if (!this._refreshFrustumPlanes) {
  22632. return;
  22633. }
  22634. this.getTransformationMatrix();
  22635. if (!this._frustumPlanes) {
  22636. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22637. }
  22638. else {
  22639. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22640. }
  22641. this._refreshFrustumPlanes = false;
  22642. };
  22643. Camera.prototype.isInFrustum = function (target) {
  22644. this.updateFrustumPlanes();
  22645. return target.isInFrustum(this._frustumPlanes);
  22646. };
  22647. Camera.prototype.isCompletelyInFrustum = function (target) {
  22648. this.updateFrustumPlanes();
  22649. return target.isCompletelyInFrustum(this._frustumPlanes);
  22650. };
  22651. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22652. if (length === void 0) { length = 100; }
  22653. if (!transform) {
  22654. transform = this.getWorldMatrix();
  22655. }
  22656. if (!origin) {
  22657. origin = this.position;
  22658. }
  22659. var forward = new BABYLON.Vector3(0, 0, 1);
  22660. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22661. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22662. return new BABYLON.Ray(origin, direction, length);
  22663. };
  22664. /**
  22665. * Releases resources associated with this node.
  22666. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22667. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22668. */
  22669. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22670. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22671. // Observables
  22672. this.onViewMatrixChangedObservable.clear();
  22673. this.onProjectionMatrixChangedObservable.clear();
  22674. this.onAfterCheckInputsObservable.clear();
  22675. this.onRestoreStateObservable.clear();
  22676. // Inputs
  22677. if (this.inputs) {
  22678. this.inputs.clear();
  22679. }
  22680. // Animations
  22681. this.getScene().stopAnimation(this);
  22682. // Remove from scene
  22683. this.getScene().removeCamera(this);
  22684. while (this._rigCameras.length > 0) {
  22685. var camera = this._rigCameras.pop();
  22686. if (camera) {
  22687. camera.dispose();
  22688. }
  22689. }
  22690. // Postprocesses
  22691. if (this._rigPostProcess) {
  22692. this._rigPostProcess.dispose(this);
  22693. this._rigPostProcess = null;
  22694. this._postProcesses = [];
  22695. }
  22696. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22697. this._rigPostProcess = null;
  22698. this._postProcesses = [];
  22699. }
  22700. else {
  22701. var i = this._postProcesses.length;
  22702. while (--i >= 0) {
  22703. var postProcess = this._postProcesses[i];
  22704. if (postProcess) {
  22705. postProcess.dispose(this);
  22706. }
  22707. }
  22708. }
  22709. // Render targets
  22710. var i = this.customRenderTargets.length;
  22711. while (--i >= 0) {
  22712. this.customRenderTargets[i].dispose();
  22713. }
  22714. this.customRenderTargets = [];
  22715. // Active Meshes
  22716. this._activeMeshes.dispose();
  22717. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22718. };
  22719. Object.defineProperty(Camera.prototype, "leftCamera", {
  22720. // ---- Camera rigs section ----
  22721. get: function () {
  22722. if (this._rigCameras.length < 1) {
  22723. return null;
  22724. }
  22725. return this._rigCameras[0];
  22726. },
  22727. enumerable: true,
  22728. configurable: true
  22729. });
  22730. Object.defineProperty(Camera.prototype, "rightCamera", {
  22731. get: function () {
  22732. if (this._rigCameras.length < 2) {
  22733. return null;
  22734. }
  22735. return this._rigCameras[1];
  22736. },
  22737. enumerable: true,
  22738. configurable: true
  22739. });
  22740. Camera.prototype.getLeftTarget = function () {
  22741. if (this._rigCameras.length < 1) {
  22742. return null;
  22743. }
  22744. return this._rigCameras[0].getTarget();
  22745. };
  22746. Camera.prototype.getRightTarget = function () {
  22747. if (this._rigCameras.length < 2) {
  22748. return null;
  22749. }
  22750. return this._rigCameras[1].getTarget();
  22751. };
  22752. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22753. if (this.cameraRigMode === mode) {
  22754. return;
  22755. }
  22756. while (this._rigCameras.length > 0) {
  22757. var camera = this._rigCameras.pop();
  22758. if (camera) {
  22759. camera.dispose();
  22760. }
  22761. }
  22762. this.cameraRigMode = mode;
  22763. this._cameraRigParams = {};
  22764. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22765. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22766. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22767. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22768. // create the rig cameras, unless none
  22769. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22770. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22771. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22772. if (leftCamera && rightCamera) {
  22773. this._rigCameras.push(leftCamera);
  22774. this._rigCameras.push(rightCamera);
  22775. }
  22776. }
  22777. switch (this.cameraRigMode) {
  22778. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22779. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22780. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22781. break;
  22782. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22783. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22784. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22785. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22786. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22787. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22788. break;
  22789. case Camera.RIG_MODE_VR:
  22790. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22791. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22792. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22793. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22794. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22795. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22796. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22797. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22798. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22799. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22800. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22801. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22802. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22803. if (metrics.compensateDistortion) {
  22804. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22805. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22806. }
  22807. break;
  22808. case Camera.RIG_MODE_WEBVR:
  22809. if (rigParams.vrDisplay) {
  22810. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22811. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22812. //Left eye
  22813. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22814. this._rigCameras[0].setCameraRigParameter("left", true);
  22815. //leaving this for future reference
  22816. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22817. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22818. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22819. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22820. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22821. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22822. this._rigCameras[0].parent = this;
  22823. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22824. //Right eye
  22825. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22826. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22827. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22828. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22829. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22830. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22831. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22832. this._rigCameras[1].parent = this;
  22833. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22834. if (Camera.UseAlternateWebVRRendering) {
  22835. this._rigCameras[1]._skipRendering = true;
  22836. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22837. }
  22838. }
  22839. break;
  22840. }
  22841. this._cascadePostProcessesToRigCams();
  22842. this.update();
  22843. };
  22844. Camera.prototype._getVRProjectionMatrix = function () {
  22845. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22846. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22847. return this._projectionMatrix;
  22848. };
  22849. Camera.prototype._updateCameraRotationMatrix = function () {
  22850. //Here for WebVR
  22851. };
  22852. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22853. //Here for WebVR
  22854. };
  22855. /**
  22856. * This function MUST be overwritten by the different WebVR cameras available.
  22857. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22858. */
  22859. Camera.prototype._getWebVRProjectionMatrix = function () {
  22860. return BABYLON.Matrix.Identity();
  22861. };
  22862. /**
  22863. * This function MUST be overwritten by the different WebVR cameras available.
  22864. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22865. */
  22866. Camera.prototype._getWebVRViewMatrix = function () {
  22867. return BABYLON.Matrix.Identity();
  22868. };
  22869. Camera.prototype.setCameraRigParameter = function (name, value) {
  22870. if (!this._cameraRigParams) {
  22871. this._cameraRigParams = {};
  22872. }
  22873. this._cameraRigParams[name] = value;
  22874. //provisionnally:
  22875. if (name === "interaxialDistance") {
  22876. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22877. }
  22878. };
  22879. /**
  22880. * needs to be overridden by children so sub has required properties to be copied
  22881. */
  22882. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22883. return null;
  22884. };
  22885. /**
  22886. * May need to be overridden by children
  22887. * @hidden
  22888. */
  22889. Camera.prototype._updateRigCameras = function () {
  22890. for (var i = 0; i < this._rigCameras.length; i++) {
  22891. this._rigCameras[i].minZ = this.minZ;
  22892. this._rigCameras[i].maxZ = this.maxZ;
  22893. this._rigCameras[i].fov = this.fov;
  22894. }
  22895. // only update viewport when ANAGLYPH
  22896. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22897. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22898. }
  22899. };
  22900. /** @hidden */
  22901. Camera.prototype._setupInputs = function () {
  22902. };
  22903. Camera.prototype.serialize = function () {
  22904. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22905. // Type
  22906. serializationObject.type = this.getClassName();
  22907. // Parent
  22908. if (this.parent) {
  22909. serializationObject.parentId = this.parent.id;
  22910. }
  22911. if (this.inputs) {
  22912. this.inputs.serialize(serializationObject);
  22913. }
  22914. // Animations
  22915. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22916. serializationObject.ranges = this.serializeAnimationRanges();
  22917. return serializationObject;
  22918. };
  22919. Camera.prototype.clone = function (name) {
  22920. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22921. };
  22922. Camera.prototype.getDirection = function (localAxis) {
  22923. var result = BABYLON.Vector3.Zero();
  22924. this.getDirectionToRef(localAxis, result);
  22925. return result;
  22926. };
  22927. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22928. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22929. };
  22930. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22931. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22932. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22933. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22934. interaxial_distance: interaxial_distance,
  22935. isStereoscopicSideBySide: isStereoscopicSideBySide
  22936. });
  22937. if (constructorFunc) {
  22938. return constructorFunc;
  22939. }
  22940. // Default to universal camera
  22941. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22942. };
  22943. Camera.prototype.computeWorldMatrix = function () {
  22944. return this.getWorldMatrix();
  22945. };
  22946. Camera.Parse = function (parsedCamera, scene) {
  22947. var type = parsedCamera.type;
  22948. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22949. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22950. // Parent
  22951. if (parsedCamera.parentId) {
  22952. camera._waitingParentId = parsedCamera.parentId;
  22953. }
  22954. //If camera has an input manager, let it parse inputs settings
  22955. if (camera.inputs) {
  22956. camera.inputs.parse(parsedCamera);
  22957. camera._setupInputs();
  22958. }
  22959. if (camera.setPosition) { // need to force position
  22960. camera.position.copyFromFloats(0, 0, 0);
  22961. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22962. }
  22963. // Target
  22964. if (parsedCamera.target) {
  22965. if (camera.setTarget) {
  22966. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22967. }
  22968. }
  22969. // Apply 3d rig, when found
  22970. if (parsedCamera.cameraRigMode) {
  22971. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22972. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22973. }
  22974. // Animations
  22975. if (parsedCamera.animations) {
  22976. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22977. var parsedAnimation = parsedCamera.animations[animationIndex];
  22978. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22979. }
  22980. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22981. }
  22982. if (parsedCamera.autoAnimate) {
  22983. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22984. }
  22985. return camera;
  22986. };
  22987. // Statics
  22988. Camera._PERSPECTIVE_CAMERA = 0;
  22989. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22990. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22991. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22992. Camera._RIG_MODE_NONE = 0;
  22993. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22994. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22995. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22996. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22997. Camera._RIG_MODE_VR = 20;
  22998. Camera._RIG_MODE_WEBVR = 21;
  22999. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23000. Camera.UseAlternateWebVRRendering = false;
  23001. __decorate([
  23002. BABYLON.serializeAsVector3()
  23003. ], Camera.prototype, "position", void 0);
  23004. __decorate([
  23005. BABYLON.serializeAsVector3()
  23006. ], Camera.prototype, "upVector", void 0);
  23007. __decorate([
  23008. BABYLON.serialize()
  23009. ], Camera.prototype, "orthoLeft", void 0);
  23010. __decorate([
  23011. BABYLON.serialize()
  23012. ], Camera.prototype, "orthoRight", void 0);
  23013. __decorate([
  23014. BABYLON.serialize()
  23015. ], Camera.prototype, "orthoBottom", void 0);
  23016. __decorate([
  23017. BABYLON.serialize()
  23018. ], Camera.prototype, "orthoTop", void 0);
  23019. __decorate([
  23020. BABYLON.serialize()
  23021. ], Camera.prototype, "fov", void 0);
  23022. __decorate([
  23023. BABYLON.serialize()
  23024. ], Camera.prototype, "minZ", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], Camera.prototype, "maxZ", void 0);
  23028. __decorate([
  23029. BABYLON.serialize()
  23030. ], Camera.prototype, "inertia", void 0);
  23031. __decorate([
  23032. BABYLON.serialize()
  23033. ], Camera.prototype, "mode", void 0);
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Camera.prototype, "layerMask", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Camera.prototype, "fovMode", void 0);
  23040. __decorate([
  23041. BABYLON.serialize()
  23042. ], Camera.prototype, "cameraRigMode", void 0);
  23043. __decorate([
  23044. BABYLON.serialize()
  23045. ], Camera.prototype, "interaxialDistance", void 0);
  23046. __decorate([
  23047. BABYLON.serialize()
  23048. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23049. return Camera;
  23050. }(BABYLON.Node));
  23051. BABYLON.Camera = Camera;
  23052. })(BABYLON || (BABYLON = {}));
  23053. //# sourceMappingURL=babylon.camera.js.map
  23054. var BABYLON;
  23055. (function (BABYLON) {
  23056. var RenderingManager = /** @class */ (function () {
  23057. function RenderingManager(scene) {
  23058. /**
  23059. * @hidden
  23060. */
  23061. this._useSceneAutoClearSetup = false;
  23062. this._renderingGroups = new Array();
  23063. this._autoClearDepthStencil = {};
  23064. this._customOpaqueSortCompareFn = {};
  23065. this._customAlphaTestSortCompareFn = {};
  23066. this._customTransparentSortCompareFn = {};
  23067. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23068. this._scene = scene;
  23069. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23070. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23071. }
  23072. }
  23073. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23074. if (depth === void 0) { depth = true; }
  23075. if (stencil === void 0) { stencil = true; }
  23076. if (this._depthStencilBufferAlreadyCleaned) {
  23077. return;
  23078. }
  23079. this._scene.getEngine().clear(null, false, depth, stencil);
  23080. this._depthStencilBufferAlreadyCleaned = true;
  23081. };
  23082. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23083. // Update the observable context (not null as it only goes away on dispose)
  23084. var info = this._renderingGroupInfo;
  23085. info.scene = this._scene;
  23086. info.camera = this._scene.activeCamera;
  23087. // Dispatch sprites
  23088. if (renderSprites) {
  23089. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23090. var manager = this._scene.spriteManagers[index];
  23091. this.dispatchSprites(manager);
  23092. }
  23093. }
  23094. // Render
  23095. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23096. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23097. var renderingGroup = this._renderingGroups[index];
  23098. if (!renderingGroup)
  23099. continue;
  23100. var renderingGroupMask = Math.pow(2, index);
  23101. info.renderingGroupId = index;
  23102. // Before Observable
  23103. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23104. // Clear depth/stencil if needed
  23105. if (RenderingManager.AUTOCLEAR) {
  23106. var autoClear = this._useSceneAutoClearSetup ?
  23107. this._scene.getAutoClearDepthStencilSetup(index) :
  23108. this._autoClearDepthStencil[index];
  23109. if (autoClear && autoClear.autoClear) {
  23110. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23111. }
  23112. }
  23113. // Render
  23114. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23115. var step = _a[_i];
  23116. step.action(index);
  23117. }
  23118. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23119. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23120. var step = _c[_b];
  23121. step.action(index);
  23122. }
  23123. // After Observable
  23124. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23125. }
  23126. };
  23127. RenderingManager.prototype.reset = function () {
  23128. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23129. var renderingGroup = this._renderingGroups[index];
  23130. if (renderingGroup) {
  23131. renderingGroup.prepare();
  23132. }
  23133. }
  23134. };
  23135. RenderingManager.prototype.dispose = function () {
  23136. this.freeRenderingGroups();
  23137. this._renderingGroups.length = 0;
  23138. this._renderingGroupInfo = null;
  23139. };
  23140. /**
  23141. * Clear the info related to rendering groups preventing retention points during dispose.
  23142. */
  23143. RenderingManager.prototype.freeRenderingGroups = function () {
  23144. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23145. var renderingGroup = this._renderingGroups[index];
  23146. if (renderingGroup) {
  23147. renderingGroup.dispose();
  23148. }
  23149. }
  23150. };
  23151. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23152. if (this._renderingGroups[renderingGroupId] === undefined) {
  23153. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23154. }
  23155. };
  23156. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23157. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23158. this._prepareRenderingGroup(renderingGroupId);
  23159. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23160. };
  23161. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23162. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23163. this._prepareRenderingGroup(renderingGroupId);
  23164. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23165. };
  23166. /**
  23167. * @param subMesh The submesh to dispatch
  23168. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23169. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23170. */
  23171. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23172. if (mesh === undefined) {
  23173. mesh = subMesh.getMesh();
  23174. }
  23175. var renderingGroupId = mesh.renderingGroupId || 0;
  23176. this._prepareRenderingGroup(renderingGroupId);
  23177. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23178. };
  23179. /**
  23180. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23181. * This allowed control for front to back rendering or reversly depending of the special needs.
  23182. *
  23183. * @param renderingGroupId The rendering group id corresponding to its index
  23184. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23185. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23186. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23187. */
  23188. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23189. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23190. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23191. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23192. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23193. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23194. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23195. if (this._renderingGroups[renderingGroupId]) {
  23196. var group = this._renderingGroups[renderingGroupId];
  23197. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23198. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23199. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23200. }
  23201. };
  23202. /**
  23203. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23204. *
  23205. * @param renderingGroupId The rendering group id corresponding to its index
  23206. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23207. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23208. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23209. */
  23210. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23211. if (depth === void 0) { depth = true; }
  23212. if (stencil === void 0) { stencil = true; }
  23213. this._autoClearDepthStencil[renderingGroupId] = {
  23214. autoClear: autoClearDepthStencil,
  23215. depth: depth,
  23216. stencil: stencil
  23217. };
  23218. };
  23219. /**
  23220. * Gets the current auto clear configuration for one rendering group of the rendering
  23221. * manager.
  23222. * @param index the rendering group index to get the information for
  23223. * @returns The auto clear setup for the requested rendering group
  23224. */
  23225. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23226. return this._autoClearDepthStencil[index];
  23227. };
  23228. /**
  23229. * The max id used for rendering groups (not included)
  23230. */
  23231. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23232. /**
  23233. * The min id used for rendering groups (included)
  23234. */
  23235. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23236. /**
  23237. * Used to globally prevent autoclearing scenes.
  23238. */
  23239. RenderingManager.AUTOCLEAR = true;
  23240. return RenderingManager;
  23241. }());
  23242. BABYLON.RenderingManager = RenderingManager;
  23243. })(BABYLON || (BABYLON = {}));
  23244. //# sourceMappingURL=babylon.renderingManager.js.map
  23245. var BABYLON;
  23246. (function (BABYLON) {
  23247. var RenderingGroup = /** @class */ (function () {
  23248. /**
  23249. * Creates a new rendering group.
  23250. * @param index The rendering group index
  23251. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23252. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23253. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23254. */
  23255. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23256. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23257. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23258. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23259. this.index = index;
  23260. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23261. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23262. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23263. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23264. this._particleSystems = new BABYLON.SmartArray(256);
  23265. this._spriteManagers = new BABYLON.SmartArray(256);
  23266. this._edgesRenderers = new BABYLON.SmartArray(16);
  23267. this._scene = scene;
  23268. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23269. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23270. this.transparentSortCompareFn = transparentSortCompareFn;
  23271. }
  23272. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23273. /**
  23274. * Set the opaque sort comparison function.
  23275. * If null the sub meshes will be render in the order they were created
  23276. */
  23277. set: function (value) {
  23278. this._opaqueSortCompareFn = value;
  23279. if (value) {
  23280. this._renderOpaque = this.renderOpaqueSorted;
  23281. }
  23282. else {
  23283. this._renderOpaque = RenderingGroup.renderUnsorted;
  23284. }
  23285. },
  23286. enumerable: true,
  23287. configurable: true
  23288. });
  23289. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23290. /**
  23291. * Set the alpha test sort comparison function.
  23292. * If null the sub meshes will be render in the order they were created
  23293. */
  23294. set: function (value) {
  23295. this._alphaTestSortCompareFn = value;
  23296. if (value) {
  23297. this._renderAlphaTest = this.renderAlphaTestSorted;
  23298. }
  23299. else {
  23300. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23301. }
  23302. },
  23303. enumerable: true,
  23304. configurable: true
  23305. });
  23306. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23307. /**
  23308. * Set the transparent sort comparison function.
  23309. * If null the sub meshes will be render in the order they were created
  23310. */
  23311. set: function (value) {
  23312. if (value) {
  23313. this._transparentSortCompareFn = value;
  23314. }
  23315. else {
  23316. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23317. }
  23318. this._renderTransparent = this.renderTransparentSorted;
  23319. },
  23320. enumerable: true,
  23321. configurable: true
  23322. });
  23323. /**
  23324. * Render all the sub meshes contained in the group.
  23325. * @param customRenderFunction Used to override the default render behaviour of the group.
  23326. * @returns true if rendered some submeshes.
  23327. */
  23328. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23329. if (customRenderFunction) {
  23330. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23331. return;
  23332. }
  23333. var engine = this._scene.getEngine();
  23334. // Depth only
  23335. if (this._depthOnlySubMeshes.length !== 0) {
  23336. engine.setColorWrite(false);
  23337. this._renderAlphaTest(this._depthOnlySubMeshes);
  23338. engine.setColorWrite(true);
  23339. }
  23340. // Opaque
  23341. if (this._opaqueSubMeshes.length !== 0) {
  23342. this._renderOpaque(this._opaqueSubMeshes);
  23343. }
  23344. // Alpha test
  23345. if (this._alphaTestSubMeshes.length !== 0) {
  23346. this._renderAlphaTest(this._alphaTestSubMeshes);
  23347. }
  23348. var stencilState = engine.getStencilBuffer();
  23349. engine.setStencilBuffer(false);
  23350. // Sprites
  23351. if (renderSprites) {
  23352. this._renderSprites();
  23353. }
  23354. // Particles
  23355. if (renderParticles) {
  23356. this._renderParticles(activeMeshes);
  23357. }
  23358. if (this.onBeforeTransparentRendering) {
  23359. this.onBeforeTransparentRendering();
  23360. }
  23361. // Transparent
  23362. if (this._transparentSubMeshes.length !== 0) {
  23363. this._renderTransparent(this._transparentSubMeshes);
  23364. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23365. }
  23366. // Set back stencil to false in case it changes before the edge renderer.
  23367. engine.setStencilBuffer(false);
  23368. // Edges
  23369. if (this._edgesRenderers.length) {
  23370. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23371. this._edgesRenderers.data[edgesRendererIndex].render();
  23372. }
  23373. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23374. }
  23375. // Restore Stencil state.
  23376. engine.setStencilBuffer(stencilState);
  23377. };
  23378. /**
  23379. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23380. * @param subMeshes The submeshes to render
  23381. */
  23382. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23383. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23384. };
  23385. /**
  23386. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23387. * @param subMeshes The submeshes to render
  23388. */
  23389. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23390. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23391. };
  23392. /**
  23393. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23394. * @param subMeshes The submeshes to render
  23395. */
  23396. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23397. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23398. };
  23399. /**
  23400. * Renders the submeshes in a specified order.
  23401. * @param subMeshes The submeshes to sort before render
  23402. * @param sortCompareFn The comparison function use to sort
  23403. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23404. * @param transparent Specifies to activate blending if true
  23405. */
  23406. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23407. var subIndex = 0;
  23408. var subMesh;
  23409. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23410. for (; subIndex < subMeshes.length; subIndex++) {
  23411. subMesh = subMeshes.data[subIndex];
  23412. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23413. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23414. }
  23415. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23416. if (sortCompareFn) {
  23417. sortedArray.sort(sortCompareFn);
  23418. }
  23419. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23420. subMesh = sortedArray[subIndex];
  23421. if (transparent) {
  23422. var material = subMesh.getMaterial();
  23423. if (material && material.needDepthPrePass) {
  23424. var engine = material.getScene().getEngine();
  23425. engine.setColorWrite(false);
  23426. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23427. subMesh.render(false);
  23428. engine.setColorWrite(true);
  23429. }
  23430. }
  23431. subMesh.render(transparent);
  23432. }
  23433. };
  23434. /**
  23435. * Renders the submeshes in the order they were dispatched (no sort applied).
  23436. * @param subMeshes The submeshes to render
  23437. */
  23438. RenderingGroup.renderUnsorted = function (subMeshes) {
  23439. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23440. var submesh = subMeshes.data[subIndex];
  23441. submesh.render(false);
  23442. }
  23443. };
  23444. /**
  23445. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23446. * are rendered back to front if in the same alpha index.
  23447. *
  23448. * @param a The first submesh
  23449. * @param b The second submesh
  23450. * @returns The result of the comparison
  23451. */
  23452. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23453. // Alpha index first
  23454. if (a._alphaIndex > b._alphaIndex) {
  23455. return 1;
  23456. }
  23457. if (a._alphaIndex < b._alphaIndex) {
  23458. return -1;
  23459. }
  23460. // Then distance to camera
  23461. return RenderingGroup.backToFrontSortCompare(a, b);
  23462. };
  23463. /**
  23464. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23465. * are rendered back to front.
  23466. *
  23467. * @param a The first submesh
  23468. * @param b The second submesh
  23469. * @returns The result of the comparison
  23470. */
  23471. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23472. // Then distance to camera
  23473. if (a._distanceToCamera < b._distanceToCamera) {
  23474. return 1;
  23475. }
  23476. if (a._distanceToCamera > b._distanceToCamera) {
  23477. return -1;
  23478. }
  23479. return 0;
  23480. };
  23481. /**
  23482. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23483. * are rendered front to back (prevent overdraw).
  23484. *
  23485. * @param a The first submesh
  23486. * @param b The second submesh
  23487. * @returns The result of the comparison
  23488. */
  23489. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23490. // Then distance to camera
  23491. if (a._distanceToCamera < b._distanceToCamera) {
  23492. return -1;
  23493. }
  23494. if (a._distanceToCamera > b._distanceToCamera) {
  23495. return 1;
  23496. }
  23497. return 0;
  23498. };
  23499. /**
  23500. * Resets the different lists of submeshes to prepare a new frame.
  23501. */
  23502. RenderingGroup.prototype.prepare = function () {
  23503. this._opaqueSubMeshes.reset();
  23504. this._transparentSubMeshes.reset();
  23505. this._alphaTestSubMeshes.reset();
  23506. this._depthOnlySubMeshes.reset();
  23507. this._particleSystems.reset();
  23508. this._spriteManagers.reset();
  23509. this._edgesRenderers.reset();
  23510. };
  23511. RenderingGroup.prototype.dispose = function () {
  23512. this._opaqueSubMeshes.dispose();
  23513. this._transparentSubMeshes.dispose();
  23514. this._alphaTestSubMeshes.dispose();
  23515. this._depthOnlySubMeshes.dispose();
  23516. this._particleSystems.dispose();
  23517. this._spriteManagers.dispose();
  23518. this._edgesRenderers.dispose();
  23519. };
  23520. /**
  23521. * Inserts the submesh in its correct queue depending on its material.
  23522. * @param subMesh The submesh to dispatch
  23523. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23524. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23525. */
  23526. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23527. // Get mesh and materials if not provided
  23528. if (mesh === undefined) {
  23529. mesh = subMesh.getMesh();
  23530. }
  23531. if (material === undefined) {
  23532. material = subMesh.getMaterial();
  23533. }
  23534. if (material === null || material === undefined) {
  23535. return;
  23536. }
  23537. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23538. this._transparentSubMeshes.push(subMesh);
  23539. }
  23540. else if (material.needAlphaTesting()) { // Alpha test
  23541. if (material.needDepthPrePass) {
  23542. this._depthOnlySubMeshes.push(subMesh);
  23543. }
  23544. this._alphaTestSubMeshes.push(subMesh);
  23545. }
  23546. else {
  23547. if (material.needDepthPrePass) {
  23548. this._depthOnlySubMeshes.push(subMesh);
  23549. }
  23550. this._opaqueSubMeshes.push(subMesh); // Opaque
  23551. }
  23552. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23553. this._edgesRenderers.push(mesh._edgesRenderer);
  23554. }
  23555. };
  23556. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23557. this._spriteManagers.push(spriteManager);
  23558. };
  23559. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23560. this._particleSystems.push(particleSystem);
  23561. };
  23562. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23563. if (this._particleSystems.length === 0) {
  23564. return;
  23565. }
  23566. // Particles
  23567. var activeCamera = this._scene.activeCamera;
  23568. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23569. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23570. var particleSystem = this._particleSystems.data[particleIndex];
  23571. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23572. continue;
  23573. }
  23574. var emitter = particleSystem.emitter;
  23575. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23576. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23577. }
  23578. }
  23579. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23580. };
  23581. RenderingGroup.prototype._renderSprites = function () {
  23582. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23583. return;
  23584. }
  23585. // Sprites
  23586. var activeCamera = this._scene.activeCamera;
  23587. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23588. for (var id = 0; id < this._spriteManagers.length; id++) {
  23589. var spriteManager = this._spriteManagers.data[id];
  23590. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23591. spriteManager.render();
  23592. }
  23593. }
  23594. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23595. };
  23596. return RenderingGroup;
  23597. }());
  23598. BABYLON.RenderingGroup = RenderingGroup;
  23599. })(BABYLON || (BABYLON = {}));
  23600. //# sourceMappingURL=babylon.renderingGroup.js.map
  23601. var BABYLON;
  23602. (function (BABYLON) {
  23603. /**
  23604. * Groups all the scene component constants in one place to ease maintenance.
  23605. * @hidden
  23606. */
  23607. var SceneComponentConstants = /** @class */ (function () {
  23608. function SceneComponentConstants() {
  23609. }
  23610. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23611. SceneComponentConstants.NAME_LAYER = "Layer";
  23612. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23613. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23614. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23615. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23616. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23617. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23618. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23619. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23620. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23621. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23622. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23623. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23624. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23625. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23626. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23627. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23628. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23629. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23630. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23631. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23632. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23633. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23634. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23635. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 0;
  23636. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 1;
  23637. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 2;
  23638. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23639. return SceneComponentConstants;
  23640. }());
  23641. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23642. /**
  23643. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23644. * @hidden
  23645. */
  23646. var Stage = /** @class */ (function (_super) {
  23647. __extends(Stage, _super);
  23648. /**
  23649. * Hide ctor from the rest of the world.
  23650. * @param items The items to add.
  23651. */
  23652. function Stage(items) {
  23653. return _super.apply(this, items) || this;
  23654. }
  23655. /**
  23656. * Creates a new Stage.
  23657. * @returns A new instance of a Stage
  23658. */
  23659. Stage.Create = function () {
  23660. return Object.create(Stage.prototype);
  23661. };
  23662. /**
  23663. * Registers a step in an ordered way in the targeted stage.
  23664. * @param index Defines the position to register the step in
  23665. * @param component Defines the component attached to the step
  23666. * @param action Defines the action to launch during the step
  23667. */
  23668. Stage.prototype.registerStep = function (index, component, action) {
  23669. var i = 0;
  23670. var maxIndex = Number.MAX_VALUE;
  23671. for (; i < this.length && i < maxIndex; i++) {
  23672. var step = this[i];
  23673. maxIndex = step.index;
  23674. }
  23675. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23676. };
  23677. /**
  23678. * Clears all the steps from the stage.
  23679. */
  23680. Stage.prototype.clear = function () {
  23681. this.length = 0;
  23682. };
  23683. return Stage;
  23684. }(Array));
  23685. BABYLON.Stage = Stage;
  23686. })(BABYLON || (BABYLON = {}));
  23687. //# sourceMappingURL=babylon.sceneComponent.js.map
  23688. var BABYLON;
  23689. (function (BABYLON) {
  23690. /**
  23691. * Base class of the scene acting as a container for the different elements composing a scene.
  23692. * This class is dynamically extended by the different components of the scene increasing
  23693. * flexibility and reducing coupling
  23694. */
  23695. var AbstractScene = /** @class */ (function () {
  23696. function AbstractScene() {
  23697. /** All of the cameras added to this scene
  23698. * @see http://doc.babylonjs.com/babylon101/cameras
  23699. */
  23700. this.cameras = new Array();
  23701. /**
  23702. * All of the lights added to this scene
  23703. * @see http://doc.babylonjs.com/babylon101/lights
  23704. */
  23705. this.lights = new Array();
  23706. /**
  23707. * All of the (abstract) meshes added to this scene
  23708. */
  23709. this.meshes = new Array();
  23710. /**
  23711. * The list of skeletons added to the scene
  23712. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23713. */
  23714. this.skeletons = new Array();
  23715. /**
  23716. * All of the particle systems added to this scene
  23717. * @see http://doc.babylonjs.com/babylon101/particles
  23718. */
  23719. this.particleSystems = new Array();
  23720. /**
  23721. * Gets a list of Animations associated with the scene
  23722. */
  23723. this.animations = [];
  23724. /**
  23725. * All of the animation groups added to this scene
  23726. * @see http://doc.babylonjs.com/how_to/group
  23727. */
  23728. this.animationGroups = new Array();
  23729. /**
  23730. * All of the multi-materials added to this scene
  23731. * @see http://doc.babylonjs.com/how_to/multi_materials
  23732. */
  23733. this.multiMaterials = new Array();
  23734. /**
  23735. * All of the materials added to this scene
  23736. * @see http://doc.babylonjs.com/babylon101/materials
  23737. */
  23738. this.materials = new Array();
  23739. /**
  23740. * The list of morph target managers added to the scene
  23741. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23742. */
  23743. this.morphTargetManagers = new Array();
  23744. /**
  23745. * The list of geometries used in the scene.
  23746. */
  23747. this.geometries = new Array();
  23748. /**
  23749. * All of the tranform nodes added to this scene
  23750. * @see http://doc.babylonjs.com/how_to/transformnode
  23751. */
  23752. this.transformNodes = new Array();
  23753. /**
  23754. * ActionManagers available on the scene.
  23755. */
  23756. this.actionManagers = new Array();
  23757. /**
  23758. * Sounds to keep.
  23759. */
  23760. this.sounds = new Array();
  23761. /**
  23762. * Textures to keep.
  23763. */
  23764. this.textures = new Array();
  23765. }
  23766. /**
  23767. * Adds a parser in the list of available ones
  23768. * @param name Defines the name of the parser
  23769. * @param parser Defines the parser to add
  23770. */
  23771. AbstractScene.AddParser = function (name, parser) {
  23772. this._BabylonFileParsers[name] = parser;
  23773. };
  23774. /**
  23775. * Gets a general parser from the list of avaialble ones
  23776. * @param name Defines the name of the parser
  23777. * @returns the requested parser or null
  23778. */
  23779. AbstractScene.GetParser = function (name) {
  23780. if (this._BabylonFileParsers[name]) {
  23781. return this._BabylonFileParsers[name];
  23782. }
  23783. return null;
  23784. };
  23785. /**
  23786. * Adds n individual parser in the list of available ones
  23787. * @param name Defines the name of the parser
  23788. * @param parser Defines the parser to add
  23789. */
  23790. AbstractScene.AddIndividualParser = function (name, parser) {
  23791. this._IndividualBabylonFileParsers[name] = parser;
  23792. };
  23793. /**
  23794. * Gets an individual parser from the list of avaialble ones
  23795. * @param name Defines the name of the parser
  23796. * @returns the requested parser or null
  23797. */
  23798. AbstractScene.GetIndividualParser = function (name) {
  23799. if (this._IndividualBabylonFileParsers[name]) {
  23800. return this._IndividualBabylonFileParsers[name];
  23801. }
  23802. return null;
  23803. };
  23804. /**
  23805. * Parser json data and populate both a scene and its associated container object
  23806. * @param jsonData Defines the data to parse
  23807. * @param scene Defines the scene to parse the data for
  23808. * @param container Defines the container attached to the parsing sequence
  23809. * @param rootUrl Defines the root url of the data
  23810. */
  23811. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23812. for (var parserName in this._BabylonFileParsers) {
  23813. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23814. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23815. }
  23816. }
  23817. };
  23818. /**
  23819. * Stores the list of available parsers in the application.
  23820. */
  23821. AbstractScene._BabylonFileParsers = {};
  23822. /**
  23823. * Stores the list of available individual parsers in the application.
  23824. */
  23825. AbstractScene._IndividualBabylonFileParsers = {};
  23826. return AbstractScene;
  23827. }());
  23828. BABYLON.AbstractScene = AbstractScene;
  23829. })(BABYLON || (BABYLON = {}));
  23830. //# sourceMappingURL=babylon.abstractScene.js.map
  23831. var BABYLON;
  23832. (function (BABYLON) {
  23833. /** @hidden */
  23834. var ClickInfo = /** @class */ (function () {
  23835. function ClickInfo() {
  23836. this._singleClick = false;
  23837. this._doubleClick = false;
  23838. this._hasSwiped = false;
  23839. this._ignore = false;
  23840. }
  23841. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23842. get: function () {
  23843. return this._singleClick;
  23844. },
  23845. set: function (b) {
  23846. this._singleClick = b;
  23847. },
  23848. enumerable: true,
  23849. configurable: true
  23850. });
  23851. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23852. get: function () {
  23853. return this._doubleClick;
  23854. },
  23855. set: function (b) {
  23856. this._doubleClick = b;
  23857. },
  23858. enumerable: true,
  23859. configurable: true
  23860. });
  23861. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23862. get: function () {
  23863. return this._hasSwiped;
  23864. },
  23865. set: function (b) {
  23866. this._hasSwiped = b;
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23872. get: function () {
  23873. return this._ignore;
  23874. },
  23875. set: function (b) {
  23876. this._ignore = b;
  23877. },
  23878. enumerable: true,
  23879. configurable: true
  23880. });
  23881. return ClickInfo;
  23882. }());
  23883. /**
  23884. * This class is used by the onRenderingGroupObservable
  23885. */
  23886. var RenderingGroupInfo = /** @class */ (function () {
  23887. function RenderingGroupInfo() {
  23888. }
  23889. return RenderingGroupInfo;
  23890. }());
  23891. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23892. /**
  23893. * Represents a scene to be rendered by the engine.
  23894. * @see http://doc.babylonjs.com/features/scene
  23895. */
  23896. var Scene = /** @class */ (function (_super) {
  23897. __extends(Scene, _super);
  23898. /**
  23899. * Creates a new Scene
  23900. * @param engine defines the engine to use to render this scene
  23901. */
  23902. function Scene(engine) {
  23903. var _this = _super.call(this) || this;
  23904. // Members
  23905. /**
  23906. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23907. */
  23908. _this.autoClear = true;
  23909. /**
  23910. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23911. */
  23912. _this.autoClearDepthAndStencil = true;
  23913. /**
  23914. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23915. */
  23916. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23917. /**
  23918. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23919. */
  23920. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23921. _this._forceWireframe = false;
  23922. _this._forcePointsCloud = false;
  23923. /**
  23924. * Gets or sets a boolean indicating if animations are enabled
  23925. */
  23926. _this.animationsEnabled = true;
  23927. _this._animationPropertiesOverride = null;
  23928. /**
  23929. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23930. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23931. */
  23932. _this.useConstantAnimationDeltaTime = false;
  23933. /**
  23934. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23935. * Please note that it requires to run a ray cast through the scene on every frame
  23936. */
  23937. _this.constantlyUpdateMeshUnderPointer = false;
  23938. /**
  23939. * Defines the HTML cursor to use when hovering over interactive elements
  23940. */
  23941. _this.hoverCursor = "pointer";
  23942. /**
  23943. * Defines the HTML default cursor to use (empty by default)
  23944. */
  23945. _this.defaultCursor = "";
  23946. /**
  23947. * This is used to call preventDefault() on pointer down
  23948. * in order to block unwanted artifacts like system double clicks
  23949. */
  23950. _this.preventDefaultOnPointerDown = true;
  23951. // Metadata
  23952. /**
  23953. * Gets or sets user defined metadata
  23954. */
  23955. _this.metadata = null;
  23956. /**
  23957. * Use this array to add regular expressions used to disable offline support for specific urls
  23958. */
  23959. _this.disableOfflineSupportExceptionRules = new Array();
  23960. /**
  23961. * An event triggered when the scene is disposed.
  23962. */
  23963. _this.onDisposeObservable = new BABYLON.Observable();
  23964. _this._onDisposeObserver = null;
  23965. /**
  23966. * An event triggered before rendering the scene (right after animations and physics)
  23967. */
  23968. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23969. _this._onBeforeRenderObserver = null;
  23970. /**
  23971. * An event triggered after rendering the scene
  23972. */
  23973. _this.onAfterRenderObservable = new BABYLON.Observable();
  23974. _this._onAfterRenderObserver = null;
  23975. /**
  23976. * An event triggered before animating the scene
  23977. */
  23978. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23979. /**
  23980. * An event triggered after animations processing
  23981. */
  23982. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23983. /**
  23984. * An event triggered before draw calls are ready to be sent
  23985. */
  23986. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23987. /**
  23988. * An event triggered after draw calls have been sent
  23989. */
  23990. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23991. /**
  23992. * An event triggered when physic simulation is about to be run
  23993. */
  23994. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23995. /**
  23996. * An event triggered when physic simulation has been done
  23997. */
  23998. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23999. /**
  24000. * An event triggered when the scene is ready
  24001. */
  24002. _this.onReadyObservable = new BABYLON.Observable();
  24003. /**
  24004. * An event triggered before rendering a camera
  24005. */
  24006. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24007. _this._onBeforeCameraRenderObserver = null;
  24008. /**
  24009. * An event triggered after rendering a camera
  24010. */
  24011. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24012. _this._onAfterCameraRenderObserver = null;
  24013. /**
  24014. * An event triggered when active meshes evaluation is about to start
  24015. */
  24016. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24017. /**
  24018. * An event triggered when active meshes evaluation is done
  24019. */
  24020. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24021. /**
  24022. * An event triggered when particles rendering is about to start
  24023. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24024. */
  24025. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24026. /**
  24027. * An event triggered when particles rendering is done
  24028. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24029. */
  24030. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24031. /**
  24032. * An event triggered when sprites rendering is about to start
  24033. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24034. */
  24035. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered when sprites rendering is done
  24038. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24039. */
  24040. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24043. */
  24044. _this.onDataLoadedObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when a camera is created
  24047. */
  24048. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24049. /**
  24050. * An event triggered when a camera is removed
  24051. */
  24052. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24053. /**
  24054. * An event triggered when a light is created
  24055. */
  24056. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when a light is removed
  24059. */
  24060. _this.onLightRemovedObservable = new BABYLON.Observable();
  24061. /**
  24062. * An event triggered when a geometry is created
  24063. */
  24064. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when a geometry is removed
  24067. */
  24068. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when a transform node is created
  24071. */
  24072. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when a transform node is removed
  24075. */
  24076. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24077. /**
  24078. * An event triggered when a mesh is created
  24079. */
  24080. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24081. /**
  24082. * An event triggered when a mesh is removed
  24083. */
  24084. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24085. /**
  24086. * An event triggered when render targets are about to be rendered
  24087. * Can happen multiple times per frame.
  24088. */
  24089. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24090. /**
  24091. * An event triggered when render targets were rendered.
  24092. * Can happen multiple times per frame.
  24093. */
  24094. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24095. /**
  24096. * An event triggered before calculating deterministic simulation step
  24097. */
  24098. _this.onBeforeStepObservable = new BABYLON.Observable();
  24099. /**
  24100. * An event triggered after calculating deterministic simulation step
  24101. */
  24102. _this.onAfterStepObservable = new BABYLON.Observable();
  24103. /**
  24104. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24105. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24106. * 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)
  24107. */
  24108. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24109. /**
  24110. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24111. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24112. * 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)
  24113. */
  24114. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24115. // Animations
  24116. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24117. /**
  24118. * 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).
  24119. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24120. */
  24121. _this.onPrePointerObservable = new BABYLON.Observable();
  24122. /**
  24123. * Observable event triggered each time an input event is received from the rendering canvas
  24124. */
  24125. _this.onPointerObservable = new BABYLON.Observable();
  24126. _this._meshPickProceed = false;
  24127. _this._currentPickResult = null;
  24128. _this._previousPickResult = null;
  24129. _this._totalPointersPressed = 0;
  24130. _this._doubleClickOccured = false;
  24131. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24132. _this.cameraToUseForPointers = null;
  24133. _this._pointerX = 0;
  24134. _this._pointerY = 0;
  24135. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24136. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24137. _this._startingPointerTime = 0;
  24138. _this._previousStartingPointerTime = 0;
  24139. _this._pointerCaptures = {};
  24140. // Deterministic lockstep
  24141. _this._timeAccumulator = 0;
  24142. _this._currentStepId = 0;
  24143. _this._currentInternalStep = 0;
  24144. // Keyboard
  24145. /**
  24146. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24147. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24148. */
  24149. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24150. /**
  24151. * Observable event triggered each time an keyboard event is received from the hosting window
  24152. */
  24153. _this.onKeyboardObservable = new BABYLON.Observable();
  24154. // Coordinates system
  24155. _this._useRightHandedSystem = false;
  24156. // Fog
  24157. _this._fogEnabled = true;
  24158. _this._fogMode = Scene.FOGMODE_NONE;
  24159. /**
  24160. * Gets or sets the fog color to use
  24161. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24162. */
  24163. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24164. /**
  24165. * Gets or sets the fog density to use
  24166. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24167. */
  24168. _this.fogDensity = 0.1;
  24169. /**
  24170. * Gets or sets the fog start distance to use
  24171. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24172. */
  24173. _this.fogStart = 0;
  24174. /**
  24175. * Gets or sets the fog end distance to use
  24176. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24177. */
  24178. _this.fogEnd = 1000.0;
  24179. // Lights
  24180. _this._shadowsEnabled = true;
  24181. _this._lightsEnabled = true;
  24182. /** All of the active cameras added to this scene. */
  24183. _this.activeCameras = new Array();
  24184. // Textures
  24185. _this._texturesEnabled = true;
  24186. // Particles
  24187. /**
  24188. * Gets or sets a boolean indicating if particles are enabled on this scene
  24189. */
  24190. _this.particlesEnabled = true;
  24191. // Sprites
  24192. /**
  24193. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24194. */
  24195. _this.spritesEnabled = true;
  24196. /**
  24197. * All of the sprite managers added to this scene
  24198. * @see http://doc.babylonjs.com/babylon101/sprites
  24199. */
  24200. _this.spriteManagers = new Array();
  24201. // Skeletons
  24202. _this._skeletonsEnabled = true;
  24203. // Lens flares
  24204. /**
  24205. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24206. */
  24207. _this.lensFlaresEnabled = true;
  24208. // Collisions
  24209. /**
  24210. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24211. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24212. */
  24213. _this.collisionsEnabled = true;
  24214. /**
  24215. * Defines the gravity applied to this scene (used only for collisions)
  24216. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24217. */
  24218. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24219. // Postprocesses
  24220. /**
  24221. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24222. */
  24223. _this.postProcessesEnabled = true;
  24224. /**
  24225. * The list of postprocesses added to the scene
  24226. */
  24227. _this.postProcesses = new Array();
  24228. // Customs render targets
  24229. /**
  24230. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24231. */
  24232. _this.renderTargetsEnabled = true;
  24233. /**
  24234. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24235. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24236. */
  24237. _this.dumpNextRenderTargets = false;
  24238. /**
  24239. * The list of user defined render targets added to the scene
  24240. */
  24241. _this.customRenderTargets = new Array();
  24242. /**
  24243. * Gets the list of meshes imported to the scene through SceneLoader
  24244. */
  24245. _this.importedMeshesFiles = new Array();
  24246. // Probes
  24247. /**
  24248. * Gets or sets a boolean indicating if probes are enabled on this scene
  24249. */
  24250. _this.probesEnabled = true;
  24251. /**
  24252. * The list of reflection probes added to the scene
  24253. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24254. */
  24255. _this.reflectionProbes = new Array();
  24256. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24257. // Procedural textures
  24258. /**
  24259. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24260. */
  24261. _this.proceduralTexturesEnabled = true;
  24262. /**
  24263. * The list of procedural textures added to the scene
  24264. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24265. */
  24266. _this.proceduralTextures = new Array();
  24267. /**
  24268. * The list of sound tracks added to the scene
  24269. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24270. */
  24271. _this.soundTracks = new Array();
  24272. _this._audioEnabled = true;
  24273. _this._headphone = false;
  24274. // Performance counters
  24275. _this._totalVertices = new BABYLON.PerfCounter();
  24276. /** @hidden */
  24277. _this._activeIndices = new BABYLON.PerfCounter();
  24278. /** @hidden */
  24279. _this._activeParticles = new BABYLON.PerfCounter();
  24280. /** @hidden */
  24281. _this._activeBones = new BABYLON.PerfCounter();
  24282. _this._animationTime = 0;
  24283. /**
  24284. * Gets or sets a general scale for animation speed
  24285. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24286. */
  24287. _this.animationTimeScale = 1;
  24288. _this._renderId = 0;
  24289. _this._executeWhenReadyTimeoutId = -1;
  24290. _this._intermediateRendering = false;
  24291. _this._viewUpdateFlag = -1;
  24292. _this._projectionUpdateFlag = -1;
  24293. _this._alternateViewUpdateFlag = -1;
  24294. _this._alternateProjectionUpdateFlag = -1;
  24295. /** @hidden */
  24296. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24297. _this._activeRequests = new Array();
  24298. _this._pendingData = new Array();
  24299. _this._isDisposed = false;
  24300. /**
  24301. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24302. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24303. */
  24304. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24305. _this._activeMeshes = new BABYLON.SmartArray(256);
  24306. _this._processedMaterials = new BABYLON.SmartArray(256);
  24307. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24308. /** @hidden */
  24309. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24310. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24311. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24312. /** @hidden */
  24313. _this._activeAnimatables = new Array();
  24314. _this._transformMatrix = BABYLON.Matrix.Zero();
  24315. _this._useAlternateCameraConfiguration = false;
  24316. _this._alternateRendering = false;
  24317. /**
  24318. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24319. * This is useful if there are more lights that the maximum simulteanous authorized
  24320. */
  24321. _this.requireLightSorting = false;
  24322. /**
  24323. * @hidden
  24324. * Backing store of defined scene components.
  24325. */
  24326. _this._components = [];
  24327. /**
  24328. * @hidden
  24329. * Backing store of defined scene components.
  24330. */
  24331. _this._serializableComponents = [];
  24332. /**
  24333. * List of components to register on the next registration step.
  24334. */
  24335. _this._transientComponents = [];
  24336. /**
  24337. * @hidden
  24338. * Defines the actions happening before camera updates.
  24339. */
  24340. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24341. /**
  24342. * @hidden
  24343. * Defines the actions happening before camera updates.
  24344. */
  24345. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24346. /**
  24347. * @hidden
  24348. * Defines the actions happening during the per mesh ready checks.
  24349. */
  24350. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24351. /**
  24352. * @hidden
  24353. * Defines the actions happening before evaluate active mesh checks.
  24354. */
  24355. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24356. /**
  24357. * @hidden
  24358. * Defines the actions happening during the evaluate sub mesh checks.
  24359. */
  24360. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24361. /**
  24362. * @hidden
  24363. * Defines the actions happening during the active mesh stage.
  24364. */
  24365. _this._activeMeshStage = BABYLON.Stage.Create();
  24366. /**
  24367. * @hidden
  24368. * Defines the actions happening during the per camera render target step.
  24369. */
  24370. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24371. /**
  24372. * @hidden
  24373. * Defines the actions happening just before the active camera is drawing.
  24374. */
  24375. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24376. /**
  24377. * Defines the actions happening just before a rendering group is drawing.
  24378. */
  24379. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24380. /**
  24381. * @hidden
  24382. * Defines the actions happening just after a rendering group has been drawn.
  24383. */
  24384. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24385. /**
  24386. * @hidden
  24387. * Defines the actions happening just after the active camera has been drawn.
  24388. */
  24389. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24390. /**
  24391. * @hidden
  24392. * Defines the actions happening when Geometries are rebuilding.
  24393. */
  24394. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24395. _this._activeMeshesFrozen = false;
  24396. /** @hidden */
  24397. _this._allowPostProcessClear = true;
  24398. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24399. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24400. _this.blockMaterialDirtyMechanism = false;
  24401. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24402. _this._engine.scenes.push(_this);
  24403. _this._uid = null;
  24404. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24405. if (BABYLON.PostProcessManager) {
  24406. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24407. }
  24408. if (BABYLON.OutlineRenderer) {
  24409. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24410. }
  24411. if (BABYLON.Tools.IsWindowObjectExist()) {
  24412. _this.attachControl();
  24413. }
  24414. //collision coordinator initialization. For now legacy per default.
  24415. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24416. // Uniform Buffer
  24417. _this._createUbo();
  24418. // Default Image processing definition
  24419. if (BABYLON.ImageProcessingConfiguration) {
  24420. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24421. }
  24422. return _this;
  24423. }
  24424. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24425. /**
  24426. * Texture used in all pbr material as the reflection texture.
  24427. * As in the majority of the scene they are the same (exception for multi room and so on),
  24428. * this is easier to reference from here than from all the materials.
  24429. */
  24430. get: function () {
  24431. return this._environmentTexture;
  24432. },
  24433. /**
  24434. * Texture used in all pbr material as the reflection texture.
  24435. * As in the majority of the scene they are the same (exception for multi room and so on),
  24436. * this is easier to set here than in all the materials.
  24437. */
  24438. set: function (value) {
  24439. if (this._environmentTexture === value) {
  24440. return;
  24441. }
  24442. this._environmentTexture = value;
  24443. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24449. /**
  24450. * Default image processing configuration used either in the rendering
  24451. * Forward main pass or through the imageProcessingPostProcess if present.
  24452. * As in the majority of the scene they are the same (exception for multi camera),
  24453. * this is easier to reference from here than from all the materials and post process.
  24454. *
  24455. * No setter as we it is a shared configuration, you can set the values instead.
  24456. */
  24457. get: function () {
  24458. return this._imageProcessingConfiguration;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24464. get: function () {
  24465. return this._forceWireframe;
  24466. },
  24467. /**
  24468. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24469. */
  24470. set: function (value) {
  24471. if (this._forceWireframe === value) {
  24472. return;
  24473. }
  24474. this._forceWireframe = value;
  24475. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24481. get: function () {
  24482. return this._forcePointsCloud;
  24483. },
  24484. /**
  24485. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24486. */
  24487. set: function (value) {
  24488. if (this._forcePointsCloud === value) {
  24489. return;
  24490. }
  24491. this._forcePointsCloud = value;
  24492. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24493. },
  24494. enumerable: true,
  24495. configurable: true
  24496. });
  24497. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24498. /**
  24499. * Gets or sets the animation properties override
  24500. */
  24501. get: function () {
  24502. return this._animationPropertiesOverride;
  24503. },
  24504. set: function (value) {
  24505. this._animationPropertiesOverride = value;
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(Scene.prototype, "onDispose", {
  24511. /** Sets a function to be executed when this scene is disposed. */
  24512. set: function (callback) {
  24513. if (this._onDisposeObserver) {
  24514. this.onDisposeObservable.remove(this._onDisposeObserver);
  24515. }
  24516. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "beforeRender", {
  24522. /** Sets a function to be executed before rendering this scene */
  24523. set: function (callback) {
  24524. if (this._onBeforeRenderObserver) {
  24525. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24526. }
  24527. if (callback) {
  24528. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24529. }
  24530. },
  24531. enumerable: true,
  24532. configurable: true
  24533. });
  24534. Object.defineProperty(Scene.prototype, "afterRender", {
  24535. /** Sets a function to be executed after rendering this scene */
  24536. set: function (callback) {
  24537. if (this._onAfterRenderObserver) {
  24538. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24539. }
  24540. if (callback) {
  24541. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24542. }
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24548. /** Sets a function to be executed before rendering a camera*/
  24549. set: function (callback) {
  24550. if (this._onBeforeCameraRenderObserver) {
  24551. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24552. }
  24553. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24554. },
  24555. enumerable: true,
  24556. configurable: true
  24557. });
  24558. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24559. /** Sets a function to be executed after rendering a camera*/
  24560. set: function (callback) {
  24561. if (this._onAfterCameraRenderObserver) {
  24562. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24563. }
  24564. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24570. /**
  24571. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24572. */
  24573. get: function () {
  24574. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24580. get: function () {
  24581. return this._useRightHandedSystem;
  24582. },
  24583. /**
  24584. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24585. */
  24586. set: function (value) {
  24587. if (this._useRightHandedSystem === value) {
  24588. return;
  24589. }
  24590. this._useRightHandedSystem = value;
  24591. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24592. },
  24593. enumerable: true,
  24594. configurable: true
  24595. });
  24596. /**
  24597. * Sets the step Id used by deterministic lock step
  24598. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24599. * @param newStepId defines the step Id
  24600. */
  24601. Scene.prototype.setStepId = function (newStepId) {
  24602. this._currentStepId = newStepId;
  24603. };
  24604. ;
  24605. /**
  24606. * Gets the step Id used by deterministic lock step
  24607. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24608. * @returns the step Id
  24609. */
  24610. Scene.prototype.getStepId = function () {
  24611. return this._currentStepId;
  24612. };
  24613. ;
  24614. /**
  24615. * Gets the internal step used by deterministic lock step
  24616. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24617. * @returns the internal step
  24618. */
  24619. Scene.prototype.getInternalStep = function () {
  24620. return this._currentInternalStep;
  24621. };
  24622. ;
  24623. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24624. get: function () {
  24625. return this._fogEnabled;
  24626. },
  24627. /**
  24628. * Gets or sets a boolean indicating if fog is enabled on this scene
  24629. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24630. */
  24631. set: function (value) {
  24632. if (this._fogEnabled === value) {
  24633. return;
  24634. }
  24635. this._fogEnabled = value;
  24636. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. Object.defineProperty(Scene.prototype, "fogMode", {
  24642. get: function () {
  24643. return this._fogMode;
  24644. },
  24645. /**
  24646. * Gets or sets the fog mode to use
  24647. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24648. */
  24649. set: function (value) {
  24650. if (this._fogMode === value) {
  24651. return;
  24652. }
  24653. this._fogMode = value;
  24654. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24660. get: function () {
  24661. return this._shadowsEnabled;
  24662. },
  24663. /**
  24664. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24665. */
  24666. set: function (value) {
  24667. if (this._shadowsEnabled === value) {
  24668. return;
  24669. }
  24670. this._shadowsEnabled = value;
  24671. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24672. },
  24673. enumerable: true,
  24674. configurable: true
  24675. });
  24676. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24677. get: function () {
  24678. return this._lightsEnabled;
  24679. },
  24680. /**
  24681. * Gets or sets a boolean indicating if lights are enabled on this scene
  24682. */
  24683. set: function (value) {
  24684. if (this._lightsEnabled === value) {
  24685. return;
  24686. }
  24687. this._lightsEnabled = value;
  24688. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24689. },
  24690. enumerable: true,
  24691. configurable: true
  24692. });
  24693. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24694. /** The default material used on meshes when no material is affected */
  24695. get: function () {
  24696. if (!this._defaultMaterial) {
  24697. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24698. }
  24699. return this._defaultMaterial;
  24700. },
  24701. /** The default material used on meshes when no material is affected */
  24702. set: function (value) {
  24703. this._defaultMaterial = value;
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24709. get: function () {
  24710. return this._texturesEnabled;
  24711. },
  24712. /**
  24713. * Gets or sets a boolean indicating if textures are enabled on this scene
  24714. */
  24715. set: function (value) {
  24716. if (this._texturesEnabled === value) {
  24717. return;
  24718. }
  24719. this._texturesEnabled = value;
  24720. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24721. },
  24722. enumerable: true,
  24723. configurable: true
  24724. });
  24725. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24726. get: function () {
  24727. return this._skeletonsEnabled;
  24728. },
  24729. /**
  24730. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24731. */
  24732. set: function (value) {
  24733. if (this._skeletonsEnabled === value) {
  24734. return;
  24735. }
  24736. this._skeletonsEnabled = value;
  24737. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24738. },
  24739. enumerable: true,
  24740. configurable: true
  24741. });
  24742. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24743. /**
  24744. * Gets the main soundtrack associated with the scene
  24745. */
  24746. get: function () {
  24747. if (!this._mainSoundTrack) {
  24748. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24749. }
  24750. return this._mainSoundTrack;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24756. /** @hidden */
  24757. get: function () {
  24758. return this._alternateRendering;
  24759. },
  24760. enumerable: true,
  24761. configurable: true
  24762. });
  24763. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24764. /**
  24765. * Gets the list of frustum planes (built from the active camera)
  24766. */
  24767. get: function () {
  24768. return this._frustumPlanes;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. /**
  24774. * Registers the transient components if needed.
  24775. */
  24776. Scene.prototype._registerTransientComponents = function () {
  24777. // Register components that have been associated lately to the scene.
  24778. if (this._transientComponents.length > 0) {
  24779. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24780. var component = _a[_i];
  24781. component.register();
  24782. }
  24783. this._transientComponents = [];
  24784. }
  24785. };
  24786. /**
  24787. * @hidden
  24788. * Add a component to the scene.
  24789. * Note that the ccomponent could be registered on th next frame if this is called after
  24790. * the register component stage.
  24791. * @param component Defines the component to add to the scene
  24792. */
  24793. Scene.prototype._addComponent = function (component) {
  24794. this._components.push(component);
  24795. this._transientComponents.push(component);
  24796. var serializableComponent = component;
  24797. if (serializableComponent.addFromContainer) {
  24798. this._serializableComponents.push(serializableComponent);
  24799. }
  24800. };
  24801. /**
  24802. * @hidden
  24803. * Gets a component from the scene.
  24804. * @param name defines the name of the component to retrieve
  24805. * @returns the component or null if not present
  24806. */
  24807. Scene.prototype._getComponent = function (name) {
  24808. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24809. var component = _a[_i];
  24810. if (component.name === name) {
  24811. return component;
  24812. }
  24813. }
  24814. return null;
  24815. };
  24816. Object.defineProperty(Scene.prototype, "debugLayer", {
  24817. /**
  24818. * Gets the debug layer (aka Inspector) associated with the scene
  24819. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24820. */
  24821. get: function () {
  24822. if (!this._debugLayer) {
  24823. this._debugLayer = new BABYLON.DebugLayer(this);
  24824. }
  24825. return this._debugLayer;
  24826. },
  24827. enumerable: true,
  24828. configurable: true
  24829. });
  24830. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24831. /**
  24832. * Gets a boolean indicating if collisions are processed on a web worker
  24833. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24834. */
  24835. get: function () {
  24836. return this._workerCollisions;
  24837. },
  24838. set: function (enabled) {
  24839. if (!BABYLON.CollisionCoordinatorLegacy) {
  24840. return;
  24841. }
  24842. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24843. this._workerCollisions = enabled;
  24844. if (this.collisionCoordinator) {
  24845. this.collisionCoordinator.destroy();
  24846. }
  24847. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24848. this.collisionCoordinator.init(this);
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24854. /**
  24855. * Gets the octree used to boost mesh selection (picking)
  24856. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24857. */
  24858. get: function () {
  24859. return this._selectionOctree;
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24865. /**
  24866. * Gets the mesh that is currently under the pointer
  24867. */
  24868. get: function () {
  24869. return this._pointerOverMesh;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. Object.defineProperty(Scene.prototype, "pointerX", {
  24875. /**
  24876. * Gets the current on-screen X position of the pointer
  24877. */
  24878. get: function () {
  24879. return this._pointerX;
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. Object.defineProperty(Scene.prototype, "pointerY", {
  24885. /**
  24886. * Gets the current on-screen Y position of the pointer
  24887. */
  24888. get: function () {
  24889. return this._pointerY;
  24890. },
  24891. enumerable: true,
  24892. configurable: true
  24893. });
  24894. /**
  24895. * Gets the cached material (ie. the latest rendered one)
  24896. * @returns the cached material
  24897. */
  24898. Scene.prototype.getCachedMaterial = function () {
  24899. return this._cachedMaterial;
  24900. };
  24901. /**
  24902. * Gets the cached effect (ie. the latest rendered one)
  24903. * @returns the cached effect
  24904. */
  24905. Scene.prototype.getCachedEffect = function () {
  24906. return this._cachedEffect;
  24907. };
  24908. /**
  24909. * Gets the cached visibility state (ie. the latest rendered one)
  24910. * @returns the cached visibility state
  24911. */
  24912. Scene.prototype.getCachedVisibility = function () {
  24913. return this._cachedVisibility;
  24914. };
  24915. /**
  24916. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24917. * @param material defines the current material
  24918. * @param effect defines the current effect
  24919. * @param visibility defines the current visibility state
  24920. * @returns true if one parameter is not cached
  24921. */
  24922. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24923. if (visibility === void 0) { visibility = 1; }
  24924. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24925. };
  24926. /**
  24927. * Gets the outline renderer associated with the scene
  24928. * @returns a OutlineRenderer
  24929. */
  24930. Scene.prototype.getOutlineRenderer = function () {
  24931. return this._outlineRenderer;
  24932. };
  24933. /**
  24934. * Gets the engine associated with the scene
  24935. * @returns an Engine
  24936. */
  24937. Scene.prototype.getEngine = function () {
  24938. return this._engine;
  24939. };
  24940. /**
  24941. * Gets the total number of vertices rendered per frame
  24942. * @returns the total number of vertices rendered per frame
  24943. */
  24944. Scene.prototype.getTotalVertices = function () {
  24945. return this._totalVertices.current;
  24946. };
  24947. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24948. /**
  24949. * Gets the performance counter for total vertices
  24950. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24951. */
  24952. get: function () {
  24953. return this._totalVertices;
  24954. },
  24955. enumerable: true,
  24956. configurable: true
  24957. });
  24958. /**
  24959. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24960. * @returns the total number of active indices rendered per frame
  24961. */
  24962. Scene.prototype.getActiveIndices = function () {
  24963. return this._activeIndices.current;
  24964. };
  24965. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24966. /**
  24967. * Gets the performance counter for active indices
  24968. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24969. */
  24970. get: function () {
  24971. return this._activeIndices;
  24972. },
  24973. enumerable: true,
  24974. configurable: true
  24975. });
  24976. /**
  24977. * Gets the total number of active particles rendered per frame
  24978. * @returns the total number of active particles rendered per frame
  24979. */
  24980. Scene.prototype.getActiveParticles = function () {
  24981. return this._activeParticles.current;
  24982. };
  24983. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24984. /**
  24985. * Gets the performance counter for active particles
  24986. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24987. */
  24988. get: function () {
  24989. return this._activeParticles;
  24990. },
  24991. enumerable: true,
  24992. configurable: true
  24993. });
  24994. /**
  24995. * Gets the total number of active bones rendered per frame
  24996. * @returns the total number of active bones rendered per frame
  24997. */
  24998. Scene.prototype.getActiveBones = function () {
  24999. return this._activeBones.current;
  25000. };
  25001. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25002. /**
  25003. * Gets the performance counter for active bones
  25004. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25005. */
  25006. get: function () {
  25007. return this._activeBones;
  25008. },
  25009. enumerable: true,
  25010. configurable: true
  25011. });
  25012. /** @hidden */
  25013. Scene.prototype.getInterFramePerfCounter = function () {
  25014. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25015. return 0;
  25016. };
  25017. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25018. /** @hidden */
  25019. get: function () {
  25020. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25021. return null;
  25022. },
  25023. enumerable: true,
  25024. configurable: true
  25025. });
  25026. /** @hidden */
  25027. Scene.prototype.getLastFrameDuration = function () {
  25028. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25029. return 0;
  25030. };
  25031. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25032. /** @hidden */
  25033. get: function () {
  25034. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25035. return null;
  25036. },
  25037. enumerable: true,
  25038. configurable: true
  25039. });
  25040. /** @hidden */
  25041. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25042. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25043. return 0;
  25044. };
  25045. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25046. /** @hidden */
  25047. get: function () {
  25048. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25049. return null;
  25050. },
  25051. enumerable: true,
  25052. configurable: true
  25053. });
  25054. /**
  25055. * Gets the array of active meshes
  25056. * @returns an array of AbstractMesh
  25057. */
  25058. Scene.prototype.getActiveMeshes = function () {
  25059. return this._activeMeshes;
  25060. };
  25061. /** @hidden */
  25062. Scene.prototype.getRenderTargetsDuration = function () {
  25063. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25064. return 0;
  25065. };
  25066. /** @hidden */
  25067. Scene.prototype.getRenderDuration = function () {
  25068. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25069. return 0;
  25070. };
  25071. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25072. /** @hidden */
  25073. get: function () {
  25074. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25075. return null;
  25076. },
  25077. enumerable: true,
  25078. configurable: true
  25079. });
  25080. /** @hidden */
  25081. Scene.prototype.getParticlesDuration = function () {
  25082. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25083. return 0;
  25084. };
  25085. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25086. /** @hidden */
  25087. get: function () {
  25088. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25089. return null;
  25090. },
  25091. enumerable: true,
  25092. configurable: true
  25093. });
  25094. /** @hidden */
  25095. Scene.prototype.getSpritesDuration = function () {
  25096. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25097. return 0;
  25098. };
  25099. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25100. /** @hidden */
  25101. get: function () {
  25102. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25103. return null;
  25104. },
  25105. enumerable: true,
  25106. configurable: true
  25107. });
  25108. /**
  25109. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25110. * @returns a number
  25111. */
  25112. Scene.prototype.getAnimationRatio = function () {
  25113. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25114. };
  25115. /**
  25116. * Gets an unique Id for the current frame
  25117. * @returns a number
  25118. */
  25119. Scene.prototype.getRenderId = function () {
  25120. return this._renderId;
  25121. };
  25122. /** Call this function if you want to manually increment the render Id*/
  25123. Scene.prototype.incrementRenderId = function () {
  25124. this._renderId++;
  25125. };
  25126. Scene.prototype._updatePointerPosition = function (evt) {
  25127. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25128. if (!canvasRect) {
  25129. return;
  25130. }
  25131. this._pointerX = evt.clientX - canvasRect.left;
  25132. this._pointerY = evt.clientY - canvasRect.top;
  25133. this._unTranslatedPointerX = this._pointerX;
  25134. this._unTranslatedPointerY = this._pointerY;
  25135. };
  25136. Scene.prototype._createUbo = function () {
  25137. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25138. this._sceneUbo.addUniform("viewProjection", 16);
  25139. this._sceneUbo.addUniform("view", 16);
  25140. };
  25141. Scene.prototype._createAlternateUbo = function () {
  25142. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25143. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25144. this._alternateSceneUbo.addUniform("view", 16);
  25145. };
  25146. // Pointers handling
  25147. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25148. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25149. if (result) {
  25150. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25151. }
  25152. return result;
  25153. };
  25154. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25155. if (pointerInfo.pickInfo) {
  25156. if (!pointerInfo.pickInfo.ray) {
  25157. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25158. }
  25159. }
  25160. };
  25161. /**
  25162. * Use this method to simulate a pointer move on a mesh
  25163. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25164. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25165. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25166. * @returns the current scene
  25167. */
  25168. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25169. var evt = new PointerEvent("pointermove", pointerEventInit);
  25170. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25171. return this;
  25172. }
  25173. return this._processPointerMove(pickResult, evt);
  25174. };
  25175. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25176. var canvas = this._engine.getRenderingCanvas();
  25177. if (!canvas) {
  25178. return this;
  25179. }
  25180. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25181. this.setPointerOverSprite(null);
  25182. this.setPointerOverMesh(pickResult.pickedMesh);
  25183. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25184. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25185. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25186. }
  25187. else {
  25188. canvas.style.cursor = this.hoverCursor;
  25189. }
  25190. }
  25191. else {
  25192. canvas.style.cursor = this.defaultCursor;
  25193. }
  25194. }
  25195. else {
  25196. this.setPointerOverMesh(null);
  25197. // Sprites
  25198. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25199. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25200. this.setPointerOverSprite(pickResult.pickedSprite);
  25201. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25202. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25203. }
  25204. else {
  25205. canvas.style.cursor = this.hoverCursor;
  25206. }
  25207. }
  25208. else {
  25209. this.setPointerOverSprite(null);
  25210. // Restore pointer
  25211. canvas.style.cursor = this.defaultCursor;
  25212. }
  25213. }
  25214. if (pickResult) {
  25215. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25216. if (this.onPointerMove) {
  25217. this.onPointerMove(evt, pickResult, type);
  25218. }
  25219. if (this.onPointerObservable.hasObservers()) {
  25220. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25221. this._setRayOnPointerInfo(pi);
  25222. this.onPointerObservable.notifyObservers(pi, type);
  25223. }
  25224. }
  25225. return this;
  25226. };
  25227. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25228. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25229. if (pickResult) {
  25230. pi.ray = pickResult.ray;
  25231. }
  25232. this.onPrePointerObservable.notifyObservers(pi, type);
  25233. if (pi.skipOnPointerObservable) {
  25234. return true;
  25235. }
  25236. else {
  25237. return false;
  25238. }
  25239. };
  25240. /**
  25241. * Use this method to simulate a pointer down on a mesh
  25242. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25243. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25244. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25245. * @returns the current scene
  25246. */
  25247. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25248. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25249. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25250. return this;
  25251. }
  25252. return this._processPointerDown(pickResult, evt);
  25253. };
  25254. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25255. var _this = this;
  25256. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25257. this._pickedDownMesh = pickResult.pickedMesh;
  25258. var actionManager = pickResult.pickedMesh.actionManager;
  25259. if (actionManager) {
  25260. if (actionManager.hasPickTriggers) {
  25261. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25262. switch (evt.button) {
  25263. case 0:
  25264. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25265. break;
  25266. case 1:
  25267. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25268. break;
  25269. case 2:
  25270. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25271. break;
  25272. }
  25273. }
  25274. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25275. window.setTimeout(function () {
  25276. 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);
  25277. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25278. if (_this._totalPointersPressed !== 0 &&
  25279. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25280. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25281. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25282. _this._startingPointerTime = 0;
  25283. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25284. }
  25285. }
  25286. }, Scene.LongPressDelay);
  25287. }
  25288. }
  25289. }
  25290. if (pickResult) {
  25291. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25292. if (this.onPointerDown) {
  25293. this.onPointerDown(evt, pickResult, type);
  25294. }
  25295. if (this.onPointerObservable.hasObservers()) {
  25296. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25297. this._setRayOnPointerInfo(pi);
  25298. this.onPointerObservable.notifyObservers(pi, type);
  25299. }
  25300. }
  25301. return this;
  25302. };
  25303. /**
  25304. * Use this method to simulate a pointer up on a mesh
  25305. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25306. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25307. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25308. * @returns the current scene
  25309. */
  25310. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25311. var evt = new PointerEvent("pointerup", pointerEventInit);
  25312. var clickInfo = new ClickInfo();
  25313. clickInfo.singleClick = true;
  25314. clickInfo.ignore = true;
  25315. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25316. return this;
  25317. }
  25318. return this._processPointerUp(pickResult, evt, clickInfo);
  25319. };
  25320. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25321. if (pickResult && pickResult && pickResult.pickedMesh) {
  25322. this._pickedUpMesh = pickResult.pickedMesh;
  25323. if (this._pickedDownMesh === this._pickedUpMesh) {
  25324. if (this.onPointerPick) {
  25325. this.onPointerPick(evt, pickResult);
  25326. }
  25327. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25328. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25329. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25330. this._setRayOnPointerInfo(pi);
  25331. this.onPointerObservable.notifyObservers(pi, type_1);
  25332. }
  25333. }
  25334. if (pickResult.pickedMesh.actionManager) {
  25335. if (clickInfo.ignore) {
  25336. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25337. }
  25338. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25339. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25340. }
  25341. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25342. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25343. }
  25344. }
  25345. }
  25346. if (this._pickedDownMesh &&
  25347. this._pickedDownMesh.actionManager &&
  25348. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25349. this._pickedDownMesh !== this._pickedUpMesh) {
  25350. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25351. }
  25352. var type = BABYLON.PointerEventTypes.POINTERUP;
  25353. if (this.onPointerObservable.hasObservers()) {
  25354. if (!clickInfo.ignore) {
  25355. if (!clickInfo.hasSwiped) {
  25356. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25357. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25358. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25359. this._setRayOnPointerInfo(pi);
  25360. this.onPointerObservable.notifyObservers(pi, type_2);
  25361. }
  25362. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25363. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25364. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25365. this._setRayOnPointerInfo(pi);
  25366. this.onPointerObservable.notifyObservers(pi, type_3);
  25367. }
  25368. }
  25369. }
  25370. else {
  25371. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25372. this._setRayOnPointerInfo(pi);
  25373. this.onPointerObservable.notifyObservers(pi, type);
  25374. }
  25375. }
  25376. if (this.onPointerUp) {
  25377. this.onPointerUp(evt, pickResult, type);
  25378. }
  25379. return this;
  25380. };
  25381. /**
  25382. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25383. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25384. * @returns true if the pointer was captured
  25385. */
  25386. Scene.prototype.isPointerCaptured = function (pointerId) {
  25387. if (pointerId === void 0) { pointerId = 0; }
  25388. return this._pointerCaptures[pointerId];
  25389. };
  25390. /**
  25391. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25392. * @param attachUp defines if you want to attach events to pointerup
  25393. * @param attachDown defines if you want to attach events to pointerdown
  25394. * @param attachMove defines if you want to attach events to pointermove
  25395. */
  25396. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25397. var _this = this;
  25398. if (attachUp === void 0) { attachUp = true; }
  25399. if (attachDown === void 0) { attachDown = true; }
  25400. if (attachMove === void 0) { attachMove = true; }
  25401. this._initActionManager = function (act, clickInfo) {
  25402. if (!_this._meshPickProceed) {
  25403. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25404. _this._currentPickResult = pickResult;
  25405. if (pickResult) {
  25406. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25407. }
  25408. _this._meshPickProceed = true;
  25409. }
  25410. return act;
  25411. };
  25412. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25413. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25414. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25415. btn !== _this._previousButtonPressed) {
  25416. _this._doubleClickOccured = false;
  25417. clickInfo.singleClick = true;
  25418. clickInfo.ignore = false;
  25419. cb(clickInfo, _this._currentPickResult);
  25420. }
  25421. };
  25422. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25423. var clickInfo = new ClickInfo();
  25424. _this._currentPickResult = null;
  25425. var act = null;
  25426. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25427. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25428. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25429. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25430. act = _this._initActionManager(act, clickInfo);
  25431. if (act)
  25432. checkPicking = act.hasPickTriggers;
  25433. }
  25434. if (checkPicking) {
  25435. var btn = evt.button;
  25436. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25437. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25438. if (!clickInfo.hasSwiped) {
  25439. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25440. if (!checkSingleClickImmediately) {
  25441. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25442. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25443. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25444. act = _this._initActionManager(act, clickInfo);
  25445. if (act)
  25446. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25447. }
  25448. }
  25449. if (checkSingleClickImmediately) {
  25450. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25451. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25452. btn !== _this._previousButtonPressed) {
  25453. clickInfo.singleClick = true;
  25454. cb(clickInfo, _this._currentPickResult);
  25455. }
  25456. }
  25457. // at least one double click is required to be check and exclusive double click is enabled
  25458. else {
  25459. // wait that no double click has been raised during the double click delay
  25460. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25461. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25462. }
  25463. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25464. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25465. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25466. act = _this._initActionManager(act, clickInfo);
  25467. if (act)
  25468. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25469. }
  25470. if (checkDoubleClick) {
  25471. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25472. if (btn === _this._previousButtonPressed &&
  25473. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25474. !_this._doubleClickOccured) {
  25475. // pointer has not moved for 2 clicks, it's a double click
  25476. if (!clickInfo.hasSwiped &&
  25477. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25478. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25479. _this._previousStartingPointerTime = 0;
  25480. _this._doubleClickOccured = true;
  25481. clickInfo.doubleClick = true;
  25482. clickInfo.ignore = false;
  25483. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25484. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25485. }
  25486. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25487. cb(clickInfo, _this._currentPickResult);
  25488. }
  25489. // if the two successive clicks are too far, it's just two simple clicks
  25490. else {
  25491. _this._doubleClickOccured = false;
  25492. _this._previousStartingPointerTime = _this._startingPointerTime;
  25493. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25494. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25495. _this._previousButtonPressed = btn;
  25496. if (Scene.ExclusiveDoubleClickMode) {
  25497. if (_this._previousDelayedSimpleClickTimeout) {
  25498. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25499. }
  25500. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25501. cb(clickInfo, _this._previousPickResult);
  25502. }
  25503. else {
  25504. cb(clickInfo, _this._currentPickResult);
  25505. }
  25506. }
  25507. }
  25508. // just the first click of the double has been raised
  25509. else {
  25510. _this._doubleClickOccured = false;
  25511. _this._previousStartingPointerTime = _this._startingPointerTime;
  25512. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25513. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25514. _this._previousButtonPressed = btn;
  25515. }
  25516. }
  25517. }
  25518. }
  25519. clickInfo.ignore = true;
  25520. cb(clickInfo, _this._currentPickResult);
  25521. };
  25522. this._spritePredicate = function (sprite) {
  25523. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25524. };
  25525. this._onPointerMove = function (evt) {
  25526. _this._updatePointerPosition(evt);
  25527. // PreObservable support
  25528. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25529. return;
  25530. }
  25531. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25532. return;
  25533. }
  25534. if (!_this.pointerMovePredicate) {
  25535. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25536. }
  25537. // Meshes
  25538. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25539. _this._processPointerMove(pickResult, evt);
  25540. };
  25541. this._onPointerDown = function (evt) {
  25542. _this._totalPointersPressed++;
  25543. _this._pickedDownMesh = null;
  25544. _this._meshPickProceed = false;
  25545. _this._updatePointerPosition(evt);
  25546. if (_this.preventDefaultOnPointerDown && canvas) {
  25547. evt.preventDefault();
  25548. canvas.focus();
  25549. }
  25550. // PreObservable support
  25551. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25552. return;
  25553. }
  25554. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25555. return;
  25556. }
  25557. _this._pointerCaptures[evt.pointerId] = true;
  25558. _this._startingPointerPosition.x = _this._pointerX;
  25559. _this._startingPointerPosition.y = _this._pointerY;
  25560. _this._startingPointerTime = Date.now();
  25561. if (!_this.pointerDownPredicate) {
  25562. _this.pointerDownPredicate = function (mesh) {
  25563. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25564. };
  25565. }
  25566. // Meshes
  25567. _this._pickedDownMesh = null;
  25568. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25569. _this._processPointerDown(pickResult, evt);
  25570. // Sprites
  25571. _this._pickedDownSprite = null;
  25572. if (_this.spriteManagers.length > 0) {
  25573. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25574. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25575. if (pickResult.pickedSprite.actionManager) {
  25576. _this._pickedDownSprite = pickResult.pickedSprite;
  25577. switch (evt.button) {
  25578. case 0:
  25579. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25580. break;
  25581. case 1:
  25582. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25583. break;
  25584. case 2:
  25585. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25586. break;
  25587. }
  25588. if (pickResult.pickedSprite.actionManager) {
  25589. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25590. }
  25591. }
  25592. }
  25593. }
  25594. };
  25595. this._onPointerUp = function (evt) {
  25596. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25597. return; // So we need to test it the pointer down was pressed before.
  25598. }
  25599. _this._totalPointersPressed--;
  25600. _this._pickedUpMesh = null;
  25601. _this._meshPickProceed = false;
  25602. _this._updatePointerPosition(evt);
  25603. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25604. // PreObservable support
  25605. if (_this.onPrePointerObservable.hasObservers()) {
  25606. if (!clickInfo.ignore) {
  25607. if (!clickInfo.hasSwiped) {
  25608. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25609. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25610. return;
  25611. }
  25612. }
  25613. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25614. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25615. return;
  25616. }
  25617. }
  25618. }
  25619. }
  25620. else {
  25621. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25622. return;
  25623. }
  25624. }
  25625. }
  25626. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25627. return;
  25628. }
  25629. _this._pointerCaptures[evt.pointerId] = false;
  25630. if (!_this.pointerUpPredicate) {
  25631. _this.pointerUpPredicate = function (mesh) {
  25632. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25633. };
  25634. }
  25635. // Meshes
  25636. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25637. _this._initActionManager(null, clickInfo);
  25638. }
  25639. if (!pickResult) {
  25640. pickResult = _this._currentPickResult;
  25641. }
  25642. _this._processPointerUp(pickResult, evt, clickInfo);
  25643. // Sprites
  25644. if (!clickInfo.ignore) {
  25645. if (_this.spriteManagers.length > 0) {
  25646. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25647. if (spritePickResult) {
  25648. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25649. if (spritePickResult.pickedSprite.actionManager) {
  25650. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25651. if (spritePickResult.pickedSprite.actionManager) {
  25652. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25653. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25654. }
  25655. }
  25656. }
  25657. }
  25658. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25659. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25660. }
  25661. }
  25662. }
  25663. }
  25664. _this._previousPickResult = _this._currentPickResult;
  25665. });
  25666. };
  25667. this._onKeyDown = function (evt) {
  25668. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25669. if (_this.onPreKeyboardObservable.hasObservers()) {
  25670. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25671. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25672. if (pi.skipOnPointerObservable) {
  25673. return;
  25674. }
  25675. }
  25676. if (_this.onKeyboardObservable.hasObservers()) {
  25677. var pi = new BABYLON.KeyboardInfo(type, evt);
  25678. _this.onKeyboardObservable.notifyObservers(pi, type);
  25679. }
  25680. if (_this.actionManager) {
  25681. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25682. }
  25683. };
  25684. this._onKeyUp = function (evt) {
  25685. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25686. if (_this.onPreKeyboardObservable.hasObservers()) {
  25687. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25688. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25689. if (pi.skipOnPointerObservable) {
  25690. return;
  25691. }
  25692. }
  25693. if (_this.onKeyboardObservable.hasObservers()) {
  25694. var pi = new BABYLON.KeyboardInfo(type, evt);
  25695. _this.onKeyboardObservable.notifyObservers(pi, type);
  25696. }
  25697. if (_this.actionManager) {
  25698. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25699. }
  25700. };
  25701. var engine = this.getEngine();
  25702. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25703. if (!canvas) {
  25704. return;
  25705. }
  25706. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25707. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25708. });
  25709. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25710. if (!canvas) {
  25711. return;
  25712. }
  25713. canvas.removeEventListener("keydown", _this._onKeyDown);
  25714. canvas.removeEventListener("keyup", _this._onKeyUp);
  25715. });
  25716. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25717. var canvas = this._engine.getRenderingCanvas();
  25718. if (!canvas) {
  25719. return;
  25720. }
  25721. if (attachMove) {
  25722. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25723. // Wheel
  25724. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25725. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25726. }
  25727. if (attachDown) {
  25728. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25729. }
  25730. if (attachUp) {
  25731. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25732. }
  25733. canvas.tabIndex = 1;
  25734. };
  25735. /** Detaches all event handlers*/
  25736. Scene.prototype.detachControl = function () {
  25737. var engine = this.getEngine();
  25738. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25739. var canvas = engine.getRenderingCanvas();
  25740. if (!canvas) {
  25741. return;
  25742. }
  25743. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25744. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25745. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25746. if (this._onCanvasBlurObserver) {
  25747. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25748. }
  25749. if (this._onCanvasFocusObserver) {
  25750. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25751. }
  25752. // Wheel
  25753. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25754. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25755. // Keyboard
  25756. canvas.removeEventListener("keydown", this._onKeyDown);
  25757. canvas.removeEventListener("keyup", this._onKeyUp);
  25758. // Observables
  25759. this.onKeyboardObservable.clear();
  25760. this.onPreKeyboardObservable.clear();
  25761. this.onPointerObservable.clear();
  25762. this.onPrePointerObservable.clear();
  25763. };
  25764. /**
  25765. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25766. * Delay loaded resources are not taking in account
  25767. * @return true if all required resources are ready
  25768. */
  25769. Scene.prototype.isReady = function () {
  25770. if (this._isDisposed) {
  25771. return false;
  25772. }
  25773. if (this._pendingData.length > 0) {
  25774. return false;
  25775. }
  25776. var index;
  25777. var engine = this.getEngine();
  25778. // Geometries
  25779. for (index = 0; index < this.geometries.length; index++) {
  25780. var geometry = this.geometries[index];
  25781. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25782. return false;
  25783. }
  25784. }
  25785. // Meshes
  25786. for (index = 0; index < this.meshes.length; index++) {
  25787. var mesh = this.meshes[index];
  25788. if (!mesh.isEnabled()) {
  25789. continue;
  25790. }
  25791. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25792. continue;
  25793. }
  25794. if (!mesh.isReady(true)) {
  25795. return false;
  25796. }
  25797. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25798. // Is Ready For Mesh
  25799. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25800. var step = _a[_i];
  25801. if (!step.action(mesh, hardwareInstancedRendering)) {
  25802. return false;
  25803. }
  25804. }
  25805. }
  25806. // Post-processes
  25807. if (this.activeCameras && this.activeCameras.length > 0) {
  25808. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25809. var camera = _c[_b];
  25810. if (!camera.isReady(true)) {
  25811. return false;
  25812. }
  25813. }
  25814. }
  25815. else if (this.activeCamera) {
  25816. if (!this.activeCamera.isReady(true)) {
  25817. return false;
  25818. }
  25819. }
  25820. // Particles
  25821. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25822. var particleSystem = _e[_d];
  25823. if (!particleSystem.isReady()) {
  25824. return false;
  25825. }
  25826. }
  25827. return true;
  25828. };
  25829. /** Resets all cached information relative to material (including effect and visibility) */
  25830. Scene.prototype.resetCachedMaterial = function () {
  25831. this._cachedMaterial = null;
  25832. this._cachedEffect = null;
  25833. this._cachedVisibility = null;
  25834. };
  25835. /**
  25836. * Registers a function to be called before every frame render
  25837. * @param func defines the function to register
  25838. */
  25839. Scene.prototype.registerBeforeRender = function (func) {
  25840. this.onBeforeRenderObservable.add(func);
  25841. };
  25842. /**
  25843. * Unregisters a function called before every frame render
  25844. * @param func defines the function to unregister
  25845. */
  25846. Scene.prototype.unregisterBeforeRender = function (func) {
  25847. this.onBeforeRenderObservable.removeCallback(func);
  25848. };
  25849. /**
  25850. * Registers a function to be called after every frame render
  25851. * @param func defines the function to register
  25852. */
  25853. Scene.prototype.registerAfterRender = function (func) {
  25854. this.onAfterRenderObservable.add(func);
  25855. };
  25856. /**
  25857. * Unregisters a function called after every frame render
  25858. * @param func defines the function to unregister
  25859. */
  25860. Scene.prototype.unregisterAfterRender = function (func) {
  25861. this.onAfterRenderObservable.removeCallback(func);
  25862. };
  25863. Scene.prototype._executeOnceBeforeRender = function (func) {
  25864. var _this = this;
  25865. var execFunc = function () {
  25866. func();
  25867. setTimeout(function () {
  25868. _this.unregisterBeforeRender(execFunc);
  25869. });
  25870. };
  25871. this.registerBeforeRender(execFunc);
  25872. };
  25873. /**
  25874. * The provided function will run before render once and will be disposed afterwards.
  25875. * A timeout delay can be provided so that the function will be executed in N ms.
  25876. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25877. * @param func The function to be executed.
  25878. * @param timeout optional delay in ms
  25879. */
  25880. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25881. var _this = this;
  25882. if (timeout !== undefined) {
  25883. setTimeout(function () {
  25884. _this._executeOnceBeforeRender(func);
  25885. }, timeout);
  25886. }
  25887. else {
  25888. this._executeOnceBeforeRender(func);
  25889. }
  25890. };
  25891. /** @hidden */
  25892. Scene.prototype._addPendingData = function (data) {
  25893. this._pendingData.push(data);
  25894. };
  25895. /** @hidden */
  25896. Scene.prototype._removePendingData = function (data) {
  25897. var wasLoading = this.isLoading;
  25898. var index = this._pendingData.indexOf(data);
  25899. if (index !== -1) {
  25900. this._pendingData.splice(index, 1);
  25901. }
  25902. if (wasLoading && !this.isLoading) {
  25903. this.onDataLoadedObservable.notifyObservers(this);
  25904. }
  25905. };
  25906. /**
  25907. * Returns the number of items waiting to be loaded
  25908. * @returns the number of items waiting to be loaded
  25909. */
  25910. Scene.prototype.getWaitingItemsCount = function () {
  25911. return this._pendingData.length;
  25912. };
  25913. Object.defineProperty(Scene.prototype, "isLoading", {
  25914. /**
  25915. * Returns a boolean indicating if the scene is still loading data
  25916. */
  25917. get: function () {
  25918. return this._pendingData.length > 0;
  25919. },
  25920. enumerable: true,
  25921. configurable: true
  25922. });
  25923. /**
  25924. * Registers a function to be executed when the scene is ready
  25925. * @param {Function} func - the function to be executed
  25926. */
  25927. Scene.prototype.executeWhenReady = function (func) {
  25928. var _this = this;
  25929. this.onReadyObservable.add(func);
  25930. if (this._executeWhenReadyTimeoutId !== -1) {
  25931. return;
  25932. }
  25933. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25934. _this._checkIsReady();
  25935. }, 150);
  25936. };
  25937. /**
  25938. * Returns a promise that resolves when the scene is ready
  25939. * @returns A promise that resolves when the scene is ready
  25940. */
  25941. Scene.prototype.whenReadyAsync = function () {
  25942. var _this = this;
  25943. return new Promise(function (resolve) {
  25944. _this.executeWhenReady(function () {
  25945. resolve();
  25946. });
  25947. });
  25948. };
  25949. /** @hidden */
  25950. Scene.prototype._checkIsReady = function () {
  25951. var _this = this;
  25952. this._registerTransientComponents();
  25953. if (this.isReady()) {
  25954. this.onReadyObservable.notifyObservers(this);
  25955. this.onReadyObservable.clear();
  25956. this._executeWhenReadyTimeoutId = -1;
  25957. return;
  25958. }
  25959. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25960. _this._checkIsReady();
  25961. }, 150);
  25962. };
  25963. // Animations
  25964. /**
  25965. * Will start the animation sequence of a given target
  25966. * @param target defines the target
  25967. * @param from defines from which frame should animation start
  25968. * @param to defines until which frame should animation run.
  25969. * @param weight defines the weight to apply to the animation (1.0 by default)
  25970. * @param loop defines if the animation loops
  25971. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25972. * @param onAnimationEnd defines the function to be executed when the animation ends
  25973. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25974. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25975. * @returns the animatable object created for this animation
  25976. */
  25977. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25978. if (weight === void 0) { weight = 1.0; }
  25979. if (speedRatio === void 0) { speedRatio = 1.0; }
  25980. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25981. returnedAnimatable.weight = weight;
  25982. return returnedAnimatable;
  25983. };
  25984. /**
  25985. * Will start the animation sequence of a given target
  25986. * @param target defines the target
  25987. * @param from defines from which frame should animation start
  25988. * @param to defines until which frame should animation run.
  25989. * @param loop defines if the animation loops
  25990. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25991. * @param onAnimationEnd defines the function to be executed when the animation ends
  25992. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25993. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25994. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25995. * @returns the animatable object created for this animation
  25996. */
  25997. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25998. if (speedRatio === void 0) { speedRatio = 1.0; }
  25999. if (stopCurrent === void 0) { stopCurrent = true; }
  26000. if (from > to && speedRatio > 0) {
  26001. speedRatio *= -1;
  26002. }
  26003. if (stopCurrent) {
  26004. this.stopAnimation(target, undefined, targetMask);
  26005. }
  26006. if (!animatable) {
  26007. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26008. }
  26009. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26010. // Local animations
  26011. if (target.animations && shouldRunTargetAnimations) {
  26012. animatable.appendAnimations(target, target.animations);
  26013. }
  26014. // Children animations
  26015. if (target.getAnimatables) {
  26016. var animatables = target.getAnimatables();
  26017. for (var index = 0; index < animatables.length; index++) {
  26018. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26019. }
  26020. }
  26021. animatable.reset();
  26022. return animatable;
  26023. };
  26024. /**
  26025. * Begin a new animation on a given node
  26026. * @param target defines the target where the animation will take place
  26027. * @param animations defines the list of animations to start
  26028. * @param from defines the initial value
  26029. * @param to defines the final value
  26030. * @param loop defines if you want animation to loop (off by default)
  26031. * @param speedRatio defines the speed ratio to apply to all animations
  26032. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26033. * @returns the list of created animatables
  26034. */
  26035. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26036. if (speedRatio === undefined) {
  26037. speedRatio = 1.0;
  26038. }
  26039. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26040. return animatable;
  26041. };
  26042. /**
  26043. * Begin a new animation on a given node and its hierarchy
  26044. * @param target defines the root node where the animation will take place
  26045. * @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.
  26046. * @param animations defines the list of animations to start
  26047. * @param from defines the initial value
  26048. * @param to defines the final value
  26049. * @param loop defines if you want animation to loop (off by default)
  26050. * @param speedRatio defines the speed ratio to apply to all animations
  26051. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26052. * @returns the list of animatables created for all nodes
  26053. */
  26054. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26055. var children = target.getDescendants(directDescendantsOnly);
  26056. var result = [];
  26057. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26058. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26059. var child = children_1[_i];
  26060. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26061. }
  26062. return result;
  26063. };
  26064. /**
  26065. * Gets the animatable associated with a specific target
  26066. * @param target defines the target of the animatable
  26067. * @returns the required animatable if found
  26068. */
  26069. Scene.prototype.getAnimatableByTarget = function (target) {
  26070. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26071. if (this._activeAnimatables[index].target === target) {
  26072. return this._activeAnimatables[index];
  26073. }
  26074. }
  26075. return null;
  26076. };
  26077. /**
  26078. * Gets all animatables associated with a given target
  26079. * @param target defines the target to look animatables for
  26080. * @returns an array of Animatables
  26081. */
  26082. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26083. var result = [];
  26084. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26085. if (this._activeAnimatables[index].target === target) {
  26086. result.push(this._activeAnimatables[index]);
  26087. }
  26088. }
  26089. return result;
  26090. };
  26091. Object.defineProperty(Scene.prototype, "animatables", {
  26092. /**
  26093. * Gets all animatable attached to the scene
  26094. */
  26095. get: function () {
  26096. return this._activeAnimatables;
  26097. },
  26098. enumerable: true,
  26099. configurable: true
  26100. });
  26101. /**
  26102. * Will stop the animation of the given target
  26103. * @param target - the target
  26104. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26105. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26106. */
  26107. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26108. var animatables = this.getAllAnimatablesByTarget(target);
  26109. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26110. var animatable = animatables_1[_i];
  26111. animatable.stop(animationName, targetMask);
  26112. }
  26113. };
  26114. /**
  26115. * Stops and removes all animations that have been applied to the scene
  26116. */
  26117. Scene.prototype.stopAllAnimations = function () {
  26118. if (this._activeAnimatables) {
  26119. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26120. this._activeAnimatables[i].stop();
  26121. }
  26122. this._activeAnimatables = [];
  26123. }
  26124. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26125. var group = _a[_i];
  26126. group.stop();
  26127. }
  26128. };
  26129. Scene.prototype._animate = function () {
  26130. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26131. return;
  26132. }
  26133. // Getting time
  26134. var now = BABYLON.Tools.Now;
  26135. if (!this._animationTimeLast) {
  26136. if (this._pendingData.length > 0) {
  26137. return;
  26138. }
  26139. this._animationTimeLast = now;
  26140. }
  26141. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26142. this._animationTime += deltaTime;
  26143. this._animationTimeLast = now;
  26144. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26145. this._activeAnimatables[index]._animate(this._animationTime);
  26146. }
  26147. // Late animation bindings
  26148. this._processLateAnimationBindings();
  26149. };
  26150. /** @hidden */
  26151. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26152. var target = runtimeAnimation.target;
  26153. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26154. if (!target._lateAnimationHolders) {
  26155. target._lateAnimationHolders = {};
  26156. }
  26157. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26158. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26159. totalWeight: 0,
  26160. animations: [],
  26161. originalValue: originalValue
  26162. };
  26163. }
  26164. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26165. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26166. };
  26167. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26168. var normalizer = 1.0;
  26169. var finalPosition = BABYLON.Tmp.Vector3[0];
  26170. var finalScaling = BABYLON.Tmp.Vector3[1];
  26171. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26172. var startIndex = 0;
  26173. var originalAnimation = holder.animations[0];
  26174. var originalValue = holder.originalValue;
  26175. var scale = 1;
  26176. if (holder.totalWeight < 1.0) {
  26177. // We need to mix the original value in
  26178. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26179. scale = 1.0 - holder.totalWeight;
  26180. }
  26181. else {
  26182. startIndex = 1;
  26183. // We need to normalize the weights
  26184. normalizer = holder.totalWeight;
  26185. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26186. scale = originalAnimation.weight / normalizer;
  26187. if (scale == 1) {
  26188. return originalAnimation.currentValue;
  26189. }
  26190. }
  26191. finalScaling.scaleInPlace(scale);
  26192. finalPosition.scaleInPlace(scale);
  26193. finalQuaternion.scaleInPlace(scale);
  26194. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26195. var runtimeAnimation = holder.animations[animIndex];
  26196. var scale = runtimeAnimation.weight / normalizer;
  26197. var currentPosition = BABYLON.Tmp.Vector3[2];
  26198. var currentScaling = BABYLON.Tmp.Vector3[3];
  26199. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26200. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26201. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26202. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26203. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26204. }
  26205. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26206. return originalAnimation._workValue;
  26207. };
  26208. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26209. var originalAnimation = holder.animations[0];
  26210. var originalValue = holder.originalValue;
  26211. if (holder.animations.length === 1) {
  26212. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26213. return refQuaternion;
  26214. }
  26215. var normalizer = 1.0;
  26216. var quaternions;
  26217. var weights;
  26218. if (holder.totalWeight < 1.0) {
  26219. var scale = 1.0 - holder.totalWeight;
  26220. quaternions = [];
  26221. weights = [];
  26222. quaternions.push(originalValue);
  26223. weights.push(scale);
  26224. }
  26225. else {
  26226. if (holder.animations.length === 2) { // Slerp as soon as we can
  26227. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26228. return refQuaternion;
  26229. }
  26230. quaternions = [];
  26231. weights = [];
  26232. normalizer = holder.totalWeight;
  26233. }
  26234. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26235. var runtimeAnimation = holder.animations[animIndex];
  26236. quaternions.push(runtimeAnimation.currentValue);
  26237. weights.push(runtimeAnimation.weight / normalizer);
  26238. }
  26239. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26240. var cumulativeAmount = 0;
  26241. var cumulativeQuaternion = null;
  26242. for (var index = 0; index < quaternions.length;) {
  26243. if (!cumulativeQuaternion) {
  26244. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26245. cumulativeQuaternion = refQuaternion;
  26246. cumulativeAmount = weights[index] + weights[index + 1];
  26247. index += 2;
  26248. continue;
  26249. }
  26250. cumulativeAmount += weights[index];
  26251. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26252. index++;
  26253. }
  26254. return cumulativeQuaternion;
  26255. };
  26256. Scene.prototype._processLateAnimationBindings = function () {
  26257. if (!this._registeredForLateAnimationBindings.length) {
  26258. return;
  26259. }
  26260. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26261. var target = this._registeredForLateAnimationBindings.data[index];
  26262. for (var path in target._lateAnimationHolders) {
  26263. var holder = target._lateAnimationHolders[path];
  26264. var originalAnimation = holder.animations[0];
  26265. var originalValue = holder.originalValue;
  26266. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26267. var finalValue = target[path];
  26268. if (matrixDecomposeMode) {
  26269. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26270. }
  26271. else {
  26272. var quaternionMode = originalValue.w !== undefined;
  26273. if (quaternionMode) {
  26274. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26275. }
  26276. else {
  26277. var startIndex = 0;
  26278. var normalizer = 1.0;
  26279. if (holder.totalWeight < 1.0) {
  26280. // We need to mix the original value in
  26281. if (originalValue.scale) {
  26282. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26283. }
  26284. else {
  26285. finalValue = originalValue * (1.0 - holder.totalWeight);
  26286. }
  26287. }
  26288. else {
  26289. // We need to normalize the weights
  26290. normalizer = holder.totalWeight;
  26291. var scale_1 = originalAnimation.weight / normalizer;
  26292. if (scale_1 !== 1) {
  26293. if (originalAnimation.currentValue.scale) {
  26294. finalValue = originalAnimation.currentValue.scale(scale_1);
  26295. }
  26296. else {
  26297. finalValue = originalAnimation.currentValue * scale_1;
  26298. }
  26299. }
  26300. else {
  26301. finalValue = originalAnimation.currentValue;
  26302. }
  26303. startIndex = 1;
  26304. }
  26305. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26306. var runtimeAnimation = holder.animations[animIndex];
  26307. var scale = runtimeAnimation.weight / normalizer;
  26308. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26309. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26310. }
  26311. else {
  26312. finalValue += runtimeAnimation.currentValue * scale;
  26313. }
  26314. }
  26315. }
  26316. }
  26317. target[path] = finalValue;
  26318. }
  26319. target._lateAnimationHolders = {};
  26320. }
  26321. this._registeredForLateAnimationBindings.reset();
  26322. };
  26323. // Matrix
  26324. /** @hidden */
  26325. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26326. this._useAlternateCameraConfiguration = active;
  26327. };
  26328. /**
  26329. * Gets the current view matrix
  26330. * @returns a Matrix
  26331. */
  26332. Scene.prototype.getViewMatrix = function () {
  26333. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26334. };
  26335. /**
  26336. * Gets the current projection matrix
  26337. * @returns a Matrix
  26338. */
  26339. Scene.prototype.getProjectionMatrix = function () {
  26340. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26341. };
  26342. /**
  26343. * Gets the current transform matrix
  26344. * @returns a Matrix made of View * Projection
  26345. */
  26346. Scene.prototype.getTransformMatrix = function () {
  26347. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26348. };
  26349. /**
  26350. * Sets the current transform matrix
  26351. * @param view defines the View matrix to use
  26352. * @param projection defines the Projection matrix to use
  26353. */
  26354. Scene.prototype.setTransformMatrix = function (view, projection) {
  26355. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26356. return;
  26357. }
  26358. this._viewUpdateFlag = view.updateFlag;
  26359. this._projectionUpdateFlag = projection.updateFlag;
  26360. this._viewMatrix = view;
  26361. this._projectionMatrix = projection;
  26362. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26363. // Update frustum
  26364. if (!this._frustumPlanes) {
  26365. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26366. }
  26367. else {
  26368. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26369. }
  26370. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26371. var otherCamera = this.activeCamera._alternateCamera;
  26372. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26373. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26374. }
  26375. if (this._sceneUbo.useUbo) {
  26376. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26377. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26378. this._sceneUbo.update();
  26379. }
  26380. };
  26381. /** @hidden */
  26382. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26383. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26384. return;
  26385. }
  26386. this._alternateViewUpdateFlag = view.updateFlag;
  26387. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26388. this._alternateViewMatrix = view;
  26389. this._alternateProjectionMatrix = projection;
  26390. if (!this._alternateTransformMatrix) {
  26391. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26392. }
  26393. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26394. if (!this._alternateSceneUbo) {
  26395. this._createAlternateUbo();
  26396. }
  26397. if (this._alternateSceneUbo.useUbo) {
  26398. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26399. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26400. this._alternateSceneUbo.update();
  26401. }
  26402. };
  26403. /**
  26404. * Gets the uniform buffer used to store scene data
  26405. * @returns a UniformBuffer
  26406. */
  26407. Scene.prototype.getSceneUniformBuffer = function () {
  26408. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26409. };
  26410. /**
  26411. * Gets an unique (relatively to the current scene) Id
  26412. * @returns an unique number for the scene
  26413. */
  26414. Scene.prototype.getUniqueId = function () {
  26415. var result = Scene._uniqueIdCounter;
  26416. Scene._uniqueIdCounter++;
  26417. return result;
  26418. };
  26419. /**
  26420. * Add a mesh to the list of scene's meshes
  26421. * @param newMesh defines the mesh to add
  26422. * @param recursive if all child meshes should also be added to the scene
  26423. */
  26424. Scene.prototype.addMesh = function (newMesh, recursive) {
  26425. var _this = this;
  26426. if (recursive === void 0) { recursive = false; }
  26427. this.meshes.push(newMesh);
  26428. //notify the collision coordinator
  26429. if (this.collisionCoordinator) {
  26430. this.collisionCoordinator.onMeshAdded(newMesh);
  26431. }
  26432. newMesh._resyncLightSources();
  26433. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26434. if (recursive) {
  26435. newMesh.getChildMeshes().forEach(function (m) {
  26436. _this.addMesh(m);
  26437. });
  26438. }
  26439. };
  26440. /**
  26441. * Remove a mesh for the list of scene's meshes
  26442. * @param toRemove defines the mesh to remove
  26443. * @param recursive if all child meshes should also be removed from the scene
  26444. * @returns the index where the mesh was in the mesh list
  26445. */
  26446. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26447. var _this = this;
  26448. if (recursive === void 0) { recursive = false; }
  26449. var index = this.meshes.indexOf(toRemove);
  26450. if (index !== -1) {
  26451. // Remove from the scene if mesh found
  26452. this.meshes.splice(index, 1);
  26453. }
  26454. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26455. if (recursive) {
  26456. toRemove.getChildMeshes().forEach(function (m) {
  26457. _this.removeMesh(m);
  26458. });
  26459. }
  26460. return index;
  26461. };
  26462. /**
  26463. * Add a transform node to the list of scene's transform nodes
  26464. * @param newTransformNode defines the transform node to add
  26465. */
  26466. Scene.prototype.addTransformNode = function (newTransformNode) {
  26467. this.transformNodes.push(newTransformNode);
  26468. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26469. };
  26470. /**
  26471. * Remove a transform node for the list of scene's transform nodes
  26472. * @param toRemove defines the transform node to remove
  26473. * @returns the index where the transform node was in the transform node list
  26474. */
  26475. Scene.prototype.removeTransformNode = function (toRemove) {
  26476. var index = this.transformNodes.indexOf(toRemove);
  26477. if (index !== -1) {
  26478. // Remove from the scene if found
  26479. this.transformNodes.splice(index, 1);
  26480. }
  26481. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26482. return index;
  26483. };
  26484. /**
  26485. * Remove a skeleton for the list of scene's skeletons
  26486. * @param toRemove defines the skeleton to remove
  26487. * @returns the index where the skeleton was in the skeleton list
  26488. */
  26489. Scene.prototype.removeSkeleton = function (toRemove) {
  26490. var index = this.skeletons.indexOf(toRemove);
  26491. if (index !== -1) {
  26492. // Remove from the scene if found
  26493. this.skeletons.splice(index, 1);
  26494. }
  26495. return index;
  26496. };
  26497. /**
  26498. * Remove a morph target for the list of scene's morph targets
  26499. * @param toRemove defines the morph target to remove
  26500. * @returns the index where the morph target was in the morph target list
  26501. */
  26502. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26503. var index = this.morphTargetManagers.indexOf(toRemove);
  26504. if (index !== -1) {
  26505. // Remove from the scene if found
  26506. this.morphTargetManagers.splice(index, 1);
  26507. }
  26508. return index;
  26509. };
  26510. /**
  26511. * Remove a light for the list of scene's lights
  26512. * @param toRemove defines the light to remove
  26513. * @returns the index where the light was in the light list
  26514. */
  26515. Scene.prototype.removeLight = function (toRemove) {
  26516. var index = this.lights.indexOf(toRemove);
  26517. if (index !== -1) {
  26518. // Remove from meshes
  26519. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26520. var mesh = _a[_i];
  26521. mesh._removeLightSource(toRemove);
  26522. }
  26523. // Remove from the scene if mesh found
  26524. this.lights.splice(index, 1);
  26525. this.sortLightsByPriority();
  26526. }
  26527. this.onLightRemovedObservable.notifyObservers(toRemove);
  26528. return index;
  26529. };
  26530. /**
  26531. * Remove a camera for the list of scene's cameras
  26532. * @param toRemove defines the camera to remove
  26533. * @returns the index where the camera was in the camera list
  26534. */
  26535. Scene.prototype.removeCamera = function (toRemove) {
  26536. var index = this.cameras.indexOf(toRemove);
  26537. if (index !== -1) {
  26538. // Remove from the scene if mesh found
  26539. this.cameras.splice(index, 1);
  26540. }
  26541. // Remove from activeCameras
  26542. var index2 = this.activeCameras.indexOf(toRemove);
  26543. if (index2 !== -1) {
  26544. // Remove from the scene if mesh found
  26545. this.activeCameras.splice(index2, 1);
  26546. }
  26547. // Reset the activeCamera
  26548. if (this.activeCamera === toRemove) {
  26549. if (this.cameras.length > 0) {
  26550. this.activeCamera = this.cameras[0];
  26551. }
  26552. else {
  26553. this.activeCamera = null;
  26554. }
  26555. }
  26556. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26557. return index;
  26558. };
  26559. /**
  26560. * Remove a particle system for the list of scene's particle systems
  26561. * @param toRemove defines the particle system to remove
  26562. * @returns the index where the particle system was in the particle system list
  26563. */
  26564. Scene.prototype.removeParticleSystem = function (toRemove) {
  26565. var index = this.particleSystems.indexOf(toRemove);
  26566. if (index !== -1) {
  26567. this.particleSystems.splice(index, 1);
  26568. }
  26569. return index;
  26570. };
  26571. /**
  26572. * Remove a animation for the list of scene's animations
  26573. * @param toRemove defines the animation to remove
  26574. * @returns the index where the animation was in the animation list
  26575. */
  26576. Scene.prototype.removeAnimation = function (toRemove) {
  26577. var index = this.animations.indexOf(toRemove);
  26578. if (index !== -1) {
  26579. this.animations.splice(index, 1);
  26580. }
  26581. return index;
  26582. };
  26583. /**
  26584. * Removes the given animation group from this scene.
  26585. * @param toRemove The animation group to remove
  26586. * @returns The index of the removed animation group
  26587. */
  26588. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26589. var index = this.animationGroups.indexOf(toRemove);
  26590. if (index !== -1) {
  26591. this.animationGroups.splice(index, 1);
  26592. }
  26593. return index;
  26594. };
  26595. /**
  26596. * Removes the given multi-material from this scene.
  26597. * @param toRemove The multi-material to remove
  26598. * @returns The index of the removed multi-material
  26599. */
  26600. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26601. var index = this.multiMaterials.indexOf(toRemove);
  26602. if (index !== -1) {
  26603. this.multiMaterials.splice(index, 1);
  26604. }
  26605. return index;
  26606. };
  26607. /**
  26608. * Removes the given material from this scene.
  26609. * @param toRemove The material to remove
  26610. * @returns The index of the removed material
  26611. */
  26612. Scene.prototype.removeMaterial = function (toRemove) {
  26613. var index = this.materials.indexOf(toRemove);
  26614. if (index !== -1) {
  26615. this.materials.splice(index, 1);
  26616. }
  26617. return index;
  26618. };
  26619. /**
  26620. * Removes the given action manager from this scene.
  26621. * @param toRemove The action manager to remove
  26622. * @returns The index of the removed action manager
  26623. */
  26624. Scene.prototype.removeActionManager = function (toRemove) {
  26625. var index = this.actionManagers.indexOf(toRemove);
  26626. if (index !== -1) {
  26627. this.actionManagers.splice(index, 1);
  26628. }
  26629. return index;
  26630. };
  26631. /**
  26632. * Removes the given texture from this scene.
  26633. * @param toRemove The texture to remove
  26634. * @returns The index of the removed texture
  26635. */
  26636. Scene.prototype.removeTexture = function (toRemove) {
  26637. var index = this.textures.indexOf(toRemove);
  26638. if (index !== -1) {
  26639. this.textures.splice(index, 1);
  26640. }
  26641. return index;
  26642. };
  26643. /**
  26644. * Adds the given light to this scene
  26645. * @param newLight The light to add
  26646. */
  26647. Scene.prototype.addLight = function (newLight) {
  26648. this.lights.push(newLight);
  26649. this.sortLightsByPriority();
  26650. // Add light to all meshes (To support if the light is removed and then readded)
  26651. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26652. var mesh = _a[_i];
  26653. if (mesh._lightSources.indexOf(newLight) === -1) {
  26654. mesh._lightSources.push(newLight);
  26655. mesh._resyncLightSources();
  26656. }
  26657. }
  26658. this.onNewLightAddedObservable.notifyObservers(newLight);
  26659. };
  26660. /**
  26661. * Sorts the list list based on light priorities
  26662. */
  26663. Scene.prototype.sortLightsByPriority = function () {
  26664. if (this.requireLightSorting) {
  26665. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26666. }
  26667. };
  26668. /**
  26669. * Adds the given camera to this scene
  26670. * @param newCamera The camera to add
  26671. */
  26672. Scene.prototype.addCamera = function (newCamera) {
  26673. this.cameras.push(newCamera);
  26674. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26675. };
  26676. /**
  26677. * Adds the given skeleton to this scene
  26678. * @param newSkeleton The skeleton to add
  26679. */
  26680. Scene.prototype.addSkeleton = function (newSkeleton) {
  26681. this.skeletons.push(newSkeleton);
  26682. };
  26683. /**
  26684. * Adds the given particle system to this scene
  26685. * @param newParticleSystem The particle system to add
  26686. */
  26687. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26688. this.particleSystems.push(newParticleSystem);
  26689. };
  26690. /**
  26691. * Adds the given animation to this scene
  26692. * @param newAnimation The animation to add
  26693. */
  26694. Scene.prototype.addAnimation = function (newAnimation) {
  26695. this.animations.push(newAnimation);
  26696. };
  26697. /**
  26698. * Adds the given animation group to this scene.
  26699. * @param newAnimationGroup The animation group to add
  26700. */
  26701. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26702. this.animationGroups.push(newAnimationGroup);
  26703. };
  26704. /**
  26705. * Adds the given multi-material to this scene
  26706. * @param newMultiMaterial The multi-material to add
  26707. */
  26708. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26709. this.multiMaterials.push(newMultiMaterial);
  26710. };
  26711. /**
  26712. * Adds the given material to this scene
  26713. * @param newMaterial The material to add
  26714. */
  26715. Scene.prototype.addMaterial = function (newMaterial) {
  26716. this.materials.push(newMaterial);
  26717. };
  26718. /**
  26719. * Adds the given morph target to this scene
  26720. * @param newMorphTargetManager The morph target to add
  26721. */
  26722. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26723. this.morphTargetManagers.push(newMorphTargetManager);
  26724. };
  26725. /**
  26726. * Adds the given geometry to this scene
  26727. * @param newGeometry The geometry to add
  26728. */
  26729. Scene.prototype.addGeometry = function (newGeometry) {
  26730. this.geometries.push(newGeometry);
  26731. };
  26732. /**
  26733. * Adds the given action manager to this scene
  26734. * @param newActionManager The action manager to add
  26735. */
  26736. Scene.prototype.addActionManager = function (newActionManager) {
  26737. this.actionManagers.push(newActionManager);
  26738. };
  26739. /**
  26740. * Adds the given texture to this scene.
  26741. * @param newTexture The texture to add
  26742. */
  26743. Scene.prototype.addTexture = function (newTexture) {
  26744. this.textures.push(newTexture);
  26745. };
  26746. /**
  26747. * Switch active camera
  26748. * @param newCamera defines the new active camera
  26749. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26750. */
  26751. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26752. if (attachControl === void 0) { attachControl = true; }
  26753. var canvas = this._engine.getRenderingCanvas();
  26754. if (!canvas) {
  26755. return;
  26756. }
  26757. if (this.activeCamera) {
  26758. this.activeCamera.detachControl(canvas);
  26759. }
  26760. this.activeCamera = newCamera;
  26761. if (attachControl) {
  26762. newCamera.attachControl(canvas);
  26763. }
  26764. };
  26765. /**
  26766. * sets the active camera of the scene using its ID
  26767. * @param id defines the camera's ID
  26768. * @return the new active camera or null if none found.
  26769. */
  26770. Scene.prototype.setActiveCameraByID = function (id) {
  26771. var camera = this.getCameraByID(id);
  26772. if (camera) {
  26773. this.activeCamera = camera;
  26774. return camera;
  26775. }
  26776. return null;
  26777. };
  26778. /**
  26779. * sets the active camera of the scene using its name
  26780. * @param name defines the camera's name
  26781. * @returns the new active camera or null if none found.
  26782. */
  26783. Scene.prototype.setActiveCameraByName = function (name) {
  26784. var camera = this.getCameraByName(name);
  26785. if (camera) {
  26786. this.activeCamera = camera;
  26787. return camera;
  26788. }
  26789. return null;
  26790. };
  26791. /**
  26792. * get an animation group using its name
  26793. * @param name defines the material's name
  26794. * @return the animation group or null if none found.
  26795. */
  26796. Scene.prototype.getAnimationGroupByName = function (name) {
  26797. for (var index = 0; index < this.animationGroups.length; index++) {
  26798. if (this.animationGroups[index].name === name) {
  26799. return this.animationGroups[index];
  26800. }
  26801. }
  26802. return null;
  26803. };
  26804. /**
  26805. * get a material using its id
  26806. * @param id defines the material's ID
  26807. * @return the material or null if none found.
  26808. */
  26809. Scene.prototype.getMaterialByID = function (id) {
  26810. for (var index = 0; index < this.materials.length; index++) {
  26811. if (this.materials[index].id === id) {
  26812. return this.materials[index];
  26813. }
  26814. }
  26815. return null;
  26816. };
  26817. /**
  26818. * Gets a material using its name
  26819. * @param name defines the material's name
  26820. * @return the material or null if none found.
  26821. */
  26822. Scene.prototype.getMaterialByName = function (name) {
  26823. for (var index = 0; index < this.materials.length; index++) {
  26824. if (this.materials[index].name === name) {
  26825. return this.materials[index];
  26826. }
  26827. }
  26828. return null;
  26829. };
  26830. /**
  26831. * Gets a camera using its id
  26832. * @param id defines the id to look for
  26833. * @returns the camera or null if not found
  26834. */
  26835. Scene.prototype.getCameraByID = function (id) {
  26836. for (var index = 0; index < this.cameras.length; index++) {
  26837. if (this.cameras[index].id === id) {
  26838. return this.cameras[index];
  26839. }
  26840. }
  26841. return null;
  26842. };
  26843. /**
  26844. * Gets a camera using its unique id
  26845. * @param uniqueId defines the unique id to look for
  26846. * @returns the camera or null if not found
  26847. */
  26848. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26849. for (var index = 0; index < this.cameras.length; index++) {
  26850. if (this.cameras[index].uniqueId === uniqueId) {
  26851. return this.cameras[index];
  26852. }
  26853. }
  26854. return null;
  26855. };
  26856. /**
  26857. * Gets a camera using its name
  26858. * @param name defines the camera's name
  26859. * @return the camera or null if none found.
  26860. */
  26861. Scene.prototype.getCameraByName = function (name) {
  26862. for (var index = 0; index < this.cameras.length; index++) {
  26863. if (this.cameras[index].name === name) {
  26864. return this.cameras[index];
  26865. }
  26866. }
  26867. return null;
  26868. };
  26869. /**
  26870. * Gets a bone using its id
  26871. * @param id defines the bone's id
  26872. * @return the bone or null if not found
  26873. */
  26874. Scene.prototype.getBoneByID = function (id) {
  26875. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26876. var skeleton = this.skeletons[skeletonIndex];
  26877. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26878. if (skeleton.bones[boneIndex].id === id) {
  26879. return skeleton.bones[boneIndex];
  26880. }
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a bone using its id
  26887. * @param name defines the bone's name
  26888. * @return the bone or null if not found
  26889. */
  26890. Scene.prototype.getBoneByName = function (name) {
  26891. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26892. var skeleton = this.skeletons[skeletonIndex];
  26893. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26894. if (skeleton.bones[boneIndex].name === name) {
  26895. return skeleton.bones[boneIndex];
  26896. }
  26897. }
  26898. }
  26899. return null;
  26900. };
  26901. /**
  26902. * Gets a light node using its name
  26903. * @param name defines the the light's name
  26904. * @return the light or null if none found.
  26905. */
  26906. Scene.prototype.getLightByName = function (name) {
  26907. for (var index = 0; index < this.lights.length; index++) {
  26908. if (this.lights[index].name === name) {
  26909. return this.lights[index];
  26910. }
  26911. }
  26912. return null;
  26913. };
  26914. /**
  26915. * Gets a light node using its id
  26916. * @param id defines the light's id
  26917. * @return the light or null if none found.
  26918. */
  26919. Scene.prototype.getLightByID = function (id) {
  26920. for (var index = 0; index < this.lights.length; index++) {
  26921. if (this.lights[index].id === id) {
  26922. return this.lights[index];
  26923. }
  26924. }
  26925. return null;
  26926. };
  26927. /**
  26928. * Gets a light node using its scene-generated unique ID
  26929. * @param uniqueId defines the light's unique id
  26930. * @return the light or null if none found.
  26931. */
  26932. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26933. for (var index = 0; index < this.lights.length; index++) {
  26934. if (this.lights[index].uniqueId === uniqueId) {
  26935. return this.lights[index];
  26936. }
  26937. }
  26938. return null;
  26939. };
  26940. /**
  26941. * Gets a particle system by id
  26942. * @param id defines the particle system id
  26943. * @return the corresponding system or null if none found
  26944. */
  26945. Scene.prototype.getParticleSystemByID = function (id) {
  26946. for (var index = 0; index < this.particleSystems.length; index++) {
  26947. if (this.particleSystems[index].id === id) {
  26948. return this.particleSystems[index];
  26949. }
  26950. }
  26951. return null;
  26952. };
  26953. /**
  26954. * Gets a geometry using its ID
  26955. * @param id defines the geometry's id
  26956. * @return the geometry or null if none found.
  26957. */
  26958. Scene.prototype.getGeometryByID = function (id) {
  26959. for (var index = 0; index < this.geometries.length; index++) {
  26960. if (this.geometries[index].id === id) {
  26961. return this.geometries[index];
  26962. }
  26963. }
  26964. return null;
  26965. };
  26966. /**
  26967. * Add a new geometry to this scene
  26968. * @param geometry defines the geometry to be added to the scene.
  26969. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26970. * @return a boolean defining if the geometry was added or not
  26971. */
  26972. Scene.prototype.pushGeometry = function (geometry, force) {
  26973. if (!force && this.getGeometryByID(geometry.id)) {
  26974. return false;
  26975. }
  26976. this.geometries.push(geometry);
  26977. //notify the collision coordinator
  26978. if (this.collisionCoordinator) {
  26979. this.collisionCoordinator.onGeometryAdded(geometry);
  26980. }
  26981. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26982. return true;
  26983. };
  26984. /**
  26985. * Removes an existing geometry
  26986. * @param geometry defines the geometry to be removed from the scene
  26987. * @return a boolean defining if the geometry was removed or not
  26988. */
  26989. Scene.prototype.removeGeometry = function (geometry) {
  26990. var index = this.geometries.indexOf(geometry);
  26991. if (index > -1) {
  26992. this.geometries.splice(index, 1);
  26993. //notify the collision coordinator
  26994. if (this.collisionCoordinator) {
  26995. this.collisionCoordinator.onGeometryDeleted(geometry);
  26996. }
  26997. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26998. return true;
  26999. }
  27000. return false;
  27001. };
  27002. /**
  27003. * Gets the list of geometries attached to the scene
  27004. * @returns an array of Geometry
  27005. */
  27006. Scene.prototype.getGeometries = function () {
  27007. return this.geometries;
  27008. };
  27009. /**
  27010. * Gets the first added mesh found of a given ID
  27011. * @param id defines the id to search for
  27012. * @return the mesh found or null if not found at all
  27013. */
  27014. Scene.prototype.getMeshByID = function (id) {
  27015. for (var index = 0; index < this.meshes.length; index++) {
  27016. if (this.meshes[index].id === id) {
  27017. return this.meshes[index];
  27018. }
  27019. }
  27020. return null;
  27021. };
  27022. /**
  27023. * Gets a list of meshes using their id
  27024. * @param id defines the id to search for
  27025. * @returns a list of meshes
  27026. */
  27027. Scene.prototype.getMeshesByID = function (id) {
  27028. return this.meshes.filter(function (m) {
  27029. return m.id === id;
  27030. });
  27031. };
  27032. /**
  27033. * Gets the first added transform node found of a given ID
  27034. * @param id defines the id to search for
  27035. * @return the found transform node or null if not found at all.
  27036. */
  27037. Scene.prototype.getTransformNodeByID = function (id) {
  27038. for (var index = 0; index < this.transformNodes.length; index++) {
  27039. if (this.transformNodes[index].id === id) {
  27040. return this.transformNodes[index];
  27041. }
  27042. }
  27043. return null;
  27044. };
  27045. /**
  27046. * Gets a list of transform nodes using their id
  27047. * @param id defines the id to search for
  27048. * @returns a list of transform nodes
  27049. */
  27050. Scene.prototype.getTransformNodesByID = function (id) {
  27051. return this.transformNodes.filter(function (m) {
  27052. return m.id === id;
  27053. });
  27054. };
  27055. /**
  27056. * Gets a mesh with its auto-generated unique id
  27057. * @param uniqueId defines the unique id to search for
  27058. * @return the found mesh or null if not found at all.
  27059. */
  27060. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27061. for (var index = 0; index < this.meshes.length; index++) {
  27062. if (this.meshes[index].uniqueId === uniqueId) {
  27063. return this.meshes[index];
  27064. }
  27065. }
  27066. return null;
  27067. };
  27068. /**
  27069. * Gets a the last added mesh using a given id
  27070. * @param id defines the id to search for
  27071. * @return the found mesh or null if not found at all.
  27072. */
  27073. Scene.prototype.getLastMeshByID = function (id) {
  27074. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27075. if (this.meshes[index].id === id) {
  27076. return this.meshes[index];
  27077. }
  27078. }
  27079. return null;
  27080. };
  27081. /**
  27082. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27083. * @param id defines the id to search for
  27084. * @return the found node or null if not found at all
  27085. */
  27086. Scene.prototype.getLastEntryByID = function (id) {
  27087. var index;
  27088. for (index = this.meshes.length - 1; index >= 0; index--) {
  27089. if (this.meshes[index].id === id) {
  27090. return this.meshes[index];
  27091. }
  27092. }
  27093. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27094. if (this.transformNodes[index].id === id) {
  27095. return this.transformNodes[index];
  27096. }
  27097. }
  27098. for (index = this.cameras.length - 1; index >= 0; index--) {
  27099. if (this.cameras[index].id === id) {
  27100. return this.cameras[index];
  27101. }
  27102. }
  27103. for (index = this.lights.length - 1; index >= 0; index--) {
  27104. if (this.lights[index].id === id) {
  27105. return this.lights[index];
  27106. }
  27107. }
  27108. return null;
  27109. };
  27110. /**
  27111. * Gets a node (Mesh, Camera, Light) using a given id
  27112. * @param id defines the id to search for
  27113. * @return the found node or null if not found at all
  27114. */
  27115. Scene.prototype.getNodeByID = function (id) {
  27116. var mesh = this.getMeshByID(id);
  27117. if (mesh) {
  27118. return mesh;
  27119. }
  27120. var light = this.getLightByID(id);
  27121. if (light) {
  27122. return light;
  27123. }
  27124. var camera = this.getCameraByID(id);
  27125. if (camera) {
  27126. return camera;
  27127. }
  27128. var bone = this.getBoneByID(id);
  27129. return bone;
  27130. };
  27131. /**
  27132. * Gets a node (Mesh, Camera, Light) using a given name
  27133. * @param name defines the name to search for
  27134. * @return the found node or null if not found at all.
  27135. */
  27136. Scene.prototype.getNodeByName = function (name) {
  27137. var mesh = this.getMeshByName(name);
  27138. if (mesh) {
  27139. return mesh;
  27140. }
  27141. var light = this.getLightByName(name);
  27142. if (light) {
  27143. return light;
  27144. }
  27145. var camera = this.getCameraByName(name);
  27146. if (camera) {
  27147. return camera;
  27148. }
  27149. var bone = this.getBoneByName(name);
  27150. return bone;
  27151. };
  27152. /**
  27153. * Gets a mesh using a given name
  27154. * @param name defines the name to search for
  27155. * @return the found mesh or null if not found at all.
  27156. */
  27157. Scene.prototype.getMeshByName = function (name) {
  27158. for (var index = 0; index < this.meshes.length; index++) {
  27159. if (this.meshes[index].name === name) {
  27160. return this.meshes[index];
  27161. }
  27162. }
  27163. return null;
  27164. };
  27165. /**
  27166. * Gets a transform node using a given name
  27167. * @param name defines the name to search for
  27168. * @return the found transform node or null if not found at all.
  27169. */
  27170. Scene.prototype.getTransformNodeByName = function (name) {
  27171. for (var index = 0; index < this.transformNodes.length; index++) {
  27172. if (this.transformNodes[index].name === name) {
  27173. return this.transformNodes[index];
  27174. }
  27175. }
  27176. return null;
  27177. };
  27178. /**
  27179. * Gets a sound using a given name
  27180. * @param name defines the name to search for
  27181. * @return the found sound or null if not found at all.
  27182. */
  27183. Scene.prototype.getSoundByName = function (name) {
  27184. var index;
  27185. if (BABYLON.AudioEngine) {
  27186. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27187. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27188. return this.mainSoundTrack.soundCollection[index];
  27189. }
  27190. }
  27191. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27192. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27193. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27194. return this.soundTracks[sdIndex].soundCollection[index];
  27195. }
  27196. }
  27197. }
  27198. }
  27199. return null;
  27200. };
  27201. /**
  27202. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27203. * @param id defines the id to search for
  27204. * @return the found skeleton or null if not found at all.
  27205. */
  27206. Scene.prototype.getLastSkeletonByID = function (id) {
  27207. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27208. if (this.skeletons[index].id === id) {
  27209. return this.skeletons[index];
  27210. }
  27211. }
  27212. return null;
  27213. };
  27214. /**
  27215. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27216. * @param id defines the id to search for
  27217. * @return the found skeleton or null if not found at all.
  27218. */
  27219. Scene.prototype.getSkeletonById = function (id) {
  27220. for (var index = 0; index < this.skeletons.length; index++) {
  27221. if (this.skeletons[index].id === id) {
  27222. return this.skeletons[index];
  27223. }
  27224. }
  27225. return null;
  27226. };
  27227. /**
  27228. * Gets a skeleton using a given name
  27229. * @param name defines the name to search for
  27230. * @return the found skeleton or null if not found at all.
  27231. */
  27232. Scene.prototype.getSkeletonByName = function (name) {
  27233. for (var index = 0; index < this.skeletons.length; index++) {
  27234. if (this.skeletons[index].name === name) {
  27235. return this.skeletons[index];
  27236. }
  27237. }
  27238. return null;
  27239. };
  27240. /**
  27241. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27242. * @param id defines the id to search for
  27243. * @return the found morph target manager or null if not found at all.
  27244. */
  27245. Scene.prototype.getMorphTargetManagerById = function (id) {
  27246. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27247. if (this.morphTargetManagers[index].uniqueId === id) {
  27248. return this.morphTargetManagers[index];
  27249. }
  27250. }
  27251. return null;
  27252. };
  27253. /**
  27254. * Gets a boolean indicating if the given mesh is active
  27255. * @param mesh defines the mesh to look for
  27256. * @returns true if the mesh is in the active list
  27257. */
  27258. Scene.prototype.isActiveMesh = function (mesh) {
  27259. return (this._activeMeshes.indexOf(mesh) !== -1);
  27260. };
  27261. Object.defineProperty(Scene.prototype, "uid", {
  27262. /**
  27263. * Return a unique id as a string which can serve as an identifier for the scene
  27264. */
  27265. get: function () {
  27266. if (!this._uid) {
  27267. this._uid = BABYLON.Tools.RandomId();
  27268. }
  27269. return this._uid;
  27270. },
  27271. enumerable: true,
  27272. configurable: true
  27273. });
  27274. /**
  27275. * Add an externaly attached data from its key.
  27276. * This method call will fail and return false, if such key already exists.
  27277. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27278. * @param key the unique key that identifies the data
  27279. * @param data the data object to associate to the key for this Engine instance
  27280. * @return true if no such key were already present and the data was added successfully, false otherwise
  27281. */
  27282. Scene.prototype.addExternalData = function (key, data) {
  27283. if (!this._externalData) {
  27284. this._externalData = new BABYLON.StringDictionary();
  27285. }
  27286. return this._externalData.add(key, data);
  27287. };
  27288. /**
  27289. * Get an externaly attached data from its key
  27290. * @param key the unique key that identifies the data
  27291. * @return the associated data, if present (can be null), or undefined if not present
  27292. */
  27293. Scene.prototype.getExternalData = function (key) {
  27294. if (!this._externalData) {
  27295. return null;
  27296. }
  27297. return this._externalData.get(key);
  27298. };
  27299. /**
  27300. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27301. * @param key the unique key that identifies the data
  27302. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27303. * @return the associated data, can be null if the factory returned null.
  27304. */
  27305. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27306. if (!this._externalData) {
  27307. this._externalData = new BABYLON.StringDictionary();
  27308. }
  27309. return this._externalData.getOrAddWithFactory(key, factory);
  27310. };
  27311. /**
  27312. * Remove an externaly attached data from the Engine instance
  27313. * @param key the unique key that identifies the data
  27314. * @return true if the data was successfully removed, false if it doesn't exist
  27315. */
  27316. Scene.prototype.removeExternalData = function (key) {
  27317. return this._externalData.remove(key);
  27318. };
  27319. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27320. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27321. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27322. var step = _a[_i];
  27323. step.action(mesh, subMesh);
  27324. }
  27325. var material = subMesh.getMaterial();
  27326. if (material !== null && material !== undefined) {
  27327. // Render targets
  27328. if (material.getRenderTargetTextures !== undefined) {
  27329. if (this._processedMaterials.indexOf(material) === -1) {
  27330. this._processedMaterials.push(material);
  27331. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27332. }
  27333. }
  27334. // Dispatch
  27335. this._activeIndices.addCount(subMesh.indexCount, false);
  27336. this._renderingManager.dispatch(subMesh, mesh, material);
  27337. }
  27338. }
  27339. };
  27340. /**
  27341. * Clear the processed materials smart array preventing retention point in material dispose.
  27342. */
  27343. Scene.prototype.freeProcessedMaterials = function () {
  27344. this._processedMaterials.dispose();
  27345. };
  27346. /**
  27347. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27348. */
  27349. Scene.prototype.freeActiveMeshes = function () {
  27350. this._activeMeshes.dispose();
  27351. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27352. this.activeCamera._activeMeshes.dispose();
  27353. }
  27354. if (this.activeCameras) {
  27355. for (var i = 0; i < this.activeCameras.length; i++) {
  27356. var activeCamera = this.activeCameras[i];
  27357. if (activeCamera && activeCamera._activeMeshes) {
  27358. activeCamera._activeMeshes.dispose();
  27359. }
  27360. }
  27361. }
  27362. };
  27363. /**
  27364. * Clear the info related to rendering groups preventing retention points during dispose.
  27365. */
  27366. Scene.prototype.freeRenderingGroups = function () {
  27367. if (this._renderingManager) {
  27368. this._renderingManager.freeRenderingGroups();
  27369. }
  27370. if (this.textures) {
  27371. for (var i = 0; i < this.textures.length; i++) {
  27372. var texture = this.textures[i];
  27373. if (texture && texture.renderList) {
  27374. texture.freeRenderingGroups();
  27375. }
  27376. }
  27377. }
  27378. };
  27379. /** @hidden */
  27380. Scene.prototype._isInIntermediateRendering = function () {
  27381. return this._intermediateRendering;
  27382. };
  27383. /**
  27384. * Defines the current active mesh candidate provider
  27385. * @param provider defines the provider to use
  27386. */
  27387. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27388. this._activeMeshCandidateProvider = provider;
  27389. };
  27390. /**
  27391. * Gets the current active mesh candidate provider
  27392. * @returns the current active mesh candidate provider
  27393. */
  27394. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27395. return this._activeMeshCandidateProvider;
  27396. };
  27397. /**
  27398. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27399. * @returns the current scene
  27400. */
  27401. Scene.prototype.freezeActiveMeshes = function () {
  27402. if (!this.activeCamera) {
  27403. return this;
  27404. }
  27405. if (!this._frustumPlanes) {
  27406. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27407. }
  27408. this._evaluateActiveMeshes();
  27409. this._activeMeshesFrozen = true;
  27410. return this;
  27411. };
  27412. /**
  27413. * Use this function to restart evaluating active meshes on every frame
  27414. * @returns the current scene
  27415. */
  27416. Scene.prototype.unfreezeActiveMeshes = function () {
  27417. this._activeMeshesFrozen = false;
  27418. return this;
  27419. };
  27420. Scene.prototype._evaluateActiveMeshes = function () {
  27421. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27422. return;
  27423. }
  27424. if (!this.activeCamera) {
  27425. return;
  27426. }
  27427. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27428. this.activeCamera._activeMeshes.reset();
  27429. this._activeMeshes.reset();
  27430. this._renderingManager.reset();
  27431. this._processedMaterials.reset();
  27432. this._activeParticleSystems.reset();
  27433. this._activeSkeletons.reset();
  27434. this._softwareSkinnedMeshes.reset();
  27435. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27436. var step = _a[_i];
  27437. step.action();
  27438. }
  27439. // Meshes
  27440. var meshes;
  27441. var len;
  27442. var checkIsEnabled = true;
  27443. // Determine mesh candidates
  27444. if (this._activeMeshCandidateProvider !== undefined) {
  27445. // Use _activeMeshCandidateProvider
  27446. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27447. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27448. if (meshes !== undefined) {
  27449. len = meshes.length;
  27450. }
  27451. else {
  27452. len = 0;
  27453. }
  27454. }
  27455. else if (this._selectionOctree !== undefined) {
  27456. // Octree
  27457. var selection = this._selectionOctree.select(this._frustumPlanes);
  27458. meshes = selection.data;
  27459. len = selection.length;
  27460. }
  27461. else {
  27462. // Full scene traversal
  27463. len = this.meshes.length;
  27464. meshes = this.meshes;
  27465. }
  27466. // Check each mesh
  27467. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27468. mesh = meshes[meshIndex];
  27469. if (mesh.isBlocked) {
  27470. continue;
  27471. }
  27472. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27473. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27474. continue;
  27475. }
  27476. mesh.computeWorldMatrix();
  27477. // Intersections
  27478. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27479. this._meshesForIntersections.pushNoDuplicate(mesh);
  27480. }
  27481. // Switch to current LOD
  27482. meshLOD = mesh.getLOD(this.activeCamera);
  27483. if (meshLOD === undefined || meshLOD === null) {
  27484. continue;
  27485. }
  27486. mesh._preActivate();
  27487. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27488. this._activeMeshes.push(mesh);
  27489. this.activeCamera._activeMeshes.push(mesh);
  27490. mesh._activate(this._renderId);
  27491. if (meshLOD !== mesh) {
  27492. meshLOD._activate(this._renderId);
  27493. }
  27494. this._activeMesh(mesh, meshLOD);
  27495. }
  27496. }
  27497. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27498. // Particle systems
  27499. if (this.particlesEnabled) {
  27500. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27501. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27502. var particleSystem = this.particleSystems[particleIndex];
  27503. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27504. continue;
  27505. }
  27506. var emitter = particleSystem.emitter;
  27507. if (!emitter.position || emitter.isEnabled()) {
  27508. this._activeParticleSystems.push(particleSystem);
  27509. particleSystem.animate();
  27510. this._renderingManager.dispatchParticles(particleSystem);
  27511. }
  27512. }
  27513. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27514. }
  27515. };
  27516. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27517. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27518. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27519. mesh.skeleton.prepare();
  27520. }
  27521. if (!mesh.computeBonesUsingShaders) {
  27522. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27523. }
  27524. }
  27525. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27526. var step = _a[_i];
  27527. step.action(sourceMesh, mesh);
  27528. }
  27529. if (mesh !== undefined && mesh !== null
  27530. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27531. // Submeshes Octrees
  27532. var len;
  27533. var subMeshes;
  27534. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27535. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27536. len = intersections.length;
  27537. subMeshes = intersections.data;
  27538. }
  27539. else {
  27540. subMeshes = mesh.subMeshes;
  27541. len = subMeshes.length;
  27542. }
  27543. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27544. subMesh = subMeshes[subIndex];
  27545. this._evaluateSubMesh(subMesh, mesh);
  27546. }
  27547. }
  27548. };
  27549. /**
  27550. * Update the transform matrix to update from the current active camera
  27551. * @param force defines a boolean used to force the update even if cache is up to date
  27552. */
  27553. Scene.prototype.updateTransformMatrix = function (force) {
  27554. if (!this.activeCamera) {
  27555. return;
  27556. }
  27557. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27558. };
  27559. /**
  27560. * 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)
  27561. * @param alternateCamera defines the camera to use
  27562. */
  27563. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27564. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27565. };
  27566. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27567. if (camera && camera._skipRendering) {
  27568. return;
  27569. }
  27570. var engine = this._engine;
  27571. this.activeCamera = camera;
  27572. if (!this.activeCamera)
  27573. throw new Error("Active camera not set");
  27574. // Viewport
  27575. engine.setViewport(this.activeCamera.viewport);
  27576. // Camera
  27577. this.resetCachedMaterial();
  27578. this._renderId++;
  27579. this.updateTransformMatrix();
  27580. if (camera._alternateCamera) {
  27581. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27582. this._alternateRendering = true;
  27583. }
  27584. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27585. // Meshes
  27586. this._evaluateActiveMeshes();
  27587. // Software skinning
  27588. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27589. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27590. mesh.applySkeleton(mesh.skeleton);
  27591. }
  27592. // Render targets
  27593. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27594. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27595. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27596. }
  27597. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27598. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27599. }
  27600. if (this.renderTargetsEnabled) {
  27601. this._intermediateRendering = true;
  27602. if (this._renderTargets.length > 0) {
  27603. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27604. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27605. var renderTarget = this._renderTargets.data[renderIndex];
  27606. if (renderTarget._shouldRender()) {
  27607. this._renderId++;
  27608. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27609. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27610. }
  27611. }
  27612. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27613. this._renderId++;
  27614. }
  27615. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27616. var step = _a[_i];
  27617. step.action(this.activeCamera);
  27618. }
  27619. this._intermediateRendering = false;
  27620. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27621. }
  27622. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27623. // Prepare Frame
  27624. if (this.postProcessManager) {
  27625. this.postProcessManager._prepareFrame();
  27626. }
  27627. // Before Camera Draw
  27628. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27629. var step = _c[_b];
  27630. step.action(this.activeCamera);
  27631. }
  27632. // Render
  27633. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27634. this._renderingManager.render(null, null, true, true);
  27635. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27636. // After Camera Draw
  27637. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27638. var step = _e[_d];
  27639. step.action(this.activeCamera);
  27640. }
  27641. // Finalize frame
  27642. if (this.postProcessManager) {
  27643. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27644. }
  27645. // Reset some special arrays
  27646. this._renderTargets.reset();
  27647. this._alternateRendering = false;
  27648. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27649. };
  27650. Scene.prototype._processSubCameras = function (camera) {
  27651. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27652. this._renderForCamera(camera);
  27653. return;
  27654. }
  27655. // rig cameras
  27656. for (var index = 0; index < camera._rigCameras.length; index++) {
  27657. this._renderForCamera(camera._rigCameras[index], camera);
  27658. }
  27659. this.activeCamera = camera;
  27660. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27661. };
  27662. Scene.prototype._checkIntersections = function () {
  27663. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27664. var sourceMesh = this._meshesForIntersections.data[index];
  27665. if (!sourceMesh.actionManager) {
  27666. continue;
  27667. }
  27668. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27669. var action = sourceMesh.actionManager.actions[actionIndex];
  27670. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27671. var parameters = action.getTriggerParameter();
  27672. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27673. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27674. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27675. if (areIntersecting && currentIntersectionInProgress === -1) {
  27676. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27677. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27678. sourceMesh._intersectionsInProgress.push(otherMesh);
  27679. }
  27680. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27681. sourceMesh._intersectionsInProgress.push(otherMesh);
  27682. }
  27683. }
  27684. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27685. //They intersected, and now they don't.
  27686. //is this trigger an exit trigger? execute an event.
  27687. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27688. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27689. }
  27690. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27691. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27692. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27693. return otherMesh === parameterMesh;
  27694. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27695. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27696. }
  27697. }
  27698. }
  27699. }
  27700. }
  27701. };
  27702. /**
  27703. * Render the scene
  27704. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27705. */
  27706. Scene.prototype.render = function (updateCameras) {
  27707. if (updateCameras === void 0) { updateCameras = true; }
  27708. if (this.isDisposed) {
  27709. return;
  27710. }
  27711. // Register components that have been associated lately to the scene.
  27712. this._registerTransientComponents();
  27713. this._activeParticles.fetchNewFrame();
  27714. this._totalVertices.fetchNewFrame();
  27715. this._activeIndices.fetchNewFrame();
  27716. this._activeBones.fetchNewFrame();
  27717. this._meshesForIntersections.reset();
  27718. this.resetCachedMaterial();
  27719. this.onBeforeAnimationsObservable.notifyObservers(this);
  27720. // Actions
  27721. if (this.actionManager) {
  27722. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27723. }
  27724. if (this._engine.isDeterministicLockStep()) {
  27725. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27726. var defaultFPS = (60.0 / 1000.0);
  27727. var defaultFrameTime = 1000 / 60; // frame time in MS
  27728. if (this._physicsEngine) {
  27729. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27730. }
  27731. var stepsTaken = 0;
  27732. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27733. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27734. internalSteps = Math.min(internalSteps, maxSubSteps);
  27735. do {
  27736. this.onBeforeStepObservable.notifyObservers(this);
  27737. // Animations
  27738. this._animationRatio = defaultFrameTime * defaultFPS;
  27739. this._animate();
  27740. this.onAfterAnimationsObservable.notifyObservers(this);
  27741. // Physics
  27742. if (this._physicsEngine) {
  27743. this.onBeforePhysicsObservable.notifyObservers(this);
  27744. this._physicsEngine._step(defaultFrameTime / 1000);
  27745. this.onAfterPhysicsObservable.notifyObservers(this);
  27746. }
  27747. this.onAfterStepObservable.notifyObservers(this);
  27748. this._currentStepId++;
  27749. stepsTaken++;
  27750. deltaTime -= defaultFrameTime;
  27751. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27752. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27753. }
  27754. else {
  27755. // Animations
  27756. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27757. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27758. this._animate();
  27759. this.onAfterAnimationsObservable.notifyObservers(this);
  27760. // Physics
  27761. if (this._physicsEngine) {
  27762. this.onBeforePhysicsObservable.notifyObservers(this);
  27763. this._physicsEngine._step(deltaTime / 1000.0);
  27764. this.onAfterPhysicsObservable.notifyObservers(this);
  27765. }
  27766. }
  27767. // Before camera update steps
  27768. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27769. var step = _a[_i];
  27770. step.action();
  27771. }
  27772. // Update Cameras
  27773. if (updateCameras) {
  27774. if (this.activeCameras.length > 0) {
  27775. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27776. var camera = this.activeCameras[cameraIndex];
  27777. camera.update();
  27778. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27779. // rig cameras
  27780. for (var index = 0; index < camera._rigCameras.length; index++) {
  27781. camera._rigCameras[index].update();
  27782. }
  27783. }
  27784. }
  27785. }
  27786. else if (this.activeCamera) {
  27787. this.activeCamera.update();
  27788. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27789. // rig cameras
  27790. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27791. this.activeCamera._rigCameras[index].update();
  27792. }
  27793. }
  27794. }
  27795. }
  27796. // Before render
  27797. this.onBeforeRenderObservable.notifyObservers(this);
  27798. // Customs render targets
  27799. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27800. var engine = this.getEngine();
  27801. var currentActiveCamera = this.activeCamera;
  27802. if (this.renderTargetsEnabled) {
  27803. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27804. this._intermediateRendering = true;
  27805. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27806. var renderTarget = this.customRenderTargets[customIndex];
  27807. if (renderTarget._shouldRender()) {
  27808. this._renderId++;
  27809. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27810. if (!this.activeCamera)
  27811. throw new Error("Active camera not set");
  27812. // Viewport
  27813. engine.setViewport(this.activeCamera.viewport);
  27814. // Camera
  27815. this.updateTransformMatrix();
  27816. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27817. }
  27818. }
  27819. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27820. this._intermediateRendering = false;
  27821. this._renderId++;
  27822. }
  27823. // Restore back buffer
  27824. if (this.customRenderTargets.length > 0) {
  27825. engine.restoreDefaultFramebuffer();
  27826. }
  27827. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27828. this.activeCamera = currentActiveCamera;
  27829. // Procedural textures
  27830. if (this.proceduralTexturesEnabled) {
  27831. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27832. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27833. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27834. if (proceduralTexture._shouldRender()) {
  27835. proceduralTexture.render();
  27836. }
  27837. }
  27838. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27839. }
  27840. // Clear
  27841. if (this.autoClearDepthAndStencil || this.autoClear) {
  27842. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27843. }
  27844. // Shadows
  27845. if (this.shadowsEnabled) {
  27846. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27847. var light = this.lights[lightIndex];
  27848. var shadowGenerator = light.getShadowGenerator();
  27849. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27850. var shadowMap = (shadowGenerator.getShadowMap());
  27851. if (this.textures.indexOf(shadowMap) !== -1) {
  27852. this._renderTargets.push(shadowMap);
  27853. }
  27854. }
  27855. }
  27856. }
  27857. // Collects render targets from external components.
  27858. for (var _b = 0, _c = this._gatherRenderTargetsStage; _b < _c.length; _b++) {
  27859. var step = _c[_b];
  27860. step.action(this._renderTargets);
  27861. }
  27862. // Multi-cameras?
  27863. if (this.activeCameras.length > 0) {
  27864. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27865. if (cameraIndex > 0) {
  27866. this._engine.clear(null, false, true, true);
  27867. }
  27868. this._processSubCameras(this.activeCameras[cameraIndex]);
  27869. }
  27870. }
  27871. else {
  27872. if (!this.activeCamera) {
  27873. throw new Error("No camera defined");
  27874. }
  27875. this._processSubCameras(this.activeCamera);
  27876. }
  27877. // Intersection checks
  27878. this._checkIntersections();
  27879. // Update the audio listener attached to the camera
  27880. if (BABYLON.AudioEngine) {
  27881. this._updateAudioParameters();
  27882. }
  27883. // After render
  27884. if (this.afterRender) {
  27885. this.afterRender();
  27886. }
  27887. this.onAfterRenderObservable.notifyObservers(this);
  27888. // Cleaning
  27889. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27890. var data = this._toBeDisposed.data[index];
  27891. if (data) {
  27892. data.dispose();
  27893. }
  27894. this._toBeDisposed[index] = null;
  27895. }
  27896. this._toBeDisposed.reset();
  27897. if (this.dumpNextRenderTargets) {
  27898. this.dumpNextRenderTargets = false;
  27899. }
  27900. this._activeBones.addCount(0, true);
  27901. this._activeIndices.addCount(0, true);
  27902. this._activeParticles.addCount(0, true);
  27903. };
  27904. Scene.prototype._updateAudioParameters = function () {
  27905. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27906. return;
  27907. }
  27908. var listeningCamera;
  27909. var audioEngine = BABYLON.Engine.audioEngine;
  27910. if (this.activeCameras.length > 0) {
  27911. listeningCamera = this.activeCameras[0];
  27912. }
  27913. else {
  27914. listeningCamera = this.activeCamera;
  27915. }
  27916. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27917. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27918. // for VR cameras
  27919. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27920. listeningCamera = listeningCamera.rigCameras[0];
  27921. }
  27922. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27923. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27924. cameraDirection.normalize();
  27925. // To avoid some errors on GearVR
  27926. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27927. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27928. }
  27929. var i;
  27930. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27931. var sound = this.mainSoundTrack.soundCollection[i];
  27932. if (sound.useCustomAttenuation) {
  27933. sound.updateDistanceFromListener();
  27934. }
  27935. }
  27936. for (i = 0; i < this.soundTracks.length; i++) {
  27937. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27938. sound = this.soundTracks[i].soundCollection[j];
  27939. if (sound.useCustomAttenuation) {
  27940. sound.updateDistanceFromListener();
  27941. }
  27942. }
  27943. }
  27944. }
  27945. };
  27946. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27947. // Audio
  27948. /**
  27949. * Gets or sets if audio support is enabled
  27950. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27951. */
  27952. get: function () {
  27953. return this._audioEnabled;
  27954. },
  27955. set: function (value) {
  27956. this._audioEnabled = value;
  27957. if (BABYLON.AudioEngine) {
  27958. if (this._audioEnabled) {
  27959. this._enableAudio();
  27960. }
  27961. else {
  27962. this._disableAudio();
  27963. }
  27964. }
  27965. },
  27966. enumerable: true,
  27967. configurable: true
  27968. });
  27969. Scene.prototype._disableAudio = function () {
  27970. var i;
  27971. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27972. this.mainSoundTrack.soundCollection[i].pause();
  27973. }
  27974. for (i = 0; i < this.soundTracks.length; i++) {
  27975. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27976. this.soundTracks[i].soundCollection[j].pause();
  27977. }
  27978. }
  27979. };
  27980. Scene.prototype._enableAudio = function () {
  27981. var i;
  27982. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27983. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27984. this.mainSoundTrack.soundCollection[i].play();
  27985. }
  27986. }
  27987. for (i = 0; i < this.soundTracks.length; i++) {
  27988. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27989. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27990. this.soundTracks[i].soundCollection[j].play();
  27991. }
  27992. }
  27993. }
  27994. };
  27995. Object.defineProperty(Scene.prototype, "headphone", {
  27996. /**
  27997. * Gets or sets if audio will be output to headphones
  27998. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27999. */
  28000. get: function () {
  28001. return this._headphone;
  28002. },
  28003. set: function (value) {
  28004. this._headphone = value;
  28005. if (BABYLON.AudioEngine) {
  28006. if (this._headphone) {
  28007. this._switchAudioModeForHeadphones();
  28008. }
  28009. else {
  28010. this._switchAudioModeForNormalSpeakers();
  28011. }
  28012. }
  28013. },
  28014. enumerable: true,
  28015. configurable: true
  28016. });
  28017. Scene.prototype._switchAudioModeForHeadphones = function () {
  28018. this.mainSoundTrack.switchPanningModelToHRTF();
  28019. for (var i = 0; i < this.soundTracks.length; i++) {
  28020. this.soundTracks[i].switchPanningModelToHRTF();
  28021. }
  28022. };
  28023. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28024. this.mainSoundTrack.switchPanningModelToEqualPower();
  28025. for (var i = 0; i < this.soundTracks.length; i++) {
  28026. this.soundTracks[i].switchPanningModelToEqualPower();
  28027. }
  28028. };
  28029. /**
  28030. * Freeze all materials
  28031. * A frozen material will not be updatable but should be faster to render
  28032. */
  28033. Scene.prototype.freezeMaterials = function () {
  28034. for (var i = 0; i < this.materials.length; i++) {
  28035. this.materials[i].freeze();
  28036. }
  28037. };
  28038. /**
  28039. * Unfreeze all materials
  28040. * A frozen material will not be updatable but should be faster to render
  28041. */
  28042. Scene.prototype.unfreezeMaterials = function () {
  28043. for (var i = 0; i < this.materials.length; i++) {
  28044. this.materials[i].unfreeze();
  28045. }
  28046. };
  28047. /**
  28048. * Releases all held ressources
  28049. */
  28050. Scene.prototype.dispose = function () {
  28051. this.beforeRender = null;
  28052. this.afterRender = null;
  28053. this.skeletons = [];
  28054. this.morphTargetManagers = [];
  28055. this._transientComponents = [];
  28056. this._isReadyForMeshStage.clear();
  28057. this._beforeEvaluateActiveMeshStage.clear();
  28058. this._evaluateSubMeshStage.clear();
  28059. this._activeMeshStage.clear();
  28060. this._cameraDrawRenderTargetStage.clear();
  28061. this._beforeCameraDrawStage.clear();
  28062. this._beforeRenderingGroupDrawStage.clear();
  28063. this._afterRenderingGroupDrawStage.clear();
  28064. this._afterCameraDrawStage.clear();
  28065. this._beforeCameraUpdateStage.clear();
  28066. this._gatherRenderTargetsStage.clear();
  28067. this._rebuildGeometryStage.clear();
  28068. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28069. var component = _a[_i];
  28070. component.dispose();
  28071. }
  28072. this.importedMeshesFiles = new Array();
  28073. this.stopAllAnimations();
  28074. this.resetCachedMaterial();
  28075. // Smart arrays
  28076. if (this.activeCamera) {
  28077. this.activeCamera._activeMeshes.dispose();
  28078. this.activeCamera = null;
  28079. }
  28080. this._activeMeshes.dispose();
  28081. this._renderingManager.dispose();
  28082. this._processedMaterials.dispose();
  28083. this._activeParticleSystems.dispose();
  28084. this._activeSkeletons.dispose();
  28085. this._softwareSkinnedMeshes.dispose();
  28086. this._renderTargets.dispose();
  28087. this._registeredForLateAnimationBindings.dispose();
  28088. this._meshesForIntersections.dispose();
  28089. this._toBeDisposed.dispose();
  28090. // Abort active requests
  28091. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28092. var request = _c[_b];
  28093. request.abort();
  28094. }
  28095. // Debug layer
  28096. if (this._debugLayer) {
  28097. this._debugLayer.hide();
  28098. }
  28099. // Events
  28100. this.onDisposeObservable.notifyObservers(this);
  28101. this.onDisposeObservable.clear();
  28102. this.onBeforeRenderObservable.clear();
  28103. this.onAfterRenderObservable.clear();
  28104. this.onBeforeRenderTargetsRenderObservable.clear();
  28105. this.onAfterRenderTargetsRenderObservable.clear();
  28106. this.onAfterStepObservable.clear();
  28107. this.onBeforeStepObservable.clear();
  28108. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28109. this.onAfterActiveMeshesEvaluationObservable.clear();
  28110. this.onBeforeParticlesRenderingObservable.clear();
  28111. this.onAfterParticlesRenderingObservable.clear();
  28112. this.onBeforeSpritesRenderingObservable.clear();
  28113. this.onAfterSpritesRenderingObservable.clear();
  28114. this.onBeforeDrawPhaseObservable.clear();
  28115. this.onAfterDrawPhaseObservable.clear();
  28116. this.onBeforePhysicsObservable.clear();
  28117. this.onAfterPhysicsObservable.clear();
  28118. this.onBeforeAnimationsObservable.clear();
  28119. this.onAfterAnimationsObservable.clear();
  28120. this.onDataLoadedObservable.clear();
  28121. this.onBeforeRenderingGroupObservable.clear();
  28122. this.onAfterRenderingGroupObservable.clear();
  28123. this.detachControl();
  28124. // Release sounds & sounds tracks
  28125. if (BABYLON.AudioEngine) {
  28126. this.disposeSounds();
  28127. }
  28128. // VR Helper
  28129. if (this.VRHelper) {
  28130. this.VRHelper.dispose();
  28131. }
  28132. // Detach cameras
  28133. var canvas = this._engine.getRenderingCanvas();
  28134. if (canvas) {
  28135. var index;
  28136. for (index = 0; index < this.cameras.length; index++) {
  28137. this.cameras[index].detachControl(canvas);
  28138. }
  28139. }
  28140. // Release animation groups
  28141. while (this.animationGroups.length) {
  28142. this.animationGroups[0].dispose();
  28143. }
  28144. // Release lights
  28145. while (this.lights.length) {
  28146. this.lights[0].dispose();
  28147. }
  28148. // Release meshes
  28149. while (this.meshes.length) {
  28150. this.meshes[0].dispose(true);
  28151. }
  28152. while (this.transformNodes.length) {
  28153. this.removeTransformNode(this.transformNodes[0]);
  28154. }
  28155. // Release cameras
  28156. while (this.cameras.length) {
  28157. this.cameras[0].dispose();
  28158. }
  28159. // Release materials
  28160. if (this.defaultMaterial) {
  28161. this.defaultMaterial.dispose();
  28162. }
  28163. while (this.multiMaterials.length) {
  28164. this.multiMaterials[0].dispose();
  28165. }
  28166. while (this.materials.length) {
  28167. this.materials[0].dispose();
  28168. }
  28169. // Release particles
  28170. while (this.particleSystems.length) {
  28171. this.particleSystems[0].dispose();
  28172. }
  28173. // Release sprites
  28174. while (this.spriteManagers.length) {
  28175. this.spriteManagers[0].dispose();
  28176. }
  28177. // Release postProcesses
  28178. while (this.postProcesses.length) {
  28179. this.postProcesses[0].dispose();
  28180. }
  28181. // Release textures
  28182. while (this.textures.length) {
  28183. this.textures[0].dispose();
  28184. }
  28185. // Release UBO
  28186. this._sceneUbo.dispose();
  28187. if (this._alternateSceneUbo) {
  28188. this._alternateSceneUbo.dispose();
  28189. }
  28190. // Post-processes
  28191. this.postProcessManager.dispose();
  28192. // Physics
  28193. if (this._physicsEngine) {
  28194. this.disablePhysicsEngine();
  28195. }
  28196. // Remove from engine
  28197. index = this._engine.scenes.indexOf(this);
  28198. if (index > -1) {
  28199. this._engine.scenes.splice(index, 1);
  28200. }
  28201. this._engine.wipeCaches(true);
  28202. this._isDisposed = true;
  28203. };
  28204. Object.defineProperty(Scene.prototype, "isDisposed", {
  28205. /**
  28206. * Gets if the scene is already disposed
  28207. */
  28208. get: function () {
  28209. return this._isDisposed;
  28210. },
  28211. enumerable: true,
  28212. configurable: true
  28213. });
  28214. /**
  28215. * Releases sounds & soundtracks
  28216. */
  28217. Scene.prototype.disposeSounds = function () {
  28218. if (!this._mainSoundTrack) {
  28219. return;
  28220. }
  28221. this.mainSoundTrack.dispose();
  28222. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28223. this.soundTracks[scIndex].dispose();
  28224. }
  28225. };
  28226. /**
  28227. * Call this function to reduce memory footprint of the scene.
  28228. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28229. */
  28230. Scene.prototype.clearCachedVertexData = function () {
  28231. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28232. var mesh = this.meshes[meshIndex];
  28233. var geometry = mesh.geometry;
  28234. if (geometry) {
  28235. geometry._indices = [];
  28236. for (var vbName in geometry._vertexBuffers) {
  28237. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28238. continue;
  28239. }
  28240. geometry._vertexBuffers[vbName]._buffer._data = null;
  28241. }
  28242. }
  28243. }
  28244. };
  28245. /**
  28246. * This function will remove the local cached buffer data from texture.
  28247. * It will save memory but will prevent the texture from being rebuilt
  28248. */
  28249. Scene.prototype.cleanCachedTextureBuffer = function () {
  28250. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28251. var baseTexture = _a[_i];
  28252. var buffer = baseTexture._buffer;
  28253. if (buffer) {
  28254. baseTexture._buffer = null;
  28255. }
  28256. }
  28257. };
  28258. // Octrees
  28259. /**
  28260. * Get the world extend vectors with an optional filter
  28261. *
  28262. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28263. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28264. */
  28265. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28266. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28267. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28268. filterPredicate = filterPredicate || (function () { return true; });
  28269. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28270. mesh.computeWorldMatrix(true);
  28271. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28272. return;
  28273. }
  28274. var boundingInfo = mesh.getBoundingInfo();
  28275. var minBox = boundingInfo.boundingBox.minimumWorld;
  28276. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28277. BABYLON.Tools.CheckExtends(minBox, min, max);
  28278. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28279. });
  28280. return {
  28281. min: min,
  28282. max: max
  28283. };
  28284. };
  28285. /**
  28286. * Creates or updates the octree used to boost selection (picking)
  28287. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28288. * @param maxCapacity defines the maximum capacity per leaf
  28289. * @param maxDepth defines the maximum depth of the octree
  28290. * @returns an octree of AbstractMesh
  28291. */
  28292. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28293. if (maxCapacity === void 0) { maxCapacity = 64; }
  28294. if (maxDepth === void 0) { maxDepth = 2; }
  28295. if (!this._selectionOctree) {
  28296. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28297. }
  28298. var worldExtends = this.getWorldExtends();
  28299. // Update octree
  28300. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28301. return this._selectionOctree;
  28302. };
  28303. // Picking
  28304. /**
  28305. * Creates a ray that can be used to pick in the scene
  28306. * @param x defines the x coordinate of the origin (on-screen)
  28307. * @param y defines the y coordinate of the origin (on-screen)
  28308. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28309. * @param camera defines the camera to use for the picking
  28310. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28311. * @returns a Ray
  28312. */
  28313. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28314. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28315. var result = BABYLON.Ray.Zero();
  28316. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28317. return result;
  28318. };
  28319. /**
  28320. * Creates a ray that can be used to pick in the scene
  28321. * @param x defines the x coordinate of the origin (on-screen)
  28322. * @param y defines the y coordinate of the origin (on-screen)
  28323. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28324. * @param result defines the ray where to store the picking ray
  28325. * @param camera defines the camera to use for the picking
  28326. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28327. * @returns the current scene
  28328. */
  28329. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28330. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28331. var engine = this._engine;
  28332. if (!camera) {
  28333. if (!this.activeCamera)
  28334. throw new Error("Active camera not set");
  28335. camera = this.activeCamera;
  28336. }
  28337. var cameraViewport = camera.viewport;
  28338. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28339. // Moving coordinates to local viewport world
  28340. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28341. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28342. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28343. return this;
  28344. };
  28345. /**
  28346. * Creates a ray that can be used to pick in the scene
  28347. * @param x defines the x coordinate of the origin (on-screen)
  28348. * @param y defines the y coordinate of the origin (on-screen)
  28349. * @param camera defines the camera to use for the picking
  28350. * @returns a Ray
  28351. */
  28352. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28353. var result = BABYLON.Ray.Zero();
  28354. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28355. return result;
  28356. };
  28357. /**
  28358. * Creates a ray that can be used to pick in the scene
  28359. * @param x defines the x coordinate of the origin (on-screen)
  28360. * @param y defines the y coordinate of the origin (on-screen)
  28361. * @param result defines the ray where to store the picking ray
  28362. * @param camera defines the camera to use for the picking
  28363. * @returns the current scene
  28364. */
  28365. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28366. if (!BABYLON.PickingInfo) {
  28367. return this;
  28368. }
  28369. var engine = this._engine;
  28370. if (!camera) {
  28371. if (!this.activeCamera)
  28372. throw new Error("Active camera not set");
  28373. camera = this.activeCamera;
  28374. }
  28375. var cameraViewport = camera.viewport;
  28376. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28377. var identity = BABYLON.Matrix.Identity();
  28378. // Moving coordinates to local viewport world
  28379. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28380. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28381. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28382. return this;
  28383. };
  28384. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28385. if (!BABYLON.PickingInfo) {
  28386. return null;
  28387. }
  28388. var pickingInfo = null;
  28389. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28390. var mesh = this.meshes[meshIndex];
  28391. if (predicate) {
  28392. if (!predicate(mesh)) {
  28393. continue;
  28394. }
  28395. }
  28396. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28397. continue;
  28398. }
  28399. var world = mesh.getWorldMatrix();
  28400. var ray = rayFunction(world);
  28401. var result = mesh.intersects(ray, fastCheck);
  28402. if (!result || !result.hit)
  28403. continue;
  28404. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28405. continue;
  28406. pickingInfo = result;
  28407. if (fastCheck) {
  28408. break;
  28409. }
  28410. }
  28411. return pickingInfo || new BABYLON.PickingInfo();
  28412. };
  28413. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28414. if (!BABYLON.PickingInfo) {
  28415. return null;
  28416. }
  28417. var pickingInfos = new Array();
  28418. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28419. var mesh = this.meshes[meshIndex];
  28420. if (predicate) {
  28421. if (!predicate(mesh)) {
  28422. continue;
  28423. }
  28424. }
  28425. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28426. continue;
  28427. }
  28428. var world = mesh.getWorldMatrix();
  28429. var ray = rayFunction(world);
  28430. var result = mesh.intersects(ray, false);
  28431. if (!result || !result.hit)
  28432. continue;
  28433. pickingInfos.push(result);
  28434. }
  28435. return pickingInfos;
  28436. };
  28437. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28438. if (!BABYLON.PickingInfo) {
  28439. return null;
  28440. }
  28441. var pickingInfo = null;
  28442. if (!camera) {
  28443. if (!this.activeCamera) {
  28444. return null;
  28445. }
  28446. camera = this.activeCamera;
  28447. }
  28448. if (this.spriteManagers.length > 0) {
  28449. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28450. var spriteManager = this.spriteManagers[spriteIndex];
  28451. if (!spriteManager.isPickable) {
  28452. continue;
  28453. }
  28454. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28455. if (!result || !result.hit)
  28456. continue;
  28457. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28458. continue;
  28459. pickingInfo = result;
  28460. if (fastCheck) {
  28461. break;
  28462. }
  28463. }
  28464. }
  28465. return pickingInfo || new BABYLON.PickingInfo();
  28466. };
  28467. /** Launch a ray to try to pick a mesh in the scene
  28468. * @param x position on screen
  28469. * @param y position on screen
  28470. * @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
  28471. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28472. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28473. * @returns a PickingInfo
  28474. */
  28475. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28476. var _this = this;
  28477. if (!BABYLON.PickingInfo) {
  28478. return null;
  28479. }
  28480. var result = this._internalPick(function (world) {
  28481. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28482. return _this._tempPickingRay;
  28483. }, predicate, fastCheck);
  28484. if (result) {
  28485. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28486. }
  28487. return result;
  28488. };
  28489. /** Launch a ray to try to pick a sprite in the scene
  28490. * @param x position on screen
  28491. * @param y position on screen
  28492. * @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
  28493. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28494. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28495. * @returns a PickingInfo
  28496. */
  28497. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28498. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28499. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28500. };
  28501. /** Use the given ray to pick a mesh in the scene
  28502. * @param ray The ray to use to pick meshes
  28503. * @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
  28504. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28505. * @returns a PickingInfo
  28506. */
  28507. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28508. var _this = this;
  28509. var result = this._internalPick(function (world) {
  28510. if (!_this._pickWithRayInverseMatrix) {
  28511. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28512. }
  28513. world.invertToRef(_this._pickWithRayInverseMatrix);
  28514. if (!_this._cachedRayForTransform) {
  28515. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28516. }
  28517. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28518. return _this._cachedRayForTransform;
  28519. }, predicate, fastCheck);
  28520. if (result) {
  28521. result.ray = ray;
  28522. }
  28523. return result;
  28524. };
  28525. /**
  28526. * Launch a ray to try to pick a mesh in the scene
  28527. * @param x X position on screen
  28528. * @param y Y position on screen
  28529. * @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
  28530. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28531. * @returns an array of PickingInfo
  28532. */
  28533. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28534. var _this = this;
  28535. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28536. };
  28537. /**
  28538. * Launch a ray to try to pick a mesh in the scene
  28539. * @param ray Ray to use
  28540. * @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
  28541. * @returns an array of PickingInfo
  28542. */
  28543. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28544. var _this = this;
  28545. return this._internalMultiPick(function (world) {
  28546. if (!_this._pickWithRayInverseMatrix) {
  28547. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28548. }
  28549. world.invertToRef(_this._pickWithRayInverseMatrix);
  28550. if (!_this._cachedRayForTransform) {
  28551. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28552. }
  28553. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28554. return _this._cachedRayForTransform;
  28555. }, predicate);
  28556. };
  28557. /**
  28558. * Force the value of meshUnderPointer
  28559. * @param mesh defines the mesh to use
  28560. */
  28561. Scene.prototype.setPointerOverMesh = function (mesh) {
  28562. if (this._pointerOverMesh === mesh) {
  28563. return;
  28564. }
  28565. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28566. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28567. }
  28568. this._pointerOverMesh = mesh;
  28569. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28570. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28571. }
  28572. };
  28573. /**
  28574. * Gets the mesh under the pointer
  28575. * @returns a Mesh or null if no mesh is under the pointer
  28576. */
  28577. Scene.prototype.getPointerOverMesh = function () {
  28578. return this._pointerOverMesh;
  28579. };
  28580. /**
  28581. * Force the sprite under the pointer
  28582. * @param sprite defines the sprite to use
  28583. */
  28584. Scene.prototype.setPointerOverSprite = function (sprite) {
  28585. if (this._pointerOverSprite === sprite) {
  28586. return;
  28587. }
  28588. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28589. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28590. }
  28591. this._pointerOverSprite = sprite;
  28592. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28593. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28594. }
  28595. };
  28596. /**
  28597. * Gets the sprite under the pointer
  28598. * @returns a Sprite or null if no sprite is under the pointer
  28599. */
  28600. Scene.prototype.getPointerOverSprite = function () {
  28601. return this._pointerOverSprite;
  28602. };
  28603. // Physics
  28604. /**
  28605. * Gets the current physics engine
  28606. * @returns a PhysicsEngine or null if none attached
  28607. */
  28608. Scene.prototype.getPhysicsEngine = function () {
  28609. return this._physicsEngine;
  28610. };
  28611. /**
  28612. * Enables physics to the current scene
  28613. * @param gravity defines the scene's gravity for the physics engine
  28614. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28615. * @return a boolean indicating if the physics engine was initialized
  28616. */
  28617. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28618. if (gravity === void 0) { gravity = null; }
  28619. if (this._physicsEngine) {
  28620. return true;
  28621. }
  28622. try {
  28623. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28624. return true;
  28625. }
  28626. catch (e) {
  28627. BABYLON.Tools.Error(e.message);
  28628. return false;
  28629. }
  28630. };
  28631. /**
  28632. * Disables and disposes the physics engine associated with the scene
  28633. */
  28634. Scene.prototype.disablePhysicsEngine = function () {
  28635. if (!this._physicsEngine) {
  28636. return;
  28637. }
  28638. this._physicsEngine.dispose();
  28639. this._physicsEngine = null;
  28640. };
  28641. /**
  28642. * Gets a boolean indicating if there is an active physics engine
  28643. * @returns a boolean indicating if there is an active physics engine
  28644. */
  28645. Scene.prototype.isPhysicsEnabled = function () {
  28646. return this._physicsEngine !== undefined;
  28647. };
  28648. /**
  28649. * Deletes a physics compound impostor
  28650. * @param compound defines the compound to delete
  28651. */
  28652. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28653. var mesh = compound.parts[0].mesh;
  28654. if (mesh.physicsImpostor) {
  28655. mesh.physicsImpostor.dispose( /*true*/);
  28656. mesh.physicsImpostor = null;
  28657. }
  28658. };
  28659. // Misc.
  28660. /** @hidden */
  28661. Scene.prototype._rebuildGeometries = function () {
  28662. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28663. var geometry = _a[_i];
  28664. geometry._rebuild();
  28665. }
  28666. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28667. var mesh = _c[_b];
  28668. mesh._rebuild();
  28669. }
  28670. if (this.postProcessManager) {
  28671. this.postProcessManager._rebuild();
  28672. }
  28673. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28674. var component = _e[_d];
  28675. component.rebuild();
  28676. }
  28677. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28678. var system = _g[_f];
  28679. system.rebuild();
  28680. }
  28681. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28682. var step = _j[_h];
  28683. step.action();
  28684. }
  28685. };
  28686. /** @hidden */
  28687. Scene.prototype._rebuildTextures = function () {
  28688. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28689. var texture = _a[_i];
  28690. texture._rebuild();
  28691. }
  28692. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28693. };
  28694. /**
  28695. * Creates a default light for the scene.
  28696. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28697. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28698. */
  28699. Scene.prototype.createDefaultLight = function (replace) {
  28700. if (replace === void 0) { replace = false; }
  28701. // Dispose existing light in replace mode.
  28702. if (replace) {
  28703. if (this.lights) {
  28704. for (var i = 0; i < this.lights.length; i++) {
  28705. this.lights[i].dispose();
  28706. }
  28707. }
  28708. }
  28709. // Light
  28710. if (this.lights.length === 0) {
  28711. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28712. }
  28713. };
  28714. /**
  28715. * Creates a default camera for the scene.
  28716. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28717. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28718. * @param replace has default false, when true replaces the active camera in the scene
  28719. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28720. */
  28721. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28722. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28723. if (replace === void 0) { replace = false; }
  28724. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28725. // Dispose existing camera in replace mode.
  28726. if (replace) {
  28727. if (this.activeCamera) {
  28728. this.activeCamera.dispose();
  28729. this.activeCamera = null;
  28730. }
  28731. }
  28732. // Camera
  28733. if (!this.activeCamera) {
  28734. var worldExtends = this.getWorldExtends();
  28735. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28736. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28737. var camera;
  28738. var radius = worldSize.length() * 1.5;
  28739. // empty scene scenario!
  28740. if (!isFinite(radius)) {
  28741. radius = 1;
  28742. worldCenter.copyFromFloats(0, 0, 0);
  28743. }
  28744. if (createArcRotateCamera) {
  28745. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28746. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28747. arcRotateCamera.wheelPrecision = 100 / radius;
  28748. camera = arcRotateCamera;
  28749. }
  28750. else {
  28751. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28752. freeCamera.setTarget(worldCenter);
  28753. camera = freeCamera;
  28754. }
  28755. camera.minZ = radius * 0.01;
  28756. camera.maxZ = radius * 1000;
  28757. camera.speed = radius * 0.2;
  28758. this.activeCamera = camera;
  28759. var canvas = this.getEngine().getRenderingCanvas();
  28760. if (attachCameraControls && canvas) {
  28761. camera.attachControl(canvas);
  28762. }
  28763. }
  28764. };
  28765. /**
  28766. * Creates a default camera and a default light.
  28767. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28768. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28769. * @param replace has the default false, when true replaces the active camera/light in the scene
  28770. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28771. */
  28772. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28773. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28774. if (replace === void 0) { replace = false; }
  28775. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28776. this.createDefaultLight(replace);
  28777. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28778. };
  28779. /**
  28780. * Creates a new sky box
  28781. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28782. * @param environmentTexture defines the texture to use as environment texture
  28783. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28784. * @param scale defines the overall scale of the skybox
  28785. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28786. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28787. * @returns a new mesh holding the sky box
  28788. */
  28789. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28790. if (pbr === void 0) { pbr = false; }
  28791. if (scale === void 0) { scale = 1000; }
  28792. if (blur === void 0) { blur = 0; }
  28793. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28794. if (!environmentTexture) {
  28795. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28796. return null;
  28797. }
  28798. if (setGlobalEnvTexture) {
  28799. if (environmentTexture) {
  28800. this.environmentTexture = environmentTexture;
  28801. }
  28802. }
  28803. // Skybox
  28804. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28805. if (pbr) {
  28806. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28807. hdrSkyboxMaterial.backFaceCulling = false;
  28808. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28809. if (hdrSkyboxMaterial.reflectionTexture) {
  28810. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28811. }
  28812. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28813. hdrSkyboxMaterial.disableLighting = true;
  28814. hdrSkyboxMaterial.twoSidedLighting = true;
  28815. hdrSkybox.infiniteDistance = true;
  28816. hdrSkybox.material = hdrSkyboxMaterial;
  28817. }
  28818. else {
  28819. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28820. skyboxMaterial.backFaceCulling = false;
  28821. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28822. if (skyboxMaterial.reflectionTexture) {
  28823. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28824. }
  28825. skyboxMaterial.disableLighting = true;
  28826. hdrSkybox.infiniteDistance = true;
  28827. hdrSkybox.material = skyboxMaterial;
  28828. }
  28829. return hdrSkybox;
  28830. };
  28831. /**
  28832. * Creates a new environment
  28833. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28834. * @param options defines the options you can use to configure the environment
  28835. * @returns the new EnvironmentHelper
  28836. */
  28837. Scene.prototype.createDefaultEnvironment = function (options) {
  28838. if (BABYLON.EnvironmentHelper) {
  28839. return new BABYLON.EnvironmentHelper(options, this);
  28840. }
  28841. return null;
  28842. };
  28843. /**
  28844. * Creates a new VREXperienceHelper
  28845. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28846. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28847. * @returns a new VREXperienceHelper
  28848. */
  28849. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28850. if (webVROptions === void 0) { webVROptions = {}; }
  28851. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28852. };
  28853. // Tags
  28854. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28855. if (tagsQuery === undefined) {
  28856. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28857. return list;
  28858. }
  28859. var listByTags = [];
  28860. forEach = forEach || (function (item) { return; });
  28861. for (var i in list) {
  28862. var item = list[i];
  28863. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28864. listByTags.push(item);
  28865. forEach(item);
  28866. }
  28867. }
  28868. return listByTags;
  28869. };
  28870. /**
  28871. * Get a list of meshes by tags
  28872. * @param tagsQuery defines the tags query to use
  28873. * @param forEach defines a predicate used to filter results
  28874. * @returns an array of Mesh
  28875. */
  28876. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28877. return this._getByTags(this.meshes, tagsQuery, forEach);
  28878. };
  28879. /**
  28880. * Get a list of cameras by tags
  28881. * @param tagsQuery defines the tags query to use
  28882. * @param forEach defines a predicate used to filter results
  28883. * @returns an array of Camera
  28884. */
  28885. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28886. return this._getByTags(this.cameras, tagsQuery, forEach);
  28887. };
  28888. /**
  28889. * Get a list of lights by tags
  28890. * @param tagsQuery defines the tags query to use
  28891. * @param forEach defines a predicate used to filter results
  28892. * @returns an array of Light
  28893. */
  28894. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28895. return this._getByTags(this.lights, tagsQuery, forEach);
  28896. };
  28897. /**
  28898. * Get a list of materials by tags
  28899. * @param tagsQuery defines the tags query to use
  28900. * @param forEach defines a predicate used to filter results
  28901. * @returns an array of Material
  28902. */
  28903. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28904. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28905. };
  28906. /**
  28907. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28908. * This allowed control for front to back rendering or reversly depending of the special needs.
  28909. *
  28910. * @param renderingGroupId The rendering group id corresponding to its index
  28911. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28912. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28913. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28914. */
  28915. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28916. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28917. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28918. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28919. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28920. };
  28921. /**
  28922. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28923. *
  28924. * @param renderingGroupId The rendering group id corresponding to its index
  28925. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28926. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28927. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28928. */
  28929. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28930. if (depth === void 0) { depth = true; }
  28931. if (stencil === void 0) { stencil = true; }
  28932. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28933. };
  28934. /**
  28935. * Gets the current auto clear configuration for one rendering group of the rendering
  28936. * manager.
  28937. * @param index the rendering group index to get the information for
  28938. * @returns The auto clear setup for the requested rendering group
  28939. */
  28940. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28941. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28942. };
  28943. /**
  28944. * Will flag all materials as dirty to trigger new shader compilation
  28945. * @param flag defines the flag used to specify which material part must be marked as dirty
  28946. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28947. */
  28948. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28949. if (this.blockMaterialDirtyMechanism) {
  28950. return;
  28951. }
  28952. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28953. var material = _a[_i];
  28954. if (predicate && !predicate(material)) {
  28955. continue;
  28956. }
  28957. material.markAsDirty(flag);
  28958. }
  28959. };
  28960. /** @hidden */
  28961. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28962. var _this = this;
  28963. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28964. this._activeRequests.push(request);
  28965. request.onCompleteObservable.add(function (request) {
  28966. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28967. });
  28968. return request;
  28969. };
  28970. /** @hidden */
  28971. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28972. var _this = this;
  28973. return new Promise(function (resolve, reject) {
  28974. _this._loadFile(url, function (data) {
  28975. resolve(data);
  28976. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28977. reject(exception);
  28978. });
  28979. });
  28980. };
  28981. // Statics
  28982. Scene._uniqueIdCounter = 0;
  28983. /** The fog is deactivated */
  28984. Scene.FOGMODE_NONE = 0;
  28985. /** The fog density is following an exponential function */
  28986. Scene.FOGMODE_EXP = 1;
  28987. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28988. Scene.FOGMODE_EXP2 = 2;
  28989. /** The fog density is following a linear function. */
  28990. Scene.FOGMODE_LINEAR = 3;
  28991. /**
  28992. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28993. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28994. */
  28995. Scene.MinDeltaTime = 1.0;
  28996. /**
  28997. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28998. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28999. */
  29000. Scene.MaxDeltaTime = 1000.0;
  29001. /** The distance in pixel that you have to move to prevent some events */
  29002. Scene.DragMovementThreshold = 10; // in pixels
  29003. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29004. Scene.LongPressDelay = 500; // in milliseconds
  29005. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29006. Scene.DoubleClickDelay = 300; // in milliseconds
  29007. /** If you need to check double click without raising a single click at first click, enable this flag */
  29008. Scene.ExclusiveDoubleClickMode = false;
  29009. return Scene;
  29010. }(BABYLON.AbstractScene));
  29011. BABYLON.Scene = Scene;
  29012. })(BABYLON || (BABYLON = {}));
  29013. //# sourceMappingURL=babylon.scene.js.map
  29014. var BABYLON;
  29015. (function (BABYLON) {
  29016. /**
  29017. * Set of assets to keep when moving a scene into an asset container.
  29018. */
  29019. var KeepAssets = /** @class */ (function (_super) {
  29020. __extends(KeepAssets, _super);
  29021. function KeepAssets() {
  29022. return _super !== null && _super.apply(this, arguments) || this;
  29023. }
  29024. return KeepAssets;
  29025. }(BABYLON.AbstractScene));
  29026. BABYLON.KeepAssets = KeepAssets;
  29027. /**
  29028. * Container with a set of assets that can be added or removed from a scene.
  29029. */
  29030. var AssetContainer = /** @class */ (function (_super) {
  29031. __extends(AssetContainer, _super);
  29032. /**
  29033. * Instantiates an AssetContainer.
  29034. * @param scene The scene the AssetContainer belongs to.
  29035. */
  29036. function AssetContainer(scene) {
  29037. var _this = _super.call(this) || this;
  29038. _this.scene = scene;
  29039. return _this;
  29040. }
  29041. /**
  29042. * Adds all the assets from the container to the scene.
  29043. */
  29044. AssetContainer.prototype.addAllToScene = function () {
  29045. var _this = this;
  29046. this.cameras.forEach(function (o) {
  29047. _this.scene.addCamera(o);
  29048. });
  29049. this.lights.forEach(function (o) {
  29050. _this.scene.addLight(o);
  29051. });
  29052. this.meshes.forEach(function (o) {
  29053. _this.scene.addMesh(o);
  29054. });
  29055. this.skeletons.forEach(function (o) {
  29056. _this.scene.addSkeleton(o);
  29057. });
  29058. this.animations.forEach(function (o) {
  29059. _this.scene.addAnimation(o);
  29060. });
  29061. this.animationGroups.forEach(function (o) {
  29062. _this.scene.addAnimationGroup(o);
  29063. });
  29064. this.multiMaterials.forEach(function (o) {
  29065. _this.scene.addMultiMaterial(o);
  29066. });
  29067. this.materials.forEach(function (o) {
  29068. _this.scene.addMaterial(o);
  29069. });
  29070. this.morphTargetManagers.forEach(function (o) {
  29071. _this.scene.addMorphTargetManager(o);
  29072. });
  29073. this.geometries.forEach(function (o) {
  29074. _this.scene.addGeometry(o);
  29075. });
  29076. this.transformNodes.forEach(function (o) {
  29077. _this.scene.addTransformNode(o);
  29078. });
  29079. this.actionManagers.forEach(function (o) {
  29080. _this.scene.addActionManager(o);
  29081. });
  29082. this.sounds.forEach(function (o) {
  29083. o.play();
  29084. o.autoplay = true;
  29085. _this.scene.mainSoundTrack.AddSound(o);
  29086. });
  29087. this.textures.forEach(function (o) {
  29088. _this.scene.addTexture(o);
  29089. });
  29090. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29091. var component = _a[_i];
  29092. component.addFromContainer(this.scene);
  29093. }
  29094. };
  29095. /**
  29096. * Removes all the assets in the container from the scene
  29097. */
  29098. AssetContainer.prototype.removeAllFromScene = function () {
  29099. var _this = this;
  29100. this.cameras.forEach(function (o) {
  29101. _this.scene.removeCamera(o);
  29102. });
  29103. this.lights.forEach(function (o) {
  29104. _this.scene.removeLight(o);
  29105. });
  29106. this.meshes.forEach(function (o) {
  29107. _this.scene.removeMesh(o);
  29108. });
  29109. this.skeletons.forEach(function (o) {
  29110. _this.scene.removeSkeleton(o);
  29111. });
  29112. this.animations.forEach(function (o) {
  29113. _this.scene.removeAnimation(o);
  29114. });
  29115. this.animationGroups.forEach(function (o) {
  29116. _this.scene.removeAnimationGroup(o);
  29117. });
  29118. this.multiMaterials.forEach(function (o) {
  29119. _this.scene.removeMultiMaterial(o);
  29120. });
  29121. this.materials.forEach(function (o) {
  29122. _this.scene.removeMaterial(o);
  29123. });
  29124. this.morphTargetManagers.forEach(function (o) {
  29125. _this.scene.removeMorphTargetManager(o);
  29126. });
  29127. this.geometries.forEach(function (o) {
  29128. _this.scene.removeGeometry(o);
  29129. });
  29130. this.transformNodes.forEach(function (o) {
  29131. _this.scene.removeTransformNode(o);
  29132. });
  29133. this.actionManagers.forEach(function (o) {
  29134. _this.scene.removeActionManager(o);
  29135. });
  29136. this.sounds.forEach(function (o) {
  29137. o.stop();
  29138. o.autoplay = false;
  29139. _this.scene.mainSoundTrack.RemoveSound(o);
  29140. });
  29141. this.textures.forEach(function (o) {
  29142. _this.scene.removeTexture(o);
  29143. });
  29144. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29145. var component = _a[_i];
  29146. component.removeFromContainer(this.scene);
  29147. }
  29148. };
  29149. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29150. if (!sourceAssets) {
  29151. return;
  29152. }
  29153. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29154. var asset = sourceAssets_1[_i];
  29155. var move = true;
  29156. if (keepAssets) {
  29157. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29158. var keepAsset = keepAssets_1[_a];
  29159. if (asset === keepAsset) {
  29160. move = false;
  29161. break;
  29162. }
  29163. }
  29164. }
  29165. if (move) {
  29166. targetAssets.push(asset);
  29167. }
  29168. }
  29169. };
  29170. /**
  29171. * Removes all the assets contained in the scene and adds them to the container.
  29172. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29173. */
  29174. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29175. if (keepAssets === undefined) {
  29176. keepAssets = new KeepAssets();
  29177. }
  29178. for (var key in this) {
  29179. if (this.hasOwnProperty(key)) {
  29180. this[key] = this[key] || [];
  29181. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29182. }
  29183. }
  29184. this.removeAllFromScene();
  29185. };
  29186. /**
  29187. * 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.
  29188. * @returns the root mesh
  29189. */
  29190. AssetContainer.prototype.createRootMesh = function () {
  29191. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29192. this.meshes.forEach(function (m) {
  29193. if (!m.parent) {
  29194. rootMesh.addChild(m);
  29195. }
  29196. });
  29197. this.meshes.unshift(rootMesh);
  29198. return rootMesh;
  29199. };
  29200. return AssetContainer;
  29201. }(BABYLON.AbstractScene));
  29202. BABYLON.AssetContainer = AssetContainer;
  29203. })(BABYLON || (BABYLON = {}));
  29204. //# sourceMappingURL=babylon.assetContainer.js.map
  29205. var BABYLON;
  29206. (function (BABYLON) {
  29207. var Buffer = /** @class */ (function () {
  29208. /**
  29209. * Constructor
  29210. * @param engine the engine
  29211. * @param data the data to use for this buffer
  29212. * @param updatable whether the data is updatable
  29213. * @param stride the stride (optional)
  29214. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29215. * @param instanced whether the buffer is instanced (optional)
  29216. * @param useBytes set to true if the stride in in bytes (optional)
  29217. */
  29218. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29219. if (stride === void 0) { stride = 0; }
  29220. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29221. if (instanced === void 0) { instanced = false; }
  29222. if (useBytes === void 0) { useBytes = false; }
  29223. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29224. this._engine = engine.getScene().getEngine();
  29225. }
  29226. else {
  29227. this._engine = engine;
  29228. }
  29229. this._updatable = updatable;
  29230. this._instanced = instanced;
  29231. this._data = data;
  29232. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29233. if (!postponeInternalCreation) { // by default
  29234. this.create();
  29235. }
  29236. }
  29237. /**
  29238. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29239. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29240. * @param offset defines offset in the buffer (0 by default)
  29241. * @param size defines the size in floats of attributes (position is 3 for instance)
  29242. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29243. * @param instanced defines if the vertex buffer contains indexed data
  29244. * @param useBytes defines if the offset and stride are in bytes
  29245. * @returns the new vertex buffer
  29246. */
  29247. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29248. if (useBytes === void 0) { useBytes = false; }
  29249. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29250. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29251. // a lot of these parameters are ignored as they are overriden by the buffer
  29252. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29253. };
  29254. // Properties
  29255. Buffer.prototype.isUpdatable = function () {
  29256. return this._updatable;
  29257. };
  29258. Buffer.prototype.getData = function () {
  29259. return this._data;
  29260. };
  29261. Buffer.prototype.getBuffer = function () {
  29262. return this._buffer;
  29263. };
  29264. /**
  29265. * Gets the stride in float32 units (i.e. byte stride / 4).
  29266. * May not be an integer if the byte stride is not divisible by 4.
  29267. * DEPRECATED. Use byteStride instead.
  29268. * @returns the stride in float32 units
  29269. */
  29270. Buffer.prototype.getStrideSize = function () {
  29271. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29272. };
  29273. // Methods
  29274. Buffer.prototype.create = function (data) {
  29275. if (data === void 0) { data = null; }
  29276. if (!data && this._buffer) {
  29277. return; // nothing to do
  29278. }
  29279. data = data || this._data;
  29280. if (!data) {
  29281. return;
  29282. }
  29283. if (!this._buffer) { // create buffer
  29284. if (this._updatable) {
  29285. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29286. this._data = data;
  29287. }
  29288. else {
  29289. this._buffer = this._engine.createVertexBuffer(data);
  29290. }
  29291. }
  29292. else if (this._updatable) { // update buffer
  29293. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29294. this._data = data;
  29295. }
  29296. };
  29297. /** @hidden */
  29298. Buffer.prototype._rebuild = function () {
  29299. this._buffer = null;
  29300. this.create(this._data);
  29301. };
  29302. Buffer.prototype.update = function (data) {
  29303. this.create(data);
  29304. };
  29305. /**
  29306. * Updates the data directly.
  29307. * @param data the new data
  29308. * @param offset the new offset
  29309. * @param vertexCount the vertex count (optional)
  29310. * @param useBytes set to true if the offset is in bytes
  29311. */
  29312. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29313. if (useBytes === void 0) { useBytes = false; }
  29314. if (!this._buffer) {
  29315. return;
  29316. }
  29317. if (this._updatable) { // update buffer
  29318. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29319. this._data = null;
  29320. }
  29321. };
  29322. Buffer.prototype.dispose = function () {
  29323. if (!this._buffer) {
  29324. return;
  29325. }
  29326. if (this._engine._releaseBuffer(this._buffer)) {
  29327. this._buffer = null;
  29328. }
  29329. };
  29330. return Buffer;
  29331. }());
  29332. BABYLON.Buffer = Buffer;
  29333. })(BABYLON || (BABYLON = {}));
  29334. //# sourceMappingURL=babylon.buffer.js.map
  29335. var BABYLON;
  29336. (function (BABYLON) {
  29337. var VertexBuffer = /** @class */ (function () {
  29338. /**
  29339. * Constructor
  29340. * @param engine the engine
  29341. * @param data the data to use for this vertex buffer
  29342. * @param kind the vertex buffer kind
  29343. * @param updatable whether the data is updatable
  29344. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29345. * @param stride the stride (optional)
  29346. * @param instanced whether the buffer is instanced (optional)
  29347. * @param offset the offset of the data (optional)
  29348. * @param size the number of components (optional)
  29349. * @param type the type of the component (optional)
  29350. * @param normalized whether the data contains normalized data (optional)
  29351. * @param useBytes set to true if stride and offset are in bytes (optional)
  29352. */
  29353. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29354. if (normalized === void 0) { normalized = false; }
  29355. if (useBytes === void 0) { useBytes = false; }
  29356. if (data instanceof BABYLON.Buffer) {
  29357. this._buffer = data;
  29358. this._ownsBuffer = false;
  29359. }
  29360. else {
  29361. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29362. this._ownsBuffer = true;
  29363. }
  29364. this._kind = kind;
  29365. if (type == undefined) {
  29366. var data_1 = this.getData();
  29367. this.type = VertexBuffer.FLOAT;
  29368. if (data_1 instanceof Int8Array)
  29369. this.type = VertexBuffer.BYTE;
  29370. else if (data_1 instanceof Uint8Array)
  29371. this.type = VertexBuffer.UNSIGNED_BYTE;
  29372. else if (data_1 instanceof Int16Array)
  29373. this.type = VertexBuffer.SHORT;
  29374. else if (data_1 instanceof Uint16Array)
  29375. this.type = VertexBuffer.UNSIGNED_SHORT;
  29376. else if (data_1 instanceof Int32Array)
  29377. this.type = VertexBuffer.INT;
  29378. else if (data_1 instanceof Uint32Array)
  29379. this.type = VertexBuffer.UNSIGNED_INT;
  29380. }
  29381. else {
  29382. this.type = type;
  29383. }
  29384. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29385. if (useBytes) {
  29386. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29387. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29388. this.byteOffset = offset || 0;
  29389. }
  29390. else {
  29391. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29392. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29393. this.byteOffset = (offset || 0) * typeByteLength;
  29394. }
  29395. this.normalized = normalized;
  29396. this._instanced = instanced !== undefined ? instanced : false;
  29397. this._instanceDivisor = instanced ? 1 : 0;
  29398. }
  29399. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29400. /**
  29401. * Gets or sets the instance divisor when in instanced mode
  29402. */
  29403. get: function () {
  29404. return this._instanceDivisor;
  29405. },
  29406. set: function (value) {
  29407. this._instanceDivisor = value;
  29408. if (value == 0) {
  29409. this._instanced = false;
  29410. }
  29411. else {
  29412. this._instanced = true;
  29413. }
  29414. },
  29415. enumerable: true,
  29416. configurable: true
  29417. });
  29418. /** @hidden */
  29419. VertexBuffer.prototype._rebuild = function () {
  29420. if (!this._buffer) {
  29421. return;
  29422. }
  29423. this._buffer._rebuild();
  29424. };
  29425. /**
  29426. * Returns the kind of the VertexBuffer (string).
  29427. */
  29428. VertexBuffer.prototype.getKind = function () {
  29429. return this._kind;
  29430. };
  29431. // Properties
  29432. /**
  29433. * Boolean : is the VertexBuffer updatable ?
  29434. */
  29435. VertexBuffer.prototype.isUpdatable = function () {
  29436. return this._buffer.isUpdatable();
  29437. };
  29438. /**
  29439. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29440. */
  29441. VertexBuffer.prototype.getData = function () {
  29442. return this._buffer.getData();
  29443. };
  29444. /**
  29445. * Returns the WebGLBuffer associated to the VertexBuffer.
  29446. */
  29447. VertexBuffer.prototype.getBuffer = function () {
  29448. return this._buffer.getBuffer();
  29449. };
  29450. /**
  29451. * Returns the stride as a multiple of the type byte length.
  29452. * DEPRECATED. Use byteStride instead.
  29453. */
  29454. VertexBuffer.prototype.getStrideSize = function () {
  29455. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29456. };
  29457. /**
  29458. * Returns the offset as a multiple of the type byte length.
  29459. * DEPRECATED. Use byteOffset instead.
  29460. */
  29461. VertexBuffer.prototype.getOffset = function () {
  29462. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29463. };
  29464. /**
  29465. * Returns the number of components per vertex attribute (integer).
  29466. */
  29467. VertexBuffer.prototype.getSize = function () {
  29468. return this._size;
  29469. };
  29470. /**
  29471. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29472. */
  29473. VertexBuffer.prototype.getIsInstanced = function () {
  29474. return this._instanced;
  29475. };
  29476. /**
  29477. * Returns the instancing divisor, zero for non-instanced (integer).
  29478. */
  29479. VertexBuffer.prototype.getInstanceDivisor = function () {
  29480. return this._instanceDivisor;
  29481. };
  29482. // Methods
  29483. /**
  29484. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29485. * Returns the created WebGLBuffer.
  29486. */
  29487. VertexBuffer.prototype.create = function (data) {
  29488. return this._buffer.create(data);
  29489. };
  29490. /**
  29491. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29492. * This function will create a new buffer if the current one is not updatable
  29493. * Returns the updated WebGLBuffer.
  29494. */
  29495. VertexBuffer.prototype.update = function (data) {
  29496. return this._buffer.update(data);
  29497. };
  29498. /**
  29499. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29500. * Returns the directly updated WebGLBuffer.
  29501. * @param data the new data
  29502. * @param offset the new offset
  29503. * @param useBytes set to true if the offset is in bytes
  29504. */
  29505. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29506. if (useBytes === void 0) { useBytes = false; }
  29507. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29508. };
  29509. /**
  29510. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29511. */
  29512. VertexBuffer.prototype.dispose = function () {
  29513. if (this._ownsBuffer) {
  29514. this._buffer.dispose();
  29515. }
  29516. };
  29517. /**
  29518. * Enumerates each value of this vertex buffer as numbers.
  29519. * @param count the number of values to enumerate
  29520. * @param callback the callback function called for each value
  29521. */
  29522. VertexBuffer.prototype.forEach = function (count, callback) {
  29523. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29524. };
  29525. Object.defineProperty(VertexBuffer, "PositionKind", {
  29526. get: function () {
  29527. return VertexBuffer._PositionKind;
  29528. },
  29529. enumerable: true,
  29530. configurable: true
  29531. });
  29532. Object.defineProperty(VertexBuffer, "NormalKind", {
  29533. get: function () {
  29534. return VertexBuffer._NormalKind;
  29535. },
  29536. enumerable: true,
  29537. configurable: true
  29538. });
  29539. Object.defineProperty(VertexBuffer, "TangentKind", {
  29540. get: function () {
  29541. return VertexBuffer._TangentKind;
  29542. },
  29543. enumerable: true,
  29544. configurable: true
  29545. });
  29546. Object.defineProperty(VertexBuffer, "UVKind", {
  29547. get: function () {
  29548. return VertexBuffer._UVKind;
  29549. },
  29550. enumerable: true,
  29551. configurable: true
  29552. });
  29553. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29554. get: function () {
  29555. return VertexBuffer._UV2Kind;
  29556. },
  29557. enumerable: true,
  29558. configurable: true
  29559. });
  29560. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29561. get: function () {
  29562. return VertexBuffer._UV3Kind;
  29563. },
  29564. enumerable: true,
  29565. configurable: true
  29566. });
  29567. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29568. get: function () {
  29569. return VertexBuffer._UV4Kind;
  29570. },
  29571. enumerable: true,
  29572. configurable: true
  29573. });
  29574. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29575. get: function () {
  29576. return VertexBuffer._UV5Kind;
  29577. },
  29578. enumerable: true,
  29579. configurable: true
  29580. });
  29581. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29582. get: function () {
  29583. return VertexBuffer._UV6Kind;
  29584. },
  29585. enumerable: true,
  29586. configurable: true
  29587. });
  29588. Object.defineProperty(VertexBuffer, "ColorKind", {
  29589. get: function () {
  29590. return VertexBuffer._ColorKind;
  29591. },
  29592. enumerable: true,
  29593. configurable: true
  29594. });
  29595. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29596. get: function () {
  29597. return VertexBuffer._MatricesIndicesKind;
  29598. },
  29599. enumerable: true,
  29600. configurable: true
  29601. });
  29602. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29603. get: function () {
  29604. return VertexBuffer._MatricesWeightsKind;
  29605. },
  29606. enumerable: true,
  29607. configurable: true
  29608. });
  29609. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29610. get: function () {
  29611. return VertexBuffer._MatricesIndicesExtraKind;
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29617. get: function () {
  29618. return VertexBuffer._MatricesWeightsExtraKind;
  29619. },
  29620. enumerable: true,
  29621. configurable: true
  29622. });
  29623. /**
  29624. * Deduces the stride given a kind.
  29625. * @param kind The kind string to deduce
  29626. * @returns The deduced stride
  29627. */
  29628. VertexBuffer.DeduceStride = function (kind) {
  29629. switch (kind) {
  29630. case VertexBuffer.UVKind:
  29631. case VertexBuffer.UV2Kind:
  29632. case VertexBuffer.UV3Kind:
  29633. case VertexBuffer.UV4Kind:
  29634. case VertexBuffer.UV5Kind:
  29635. case VertexBuffer.UV6Kind:
  29636. return 2;
  29637. case VertexBuffer.NormalKind:
  29638. case VertexBuffer.PositionKind:
  29639. return 3;
  29640. case VertexBuffer.ColorKind:
  29641. case VertexBuffer.MatricesIndicesKind:
  29642. case VertexBuffer.MatricesIndicesExtraKind:
  29643. case VertexBuffer.MatricesWeightsKind:
  29644. case VertexBuffer.MatricesWeightsExtraKind:
  29645. case VertexBuffer.TangentKind:
  29646. return 4;
  29647. default:
  29648. throw new Error("Invalid kind '" + kind + "'");
  29649. }
  29650. };
  29651. /**
  29652. * Gets the byte length of the given type.
  29653. * @param type the type
  29654. * @returns the number of bytes
  29655. */
  29656. VertexBuffer.GetTypeByteLength = function (type) {
  29657. switch (type) {
  29658. case VertexBuffer.BYTE:
  29659. case VertexBuffer.UNSIGNED_BYTE:
  29660. return 1;
  29661. case VertexBuffer.SHORT:
  29662. case VertexBuffer.UNSIGNED_SHORT:
  29663. return 2;
  29664. case VertexBuffer.INT:
  29665. case VertexBuffer.FLOAT:
  29666. return 4;
  29667. default:
  29668. throw new Error("Invalid type '" + type + "'");
  29669. }
  29670. };
  29671. /**
  29672. * Enumerates each value of the given parameters as numbers.
  29673. * @param data the data to enumerate
  29674. * @param byteOffset the byte offset of the data
  29675. * @param byteStride the byte stride of the data
  29676. * @param componentCount the number of components per element
  29677. * @param componentType the type of the component
  29678. * @param count the total number of components
  29679. * @param normalized whether the data is normalized
  29680. * @param callback the callback function called for each value
  29681. */
  29682. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29683. if (data instanceof Array) {
  29684. var offset = byteOffset / 4;
  29685. var stride = byteStride / 4;
  29686. for (var index = 0; index < count; index += componentCount) {
  29687. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29688. callback(data[offset + componentIndex], index + componentIndex);
  29689. }
  29690. offset += stride;
  29691. }
  29692. }
  29693. else {
  29694. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29695. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29696. for (var index = 0; index < count; index += componentCount) {
  29697. var componentByteOffset = byteOffset;
  29698. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29699. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29700. callback(value, index + componentIndex);
  29701. componentByteOffset += componentByteLength;
  29702. }
  29703. byteOffset += byteStride;
  29704. }
  29705. }
  29706. };
  29707. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29708. switch (type) {
  29709. case VertexBuffer.BYTE: {
  29710. var value = dataView.getInt8(byteOffset);
  29711. if (normalized) {
  29712. value = Math.max(value / 127, -1);
  29713. }
  29714. return value;
  29715. }
  29716. case VertexBuffer.UNSIGNED_BYTE: {
  29717. var value = dataView.getUint8(byteOffset);
  29718. if (normalized) {
  29719. value = value / 255;
  29720. }
  29721. return value;
  29722. }
  29723. case VertexBuffer.SHORT: {
  29724. var value = dataView.getInt16(byteOffset, true);
  29725. if (normalized) {
  29726. value = Math.max(value / 16383, -1);
  29727. }
  29728. return value;
  29729. }
  29730. case VertexBuffer.UNSIGNED_SHORT: {
  29731. var value = dataView.getUint16(byteOffset, true);
  29732. if (normalized) {
  29733. value = value / 65535;
  29734. }
  29735. return value;
  29736. }
  29737. case VertexBuffer.FLOAT: {
  29738. return dataView.getFloat32(byteOffset, true);
  29739. }
  29740. default: {
  29741. throw new Error("Invalid component type " + type);
  29742. }
  29743. }
  29744. };
  29745. /**
  29746. * The byte type.
  29747. */
  29748. VertexBuffer.BYTE = 5120;
  29749. /**
  29750. * The unsigned byte type.
  29751. */
  29752. VertexBuffer.UNSIGNED_BYTE = 5121;
  29753. /**
  29754. * The short type.
  29755. */
  29756. VertexBuffer.SHORT = 5122;
  29757. /**
  29758. * The unsigned short type.
  29759. */
  29760. VertexBuffer.UNSIGNED_SHORT = 5123;
  29761. /**
  29762. * The integer type.
  29763. */
  29764. VertexBuffer.INT = 5124;
  29765. /**
  29766. * The unsigned integer type.
  29767. */
  29768. VertexBuffer.UNSIGNED_INT = 5125;
  29769. /**
  29770. * The float type.
  29771. */
  29772. VertexBuffer.FLOAT = 5126;
  29773. // Enums
  29774. VertexBuffer._PositionKind = "position";
  29775. VertexBuffer._NormalKind = "normal";
  29776. VertexBuffer._TangentKind = "tangent";
  29777. VertexBuffer._UVKind = "uv";
  29778. VertexBuffer._UV2Kind = "uv2";
  29779. VertexBuffer._UV3Kind = "uv3";
  29780. VertexBuffer._UV4Kind = "uv4";
  29781. VertexBuffer._UV5Kind = "uv5";
  29782. VertexBuffer._UV6Kind = "uv6";
  29783. VertexBuffer._ColorKind = "color";
  29784. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29785. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29786. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29787. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29788. return VertexBuffer;
  29789. }());
  29790. BABYLON.VertexBuffer = VertexBuffer;
  29791. })(BABYLON || (BABYLON = {}));
  29792. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29793. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29794. var BABYLON;
  29795. (function (BABYLON) {
  29796. /**
  29797. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29798. */
  29799. var DummyInternalTextureTracker = /** @class */ (function () {
  29800. function DummyInternalTextureTracker() {
  29801. /**
  29802. * Gets or set the previous tracker in the list
  29803. */
  29804. this.previous = null;
  29805. /**
  29806. * Gets or set the next tracker in the list
  29807. */
  29808. this.next = null;
  29809. }
  29810. return DummyInternalTextureTracker;
  29811. }());
  29812. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29813. })(BABYLON || (BABYLON = {}));
  29814. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29815. var BABYLON;
  29816. (function (BABYLON) {
  29817. /**
  29818. * Class used to store data associated with WebGL texture data for the engine
  29819. * This class should not be used directly
  29820. */
  29821. var InternalTexture = /** @class */ (function () {
  29822. /**
  29823. * Creates a new InternalTexture
  29824. * @param engine defines the engine to use
  29825. * @param dataSource defines the type of data that will be used
  29826. */
  29827. function InternalTexture(engine, dataSource) {
  29828. /**
  29829. * Observable called when the texture is loaded
  29830. */
  29831. this.onLoadedObservable = new BABYLON.Observable();
  29832. /**
  29833. * Gets or set the previous tracker in the list
  29834. */
  29835. this.previous = null;
  29836. /**
  29837. * Gets or set the next tracker in the list
  29838. */
  29839. this.next = null;
  29840. // Private
  29841. /** @hidden */
  29842. this._initialSlot = -1;
  29843. /** @hidden */
  29844. this._designatedSlot = -1;
  29845. /** @hidden */
  29846. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29847. /** @hidden */
  29848. this._comparisonFunction = 0;
  29849. /** @hidden */
  29850. this._sphericalPolynomial = null;
  29851. /** @hidden */
  29852. this._lodGenerationScale = 0;
  29853. /** @hidden */
  29854. this._lodGenerationOffset = 0;
  29855. /** @hidden */
  29856. this._isRGBD = false;
  29857. /** @hidden */
  29858. this._references = 1;
  29859. this._engine = engine;
  29860. this._dataSource = dataSource;
  29861. this._webGLTexture = engine._createTexture();
  29862. }
  29863. /**
  29864. * Gets the Engine the texture belongs to.
  29865. * @returns The babylon engine
  29866. */
  29867. InternalTexture.prototype.getEngine = function () {
  29868. return this._engine;
  29869. };
  29870. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29871. /**
  29872. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29873. */
  29874. get: function () {
  29875. return this._dataSource;
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. /**
  29881. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29882. */
  29883. InternalTexture.prototype.incrementReferences = function () {
  29884. this._references++;
  29885. };
  29886. /**
  29887. * Change the size of the texture (not the size of the content)
  29888. * @param width defines the new width
  29889. * @param height defines the new height
  29890. * @param depth defines the new depth (1 by default)
  29891. */
  29892. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29893. if (depth === void 0) { depth = 1; }
  29894. this.width = width;
  29895. this.height = height;
  29896. this.depth = depth;
  29897. this.baseWidth = width;
  29898. this.baseHeight = height;
  29899. this.baseDepth = depth;
  29900. this._size = width * height * depth;
  29901. };
  29902. /** @hidden */
  29903. InternalTexture.prototype._rebuild = function () {
  29904. var _this = this;
  29905. var proxy;
  29906. this.isReady = false;
  29907. this._cachedCoordinatesMode = null;
  29908. this._cachedWrapU = null;
  29909. this._cachedWrapV = null;
  29910. this._cachedAnisotropicFilteringLevel = null;
  29911. switch (this._dataSource) {
  29912. case InternalTexture.DATASOURCE_TEMP:
  29913. return;
  29914. case InternalTexture.DATASOURCE_URL:
  29915. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29916. _this.isReady = true;
  29917. }, null, this._buffer, undefined, this.format);
  29918. proxy._swapAndDie(this);
  29919. return;
  29920. case InternalTexture.DATASOURCE_RAW:
  29921. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29922. proxy._swapAndDie(this);
  29923. this.isReady = true;
  29924. return;
  29925. case InternalTexture.DATASOURCE_RAW3D:
  29926. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29927. proxy._swapAndDie(this);
  29928. this.isReady = true;
  29929. return;
  29930. case InternalTexture.DATASOURCE_DYNAMIC:
  29931. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29932. proxy._swapAndDie(this);
  29933. // The engine will make sure to update content so no need to flag it as isReady = true
  29934. return;
  29935. case InternalTexture.DATASOURCE_RENDERTARGET:
  29936. var options = new BABYLON.RenderTargetCreationOptions();
  29937. options.generateDepthBuffer = this._generateDepthBuffer;
  29938. options.generateMipMaps = this.generateMipMaps;
  29939. options.generateStencilBuffer = this._generateStencilBuffer;
  29940. options.samplingMode = this.samplingMode;
  29941. options.type = this.type;
  29942. if (this.isCube) {
  29943. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29944. }
  29945. else {
  29946. var size = {
  29947. width: this.width,
  29948. height: this.height
  29949. };
  29950. proxy = this._engine.createRenderTargetTexture(size, options);
  29951. }
  29952. proxy._swapAndDie(this);
  29953. this.isReady = true;
  29954. return;
  29955. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29956. var depthTextureOptions = {
  29957. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29958. comparisonFunction: this._comparisonFunction,
  29959. generateStencil: this._generateStencilBuffer,
  29960. isCube: this.isCube
  29961. };
  29962. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29963. proxy._swapAndDie(this);
  29964. this.isReady = true;
  29965. return;
  29966. case InternalTexture.DATASOURCE_CUBE:
  29967. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29968. _this.isReady = true;
  29969. }, null, this.format, this._extension);
  29970. proxy._swapAndDie(this);
  29971. return;
  29972. case InternalTexture.DATASOURCE_CUBERAW:
  29973. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29974. proxy._swapAndDie(this);
  29975. this.isReady = true;
  29976. return;
  29977. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29978. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29979. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29980. _this.isReady = true;
  29981. });
  29982. proxy._swapAndDie(this);
  29983. return;
  29984. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29985. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29986. if (proxy) {
  29987. proxy._swapAndDie(_this);
  29988. }
  29989. _this.isReady = true;
  29990. }, null, this.format, this._extension);
  29991. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29992. return;
  29993. }
  29994. };
  29995. /** @hidden */
  29996. InternalTexture.prototype._swapAndDie = function (target) {
  29997. target._webGLTexture = this._webGLTexture;
  29998. if (this._framebuffer) {
  29999. target._framebuffer = this._framebuffer;
  30000. }
  30001. if (this._depthStencilBuffer) {
  30002. target._depthStencilBuffer = this._depthStencilBuffer;
  30003. }
  30004. if (this._lodTextureHigh) {
  30005. if (target._lodTextureHigh) {
  30006. target._lodTextureHigh.dispose();
  30007. }
  30008. target._lodTextureHigh = this._lodTextureHigh;
  30009. }
  30010. if (this._lodTextureMid) {
  30011. if (target._lodTextureMid) {
  30012. target._lodTextureMid.dispose();
  30013. }
  30014. target._lodTextureMid = this._lodTextureMid;
  30015. }
  30016. if (this._lodTextureLow) {
  30017. if (target._lodTextureLow) {
  30018. target._lodTextureLow.dispose();
  30019. }
  30020. target._lodTextureLow = this._lodTextureLow;
  30021. }
  30022. var cache = this._engine.getLoadedTexturesCache();
  30023. var index = cache.indexOf(this);
  30024. if (index !== -1) {
  30025. cache.splice(index, 1);
  30026. }
  30027. };
  30028. /**
  30029. * Dispose the current allocated resources
  30030. */
  30031. InternalTexture.prototype.dispose = function () {
  30032. if (!this._webGLTexture) {
  30033. return;
  30034. }
  30035. this._references--;
  30036. if (this._references === 0) {
  30037. this._engine._releaseTexture(this);
  30038. this._webGLTexture = null;
  30039. this.previous = null;
  30040. this.next = null;
  30041. }
  30042. };
  30043. /**
  30044. * The source of the texture data is unknown
  30045. */
  30046. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30047. /**
  30048. * Texture data comes from an URL
  30049. */
  30050. InternalTexture.DATASOURCE_URL = 1;
  30051. /**
  30052. * Texture data is only used for temporary storage
  30053. */
  30054. InternalTexture.DATASOURCE_TEMP = 2;
  30055. /**
  30056. * Texture data comes from raw data (ArrayBuffer)
  30057. */
  30058. InternalTexture.DATASOURCE_RAW = 3;
  30059. /**
  30060. * Texture content is dynamic (video or dynamic texture)
  30061. */
  30062. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30063. /**
  30064. * Texture content is generated by rendering to it
  30065. */
  30066. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30067. /**
  30068. * Texture content is part of a multi render target process
  30069. */
  30070. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30071. /**
  30072. * Texture data comes from a cube data file
  30073. */
  30074. InternalTexture.DATASOURCE_CUBE = 7;
  30075. /**
  30076. * Texture data comes from a raw cube data
  30077. */
  30078. InternalTexture.DATASOURCE_CUBERAW = 8;
  30079. /**
  30080. * Texture data come from a prefiltered cube data file
  30081. */
  30082. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30083. /**
  30084. * Texture content is raw 3D data
  30085. */
  30086. InternalTexture.DATASOURCE_RAW3D = 10;
  30087. /**
  30088. * Texture content is a depth texture
  30089. */
  30090. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30091. /**
  30092. * Texture data comes from a raw cube data encoded with RGBD
  30093. */
  30094. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30095. return InternalTexture;
  30096. }());
  30097. BABYLON.InternalTexture = InternalTexture;
  30098. })(BABYLON || (BABYLON = {}));
  30099. //# sourceMappingURL=babylon.internalTexture.js.map
  30100. var BABYLON;
  30101. (function (BABYLON) {
  30102. var BaseTexture = /** @class */ (function () {
  30103. function BaseTexture(scene) {
  30104. this._hasAlpha = false;
  30105. this.getAlphaFromRGB = false;
  30106. this.level = 1;
  30107. this.coordinatesIndex = 0;
  30108. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30109. /**
  30110. * | Value | Type | Description |
  30111. * | ----- | ------------------ | ----------- |
  30112. * | 0 | CLAMP_ADDRESSMODE | |
  30113. * | 1 | WRAP_ADDRESSMODE | |
  30114. * | 2 | MIRROR_ADDRESSMODE | |
  30115. */
  30116. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30117. /**
  30118. * | Value | Type | Description |
  30119. * | ----- | ------------------ | ----------- |
  30120. * | 0 | CLAMP_ADDRESSMODE | |
  30121. * | 1 | WRAP_ADDRESSMODE | |
  30122. * | 2 | MIRROR_ADDRESSMODE | |
  30123. */
  30124. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30125. /**
  30126. * | Value | Type | Description |
  30127. * | ----- | ------------------ | ----------- |
  30128. * | 0 | CLAMP_ADDRESSMODE | |
  30129. * | 1 | WRAP_ADDRESSMODE | |
  30130. * | 2 | MIRROR_ADDRESSMODE | |
  30131. */
  30132. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30133. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30134. this.isCube = false;
  30135. this.is3D = false;
  30136. this.gammaSpace = true;
  30137. this.invertZ = false;
  30138. this.lodLevelInAlpha = false;
  30139. this.isRenderTarget = false;
  30140. this.animations = new Array();
  30141. /**
  30142. * An event triggered when the texture is disposed.
  30143. */
  30144. this.onDisposeObservable = new BABYLON.Observable();
  30145. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30146. this._cachedSize = BABYLON.Size.Zero();
  30147. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30148. if (this._scene) {
  30149. this._scene.textures.push(this);
  30150. }
  30151. this._uid = null;
  30152. }
  30153. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30154. get: function () {
  30155. return this._hasAlpha;
  30156. },
  30157. set: function (value) {
  30158. if (this._hasAlpha === value) {
  30159. return;
  30160. }
  30161. this._hasAlpha = value;
  30162. if (this._scene) {
  30163. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30164. }
  30165. },
  30166. enumerable: true,
  30167. configurable: true
  30168. });
  30169. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30170. get: function () {
  30171. return this._coordinatesMode;
  30172. },
  30173. /**
  30174. * How a texture is mapped.
  30175. *
  30176. * | Value | Type | Description |
  30177. * | ----- | ----------------------------------- | ----------- |
  30178. * | 0 | EXPLICIT_MODE | |
  30179. * | 1 | SPHERICAL_MODE | |
  30180. * | 2 | PLANAR_MODE | |
  30181. * | 3 | CUBIC_MODE | |
  30182. * | 4 | PROJECTION_MODE | |
  30183. * | 5 | SKYBOX_MODE | |
  30184. * | 6 | INVCUBIC_MODE | |
  30185. * | 7 | EQUIRECTANGULAR_MODE | |
  30186. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30187. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30188. */
  30189. set: function (value) {
  30190. if (this._coordinatesMode === value) {
  30191. return;
  30192. }
  30193. this._coordinatesMode = value;
  30194. if (this._scene) {
  30195. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30196. }
  30197. },
  30198. enumerable: true,
  30199. configurable: true
  30200. });
  30201. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30202. /**
  30203. * Gets whether or not the texture contains RGBD data.
  30204. */
  30205. get: function () {
  30206. return this._texture != null && this._texture._isRGBD;
  30207. },
  30208. enumerable: true,
  30209. configurable: true
  30210. });
  30211. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30212. get: function () {
  30213. if (this._texture)
  30214. return this._texture._lodGenerationOffset;
  30215. return 0.0;
  30216. },
  30217. set: function (value) {
  30218. if (this._texture)
  30219. this._texture._lodGenerationOffset = value;
  30220. },
  30221. enumerable: true,
  30222. configurable: true
  30223. });
  30224. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30225. get: function () {
  30226. if (this._texture)
  30227. return this._texture._lodGenerationScale;
  30228. return 0.0;
  30229. },
  30230. set: function (value) {
  30231. if (this._texture)
  30232. this._texture._lodGenerationScale = value;
  30233. },
  30234. enumerable: true,
  30235. configurable: true
  30236. });
  30237. Object.defineProperty(BaseTexture.prototype, "uid", {
  30238. get: function () {
  30239. if (!this._uid) {
  30240. this._uid = BABYLON.Tools.RandomId();
  30241. }
  30242. return this._uid;
  30243. },
  30244. enumerable: true,
  30245. configurable: true
  30246. });
  30247. BaseTexture.prototype.toString = function () {
  30248. return this.name;
  30249. };
  30250. BaseTexture.prototype.getClassName = function () {
  30251. return "BaseTexture";
  30252. };
  30253. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30254. set: function (callback) {
  30255. if (this._onDisposeObserver) {
  30256. this.onDisposeObservable.remove(this._onDisposeObserver);
  30257. }
  30258. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30264. get: function () {
  30265. return true;
  30266. },
  30267. enumerable: true,
  30268. configurable: true
  30269. });
  30270. BaseTexture.prototype.getScene = function () {
  30271. return this._scene;
  30272. };
  30273. BaseTexture.prototype.getTextureMatrix = function () {
  30274. return BABYLON.Matrix.IdentityReadOnly;
  30275. };
  30276. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30277. return BABYLON.Matrix.IdentityReadOnly;
  30278. };
  30279. BaseTexture.prototype.getInternalTexture = function () {
  30280. return this._texture;
  30281. };
  30282. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30283. return !this.isBlocking || this.isReady();
  30284. };
  30285. BaseTexture.prototype.isReady = function () {
  30286. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30287. this.delayLoad();
  30288. return false;
  30289. }
  30290. if (this._texture) {
  30291. return this._texture.isReady;
  30292. }
  30293. return false;
  30294. };
  30295. BaseTexture.prototype.getSize = function () {
  30296. if (this._texture) {
  30297. if (this._texture.width) {
  30298. this._cachedSize.width = this._texture.width;
  30299. this._cachedSize.height = this._texture.height;
  30300. return this._cachedSize;
  30301. }
  30302. if (this._texture._size) {
  30303. this._cachedSize.width = this._texture._size;
  30304. this._cachedSize.height = this._texture._size;
  30305. return this._cachedSize;
  30306. }
  30307. }
  30308. return this._cachedSize;
  30309. };
  30310. BaseTexture.prototype.getBaseSize = function () {
  30311. if (!this.isReady() || !this._texture)
  30312. return BABYLON.Size.Zero();
  30313. if (this._texture._size) {
  30314. return new BABYLON.Size(this._texture._size, this._texture._size);
  30315. }
  30316. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30317. };
  30318. BaseTexture.prototype.scale = function (ratio) {
  30319. };
  30320. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30321. get: function () {
  30322. return false;
  30323. },
  30324. enumerable: true,
  30325. configurable: true
  30326. });
  30327. /** @hidden */
  30328. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30329. if (!this._scene) {
  30330. return null;
  30331. }
  30332. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30333. for (var index = 0; index < texturesCache.length; index++) {
  30334. var texturesCacheEntry = texturesCache[index];
  30335. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30336. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30337. texturesCacheEntry.incrementReferences();
  30338. return texturesCacheEntry;
  30339. }
  30340. }
  30341. }
  30342. return null;
  30343. };
  30344. /** @hidden */
  30345. BaseTexture.prototype._rebuild = function () {
  30346. };
  30347. BaseTexture.prototype.delayLoad = function () {
  30348. };
  30349. BaseTexture.prototype.clone = function () {
  30350. return null;
  30351. };
  30352. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30353. get: function () {
  30354. if (!this._texture) {
  30355. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30356. }
  30357. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30358. },
  30359. enumerable: true,
  30360. configurable: true
  30361. });
  30362. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30363. get: function () {
  30364. if (!this._texture) {
  30365. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30366. }
  30367. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30368. },
  30369. enumerable: true,
  30370. configurable: true
  30371. });
  30372. /**
  30373. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30374. * This will returns an RGBA array buffer containing either in values (0-255) or
  30375. * float values (0-1) depending of the underlying buffer type.
  30376. * @param faceIndex The face of the texture to read (in case of cube texture)
  30377. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30378. * @returns The Array buffer containing the pixels data.
  30379. */
  30380. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30381. if (faceIndex === void 0) { faceIndex = 0; }
  30382. if (level === void 0) { level = 0; }
  30383. if (!this._texture) {
  30384. return null;
  30385. }
  30386. var size = this.getSize();
  30387. var width = size.width;
  30388. var height = size.height;
  30389. var scene = this.getScene();
  30390. if (!scene) {
  30391. return null;
  30392. }
  30393. var engine = scene.getEngine();
  30394. if (level != 0) {
  30395. width = width / Math.pow(2, level);
  30396. height = height / Math.pow(2, level);
  30397. width = Math.round(width);
  30398. height = Math.round(height);
  30399. }
  30400. if (this._texture.isCube) {
  30401. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30402. }
  30403. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30404. };
  30405. BaseTexture.prototype.releaseInternalTexture = function () {
  30406. if (this._texture) {
  30407. this._texture.dispose();
  30408. this._texture = null;
  30409. }
  30410. };
  30411. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30412. get: function () {
  30413. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30414. return null;
  30415. }
  30416. if (!this._texture._sphericalPolynomial) {
  30417. this._texture._sphericalPolynomial =
  30418. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30419. }
  30420. return this._texture._sphericalPolynomial;
  30421. },
  30422. set: function (value) {
  30423. if (this._texture) {
  30424. this._texture._sphericalPolynomial = value;
  30425. }
  30426. },
  30427. enumerable: true,
  30428. configurable: true
  30429. });
  30430. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30431. get: function () {
  30432. if (this._texture) {
  30433. return this._texture._lodTextureHigh;
  30434. }
  30435. return null;
  30436. },
  30437. enumerable: true,
  30438. configurable: true
  30439. });
  30440. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30441. get: function () {
  30442. if (this._texture) {
  30443. return this._texture._lodTextureMid;
  30444. }
  30445. return null;
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30451. get: function () {
  30452. if (this._texture) {
  30453. return this._texture._lodTextureLow;
  30454. }
  30455. return null;
  30456. },
  30457. enumerable: true,
  30458. configurable: true
  30459. });
  30460. BaseTexture.prototype.dispose = function () {
  30461. if (!this._scene) {
  30462. return;
  30463. }
  30464. // Animations
  30465. this._scene.stopAnimation(this);
  30466. // Remove from scene
  30467. this._scene._removePendingData(this);
  30468. var index = this._scene.textures.indexOf(this);
  30469. if (index >= 0) {
  30470. this._scene.textures.splice(index, 1);
  30471. }
  30472. if (this._texture === undefined) {
  30473. return;
  30474. }
  30475. // Release
  30476. this.releaseInternalTexture();
  30477. // Callback
  30478. this.onDisposeObservable.notifyObservers(this);
  30479. this.onDisposeObservable.clear();
  30480. };
  30481. BaseTexture.prototype.serialize = function () {
  30482. if (!this.name) {
  30483. return null;
  30484. }
  30485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30486. // Animations
  30487. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30488. return serializationObject;
  30489. };
  30490. BaseTexture.WhenAllReady = function (textures, callback) {
  30491. var numRemaining = textures.length;
  30492. if (numRemaining === 0) {
  30493. callback();
  30494. return;
  30495. }
  30496. var _loop_1 = function () {
  30497. texture = textures[i];
  30498. if (texture.isReady()) {
  30499. if (--numRemaining === 0) {
  30500. callback();
  30501. }
  30502. }
  30503. else {
  30504. onLoadObservable = texture.onLoadObservable;
  30505. var onLoadCallback_1 = function () {
  30506. onLoadObservable.removeCallback(onLoadCallback_1);
  30507. if (--numRemaining === 0) {
  30508. callback();
  30509. }
  30510. };
  30511. onLoadObservable.add(onLoadCallback_1);
  30512. }
  30513. };
  30514. var texture, onLoadObservable;
  30515. for (var i = 0; i < textures.length; i++) {
  30516. _loop_1();
  30517. }
  30518. };
  30519. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30520. __decorate([
  30521. BABYLON.serialize()
  30522. ], BaseTexture.prototype, "name", void 0);
  30523. __decorate([
  30524. BABYLON.serialize("hasAlpha")
  30525. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30526. __decorate([
  30527. BABYLON.serialize()
  30528. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30529. __decorate([
  30530. BABYLON.serialize()
  30531. ], BaseTexture.prototype, "level", void 0);
  30532. __decorate([
  30533. BABYLON.serialize()
  30534. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30535. __decorate([
  30536. BABYLON.serialize("coordinatesMode")
  30537. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30538. __decorate([
  30539. BABYLON.serialize()
  30540. ], BaseTexture.prototype, "wrapU", void 0);
  30541. __decorate([
  30542. BABYLON.serialize()
  30543. ], BaseTexture.prototype, "wrapV", void 0);
  30544. __decorate([
  30545. BABYLON.serialize()
  30546. ], BaseTexture.prototype, "wrapR", void 0);
  30547. __decorate([
  30548. BABYLON.serialize()
  30549. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30550. __decorate([
  30551. BABYLON.serialize()
  30552. ], BaseTexture.prototype, "isCube", void 0);
  30553. __decorate([
  30554. BABYLON.serialize()
  30555. ], BaseTexture.prototype, "is3D", void 0);
  30556. __decorate([
  30557. BABYLON.serialize()
  30558. ], BaseTexture.prototype, "gammaSpace", void 0);
  30559. __decorate([
  30560. BABYLON.serialize()
  30561. ], BaseTexture.prototype, "invertZ", void 0);
  30562. __decorate([
  30563. BABYLON.serialize()
  30564. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30565. __decorate([
  30566. BABYLON.serialize()
  30567. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30568. __decorate([
  30569. BABYLON.serialize()
  30570. ], BaseTexture.prototype, "lodGenerationScale", null);
  30571. __decorate([
  30572. BABYLON.serialize()
  30573. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30574. return BaseTexture;
  30575. }());
  30576. BABYLON.BaseTexture = BaseTexture;
  30577. })(BABYLON || (BABYLON = {}));
  30578. //# sourceMappingURL=babylon.baseTexture.js.map
  30579. var BABYLON;
  30580. (function (BABYLON) {
  30581. var Texture = /** @class */ (function (_super) {
  30582. __extends(Texture, _super);
  30583. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30584. if (noMipmap === void 0) { noMipmap = false; }
  30585. if (invertY === void 0) { invertY = true; }
  30586. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30587. if (onLoad === void 0) { onLoad = null; }
  30588. if (onError === void 0) { onError = null; }
  30589. if (buffer === void 0) { buffer = null; }
  30590. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30591. var _this = _super.call(this, scene) || this;
  30592. _this.uOffset = 0;
  30593. _this.vOffset = 0;
  30594. _this.uScale = 1.0;
  30595. _this.vScale = 1.0;
  30596. _this.uAng = 0;
  30597. _this.vAng = 0;
  30598. _this.wAng = 0;
  30599. /**
  30600. * Defines the center of rotation (U)
  30601. */
  30602. _this.uRotationCenter = 0.5;
  30603. /**
  30604. * Defines the center of rotation (V)
  30605. */
  30606. _this.vRotationCenter = 0.5;
  30607. /**
  30608. * Defines the center of rotation (W)
  30609. */
  30610. _this.wRotationCenter = 0.5;
  30611. _this._isBlocking = true;
  30612. _this.name = url || "";
  30613. _this.url = url;
  30614. _this._noMipmap = noMipmap;
  30615. _this._invertY = invertY;
  30616. _this._samplingMode = samplingMode;
  30617. _this._buffer = buffer;
  30618. _this._deleteBuffer = deleteBuffer;
  30619. if (format) {
  30620. _this._format = format;
  30621. }
  30622. scene = _this.getScene();
  30623. if (!scene) {
  30624. return _this;
  30625. }
  30626. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30627. var load = function () {
  30628. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30629. _this.onLoadObservable.notifyObservers(_this);
  30630. }
  30631. if (onLoad) {
  30632. onLoad();
  30633. }
  30634. if (!_this.isBlocking && scene) {
  30635. scene.resetCachedMaterial();
  30636. }
  30637. };
  30638. if (!_this.url) {
  30639. _this._delayedOnLoad = load;
  30640. _this._delayedOnError = onError;
  30641. return _this;
  30642. }
  30643. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30644. if (!_this._texture) {
  30645. if (!scene.useDelayedTextureLoading) {
  30646. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30647. if (deleteBuffer) {
  30648. delete _this._buffer;
  30649. }
  30650. }
  30651. else {
  30652. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30653. _this._delayedOnLoad = load;
  30654. _this._delayedOnError = onError;
  30655. }
  30656. }
  30657. else {
  30658. if (_this._texture.isReady) {
  30659. BABYLON.Tools.SetImmediate(function () { return load(); });
  30660. }
  30661. else {
  30662. _this._texture.onLoadedObservable.add(load);
  30663. }
  30664. }
  30665. return _this;
  30666. }
  30667. Object.defineProperty(Texture.prototype, "noMipmap", {
  30668. get: function () {
  30669. return this._noMipmap;
  30670. },
  30671. enumerable: true,
  30672. configurable: true
  30673. });
  30674. Object.defineProperty(Texture.prototype, "isBlocking", {
  30675. get: function () {
  30676. return this._isBlocking;
  30677. },
  30678. set: function (value) {
  30679. this._isBlocking = value;
  30680. },
  30681. enumerable: true,
  30682. configurable: true
  30683. });
  30684. Object.defineProperty(Texture.prototype, "samplingMode", {
  30685. get: function () {
  30686. return this._samplingMode;
  30687. },
  30688. enumerable: true,
  30689. configurable: true
  30690. });
  30691. /**
  30692. * Update the url (and optional buffer) of this texture if url was null during construction.
  30693. * @param url the url of the texture
  30694. * @param buffer the buffer of the texture (defaults to null)
  30695. */
  30696. Texture.prototype.updateURL = function (url, buffer) {
  30697. if (buffer === void 0) { buffer = null; }
  30698. if (this.url) {
  30699. throw new Error("URL is already set");
  30700. }
  30701. this.url = url;
  30702. this._buffer = buffer;
  30703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30704. this.delayLoad();
  30705. };
  30706. Texture.prototype.delayLoad = function () {
  30707. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30708. return;
  30709. }
  30710. var scene = this.getScene();
  30711. if (!scene) {
  30712. return;
  30713. }
  30714. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30715. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30716. if (!this._texture) {
  30717. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30718. if (this._deleteBuffer) {
  30719. delete this._buffer;
  30720. }
  30721. }
  30722. else {
  30723. if (this._delayedOnLoad) {
  30724. if (this._texture.isReady) {
  30725. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30726. }
  30727. else {
  30728. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30729. }
  30730. }
  30731. }
  30732. this._delayedOnLoad = null;
  30733. this._delayedOnError = null;
  30734. };
  30735. /**
  30736. * Default is Trilinear mode.
  30737. *
  30738. * | Value | Type | Description |
  30739. * | ----- | ------------------ | ----------- |
  30740. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30741. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30742. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30743. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30744. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30745. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30746. * | 7 | NEAREST_LINEAR | |
  30747. * | 8 | NEAREST_NEAREST | |
  30748. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30749. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30750. * | 11 | LINEAR_LINEAR | |
  30751. * | 12 | LINEAR_NEAREST | |
  30752. *
  30753. * > _mag_: magnification filter (close to the viewer)
  30754. * > _min_: minification filter (far from the viewer)
  30755. * > _mip_: filter used between mip map levels
  30756. *
  30757. */
  30758. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30759. if (!this._texture) {
  30760. return;
  30761. }
  30762. var scene = this.getScene();
  30763. if (!scene) {
  30764. return;
  30765. }
  30766. this._samplingMode = samplingMode;
  30767. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30768. };
  30769. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30770. x *= this.uScale;
  30771. y *= this.vScale;
  30772. x -= this.uRotationCenter * this.uScale;
  30773. y -= this.vRotationCenter * this.vScale;
  30774. z -= this.wRotationCenter;
  30775. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30776. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30777. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30778. t.z += this.wRotationCenter;
  30779. };
  30780. Texture.prototype.getTextureMatrix = function () {
  30781. var _this = this;
  30782. if (this.uOffset === this._cachedUOffset &&
  30783. this.vOffset === this._cachedVOffset &&
  30784. this.uScale === this._cachedUScale &&
  30785. this.vScale === this._cachedVScale &&
  30786. this.uAng === this._cachedUAng &&
  30787. this.vAng === this._cachedVAng &&
  30788. this.wAng === this._cachedWAng) {
  30789. return this._cachedTextureMatrix;
  30790. }
  30791. this._cachedUOffset = this.uOffset;
  30792. this._cachedVOffset = this.vOffset;
  30793. this._cachedUScale = this.uScale;
  30794. this._cachedVScale = this.vScale;
  30795. this._cachedUAng = this.uAng;
  30796. this._cachedVAng = this.vAng;
  30797. this._cachedWAng = this.wAng;
  30798. if (!this._cachedTextureMatrix) {
  30799. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30800. this._rowGenerationMatrix = new BABYLON.Matrix();
  30801. this._t0 = BABYLON.Vector3.Zero();
  30802. this._t1 = BABYLON.Vector3.Zero();
  30803. this._t2 = BABYLON.Vector3.Zero();
  30804. }
  30805. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30806. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30807. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30808. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30809. this._t1.subtractInPlace(this._t0);
  30810. this._t2.subtractInPlace(this._t0);
  30811. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30812. this._cachedTextureMatrix.m[0] = this._t1.x;
  30813. this._cachedTextureMatrix.m[1] = this._t1.y;
  30814. this._cachedTextureMatrix.m[2] = this._t1.z;
  30815. this._cachedTextureMatrix.m[4] = this._t2.x;
  30816. this._cachedTextureMatrix.m[5] = this._t2.y;
  30817. this._cachedTextureMatrix.m[6] = this._t2.z;
  30818. this._cachedTextureMatrix.m[8] = this._t0.x;
  30819. this._cachedTextureMatrix.m[9] = this._t0.y;
  30820. this._cachedTextureMatrix.m[10] = this._t0.z;
  30821. var scene = this.getScene();
  30822. if (!scene) {
  30823. return this._cachedTextureMatrix;
  30824. }
  30825. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30826. return mat.hasTexture(_this);
  30827. });
  30828. return this._cachedTextureMatrix;
  30829. };
  30830. Texture.prototype.getReflectionTextureMatrix = function () {
  30831. var _this = this;
  30832. var scene = this.getScene();
  30833. if (!scene) {
  30834. return this._cachedTextureMatrix;
  30835. }
  30836. if (this.uOffset === this._cachedUOffset &&
  30837. this.vOffset === this._cachedVOffset &&
  30838. this.uScale === this._cachedUScale &&
  30839. this.vScale === this._cachedVScale &&
  30840. this.coordinatesMode === this._cachedCoordinatesMode) {
  30841. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30842. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30843. return this._cachedTextureMatrix;
  30844. }
  30845. }
  30846. else {
  30847. return this._cachedTextureMatrix;
  30848. }
  30849. }
  30850. if (!this._cachedTextureMatrix) {
  30851. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30852. }
  30853. if (!this._projectionModeMatrix) {
  30854. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30855. }
  30856. this._cachedUOffset = this.uOffset;
  30857. this._cachedVOffset = this.vOffset;
  30858. this._cachedUScale = this.uScale;
  30859. this._cachedVScale = this.vScale;
  30860. this._cachedCoordinatesMode = this.coordinatesMode;
  30861. switch (this.coordinatesMode) {
  30862. case Texture.PLANAR_MODE:
  30863. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30864. this._cachedTextureMatrix[0] = this.uScale;
  30865. this._cachedTextureMatrix[5] = this.vScale;
  30866. this._cachedTextureMatrix[12] = this.uOffset;
  30867. this._cachedTextureMatrix[13] = this.vOffset;
  30868. break;
  30869. case Texture.PROJECTION_MODE:
  30870. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30871. this._projectionModeMatrix.m[0] = 0.5;
  30872. this._projectionModeMatrix.m[5] = -0.5;
  30873. this._projectionModeMatrix.m[10] = 0.0;
  30874. this._projectionModeMatrix.m[12] = 0.5;
  30875. this._projectionModeMatrix.m[13] = 0.5;
  30876. this._projectionModeMatrix.m[14] = 1.0;
  30877. this._projectionModeMatrix.m[15] = 1.0;
  30878. var projectionMatrix = scene.getProjectionMatrix();
  30879. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30880. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30881. break;
  30882. default:
  30883. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30884. break;
  30885. }
  30886. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30887. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30888. });
  30889. return this._cachedTextureMatrix;
  30890. };
  30891. Texture.prototype.clone = function () {
  30892. var _this = this;
  30893. return BABYLON.SerializationHelper.Clone(function () {
  30894. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30895. }, this);
  30896. };
  30897. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30898. get: function () {
  30899. if (!this._onLoadObservable) {
  30900. this._onLoadObservable = new BABYLON.Observable();
  30901. }
  30902. return this._onLoadObservable;
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. Texture.prototype.serialize = function () {
  30908. var serializationObject = _super.prototype.serialize.call(this);
  30909. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30910. serializationObject.base64String = this._buffer;
  30911. serializationObject.name = serializationObject.name.replace("data:", "");
  30912. }
  30913. serializationObject.invertY = this._invertY;
  30914. serializationObject.samplingMode = this.samplingMode;
  30915. return serializationObject;
  30916. };
  30917. Texture.prototype.getClassName = function () {
  30918. return "Texture";
  30919. };
  30920. Texture.prototype.dispose = function () {
  30921. _super.prototype.dispose.call(this);
  30922. if (this._onLoadObservable) {
  30923. this._onLoadObservable.clear();
  30924. this._onLoadObservable = null;
  30925. }
  30926. this._delayedOnLoad = null;
  30927. this._delayedOnError = null;
  30928. };
  30929. // Statics
  30930. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30931. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30932. if (onLoad === void 0) { onLoad = null; }
  30933. if (onError === void 0) { onError = null; }
  30934. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30935. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30936. };
  30937. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30938. if (parsedTexture.customType) {
  30939. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30940. // Update Sampling Mode
  30941. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30942. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30943. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30944. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30945. }
  30946. }
  30947. return parsedCustomTexture;
  30948. }
  30949. if (parsedTexture.isCube) {
  30950. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30951. }
  30952. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30953. return null;
  30954. }
  30955. var texture = BABYLON.SerializationHelper.Parse(function () {
  30956. var generateMipMaps = true;
  30957. if (parsedTexture.noMipmap) {
  30958. generateMipMaps = false;
  30959. }
  30960. if (parsedTexture.mirrorPlane) {
  30961. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30962. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30963. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30964. return mirrorTexture;
  30965. }
  30966. else if (parsedTexture.isRenderTarget) {
  30967. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30968. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30969. return renderTargetTexture;
  30970. }
  30971. else {
  30972. var texture;
  30973. if (parsedTexture.base64String) {
  30974. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30975. }
  30976. else {
  30977. var url = rootUrl + parsedTexture.name;
  30978. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30979. url = parsedTexture.url;
  30980. }
  30981. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30982. }
  30983. return texture;
  30984. }
  30985. }, parsedTexture, scene);
  30986. // Update Sampling Mode
  30987. if (parsedTexture.samplingMode) {
  30988. var sampling = parsedTexture.samplingMode;
  30989. if (texture._samplingMode !== sampling) {
  30990. texture.updateSamplingMode(sampling);
  30991. }
  30992. }
  30993. // Animations
  30994. if (parsedTexture.animations) {
  30995. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30996. var parsedAnimation = parsedTexture.animations[animationIndex];
  30997. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30998. }
  30999. }
  31000. return texture;
  31001. };
  31002. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31003. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31004. if (noMipmap === void 0) { noMipmap = false; }
  31005. if (invertY === void 0) { invertY = true; }
  31006. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31007. if (onLoad === void 0) { onLoad = null; }
  31008. if (onError === void 0) { onError = null; }
  31009. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31010. if (name.substr(0, 5) !== "data:") {
  31011. name = "data:" + name;
  31012. }
  31013. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31014. };
  31015. // Constants
  31016. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31017. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31018. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31019. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31020. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31021. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31022. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31023. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31024. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31025. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31026. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31027. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31028. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31029. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31030. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31031. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31032. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31033. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31034. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31035. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31036. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31037. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31038. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31039. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31040. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31041. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31042. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31043. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31044. /**
  31045. * 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
  31046. */
  31047. Texture.UseSerializedUrlIfAny = false;
  31048. __decorate([
  31049. BABYLON.serialize()
  31050. ], Texture.prototype, "url", void 0);
  31051. __decorate([
  31052. BABYLON.serialize()
  31053. ], Texture.prototype, "uOffset", void 0);
  31054. __decorate([
  31055. BABYLON.serialize()
  31056. ], Texture.prototype, "vOffset", void 0);
  31057. __decorate([
  31058. BABYLON.serialize()
  31059. ], Texture.prototype, "uScale", void 0);
  31060. __decorate([
  31061. BABYLON.serialize()
  31062. ], Texture.prototype, "vScale", void 0);
  31063. __decorate([
  31064. BABYLON.serialize()
  31065. ], Texture.prototype, "uAng", void 0);
  31066. __decorate([
  31067. BABYLON.serialize()
  31068. ], Texture.prototype, "vAng", void 0);
  31069. __decorate([
  31070. BABYLON.serialize()
  31071. ], Texture.prototype, "wAng", void 0);
  31072. __decorate([
  31073. BABYLON.serialize()
  31074. ], Texture.prototype, "uRotationCenter", void 0);
  31075. __decorate([
  31076. BABYLON.serialize()
  31077. ], Texture.prototype, "vRotationCenter", void 0);
  31078. __decorate([
  31079. BABYLON.serialize()
  31080. ], Texture.prototype, "wRotationCenter", void 0);
  31081. __decorate([
  31082. BABYLON.serialize()
  31083. ], Texture.prototype, "isBlocking", null);
  31084. return Texture;
  31085. }(BABYLON.BaseTexture));
  31086. BABYLON.Texture = Texture;
  31087. })(BABYLON || (BABYLON = {}));
  31088. //# sourceMappingURL=babylon.texture.js.map
  31089. var BABYLON;
  31090. (function (BABYLON) {
  31091. /**
  31092. * @hidden
  31093. **/
  31094. var _InstancesBatch = /** @class */ (function () {
  31095. function _InstancesBatch() {
  31096. this.mustReturn = false;
  31097. this.visibleInstances = new Array();
  31098. this.renderSelf = new Array();
  31099. }
  31100. return _InstancesBatch;
  31101. }());
  31102. BABYLON._InstancesBatch = _InstancesBatch;
  31103. var Mesh = /** @class */ (function (_super) {
  31104. __extends(Mesh, _super);
  31105. /**
  31106. * @constructor
  31107. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31108. * @param {Scene} scene The scene to add this mesh to.
  31109. * @param {Node} parent The parent of this mesh, if it has one
  31110. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31111. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31112. * When false, achieved by calling a clone(), also passing False.
  31113. * This will make creation of children, recursive.
  31114. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31115. */
  31116. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31117. if (scene === void 0) { scene = null; }
  31118. if (parent === void 0) { parent = null; }
  31119. if (source === void 0) { source = null; }
  31120. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31121. var _this = _super.call(this, name, scene) || this;
  31122. // Members
  31123. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31124. _this.instances = new Array();
  31125. _this._LODLevels = new Array();
  31126. /** @hidden */
  31127. _this._visibleInstances = {};
  31128. _this._renderIdForInstances = new Array();
  31129. _this._batchCache = new _InstancesBatch();
  31130. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31131. // Use by builder only to know what orientation were the mesh build in.
  31132. /** @hidden */
  31133. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31134. _this.overrideMaterialSideOrientation = null;
  31135. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31136. // Will be used to save a source mesh reference, If any
  31137. _this._source = null;
  31138. scene = _this.getScene();
  31139. if (source) {
  31140. // Geometry
  31141. if (source._geometry) {
  31142. source._geometry.applyToMesh(_this);
  31143. }
  31144. // Deep copy
  31145. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31146. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31147. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31148. ], ["_poseMatrix"]);
  31149. // Source mesh
  31150. _this._source = source;
  31151. // Construction Params
  31152. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31153. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31154. var myAnyThis = _this;
  31155. var myAnySource = source;
  31156. myAnyThis._closePath = myAnySource._closePath;
  31157. myAnyThis._idx = myAnySource._idx;
  31158. myAnyThis.dashSize = myAnySource.dashSize;
  31159. myAnyThis.gapSize = myAnySource.gapSize;
  31160. myAnyThis.path3D = myAnySource.path3D;
  31161. myAnyThis.pathArray = myAnySource.pathArray;
  31162. myAnyThis.arc = myAnySource.arc;
  31163. myAnyThis.radius = myAnySource.radius;
  31164. // Animation ranges
  31165. if (_this._source._ranges) {
  31166. var ranges = _this._source._ranges;
  31167. for (var name in ranges) {
  31168. if (!ranges.hasOwnProperty(name)) {
  31169. continue;
  31170. }
  31171. if (!ranges[name]) {
  31172. continue;
  31173. }
  31174. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31175. }
  31176. }
  31177. // Metadata
  31178. if (source.metadata && source.metadata.clone) {
  31179. _this.metadata = source.metadata.clone();
  31180. }
  31181. else {
  31182. _this.metadata = source.metadata;
  31183. }
  31184. // Tags
  31185. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31186. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31187. }
  31188. // Parent
  31189. _this.parent = source.parent;
  31190. // Pivot
  31191. _this.setPivotMatrix(source.getPivotMatrix());
  31192. _this.id = name + "." + source.id;
  31193. // Material
  31194. _this.material = source.material;
  31195. var index;
  31196. if (!doNotCloneChildren) {
  31197. // Children
  31198. var directDescendants = source.getDescendants(true);
  31199. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31200. var child = directDescendants[index_1];
  31201. if (child.clone) {
  31202. child.clone(name + "." + child.name, _this);
  31203. }
  31204. }
  31205. }
  31206. // Physics clone
  31207. var physicsEngine = _this.getScene().getPhysicsEngine();
  31208. if (clonePhysicsImpostor && physicsEngine) {
  31209. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31210. if (impostor) {
  31211. _this.physicsImpostor = impostor.clone(_this);
  31212. }
  31213. }
  31214. // Particles
  31215. for (index = 0; index < scene.particleSystems.length; index++) {
  31216. var system = scene.particleSystems[index];
  31217. if (system.emitter === source) {
  31218. system.clone(system.name, _this);
  31219. }
  31220. }
  31221. _this.refreshBoundingInfo();
  31222. _this.computeWorldMatrix(true);
  31223. }
  31224. // Parent
  31225. if (parent !== null) {
  31226. _this.parent = parent;
  31227. }
  31228. return _this;
  31229. }
  31230. Object.defineProperty(Mesh, "FRONTSIDE", {
  31231. /**
  31232. * Mesh side orientation : usually the external or front surface
  31233. */
  31234. get: function () {
  31235. return Mesh._FRONTSIDE;
  31236. },
  31237. enumerable: true,
  31238. configurable: true
  31239. });
  31240. Object.defineProperty(Mesh, "BACKSIDE", {
  31241. /**
  31242. * Mesh side orientation : usually the internal or back surface
  31243. */
  31244. get: function () {
  31245. return Mesh._BACKSIDE;
  31246. },
  31247. enumerable: true,
  31248. configurable: true
  31249. });
  31250. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31251. /**
  31252. * Mesh side orientation : both internal and external or front and back surfaces
  31253. */
  31254. get: function () {
  31255. return Mesh._DOUBLESIDE;
  31256. },
  31257. enumerable: true,
  31258. configurable: true
  31259. });
  31260. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31261. /**
  31262. * Mesh side orientation : by default, `FRONTSIDE`
  31263. */
  31264. get: function () {
  31265. return Mesh._DEFAULTSIDE;
  31266. },
  31267. enumerable: true,
  31268. configurable: true
  31269. });
  31270. Object.defineProperty(Mesh, "NO_CAP", {
  31271. /**
  31272. * Mesh cap setting : no cap
  31273. */
  31274. get: function () {
  31275. return Mesh._NO_CAP;
  31276. },
  31277. enumerable: true,
  31278. configurable: true
  31279. });
  31280. Object.defineProperty(Mesh, "CAP_START", {
  31281. /**
  31282. * Mesh cap setting : one cap at the beginning of the mesh
  31283. */
  31284. get: function () {
  31285. return Mesh._CAP_START;
  31286. },
  31287. enumerable: true,
  31288. configurable: true
  31289. });
  31290. Object.defineProperty(Mesh, "CAP_END", {
  31291. /**
  31292. * Mesh cap setting : one cap at the end of the mesh
  31293. */
  31294. get: function () {
  31295. return Mesh._CAP_END;
  31296. },
  31297. enumerable: true,
  31298. configurable: true
  31299. });
  31300. Object.defineProperty(Mesh, "CAP_ALL", {
  31301. /**
  31302. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31303. */
  31304. get: function () {
  31305. return Mesh._CAP_ALL;
  31306. },
  31307. enumerable: true,
  31308. configurable: true
  31309. });
  31310. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31311. /**
  31312. * An event triggered before rendering the mesh
  31313. */
  31314. get: function () {
  31315. if (!this._onBeforeRenderObservable) {
  31316. this._onBeforeRenderObservable = new BABYLON.Observable();
  31317. }
  31318. return this._onBeforeRenderObservable;
  31319. },
  31320. enumerable: true,
  31321. configurable: true
  31322. });
  31323. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31324. /**
  31325. * An event triggered after rendering the mesh
  31326. */
  31327. get: function () {
  31328. if (!this._onAfterRenderObservable) {
  31329. this._onAfterRenderObservable = new BABYLON.Observable();
  31330. }
  31331. return this._onAfterRenderObservable;
  31332. },
  31333. enumerable: true,
  31334. configurable: true
  31335. });
  31336. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31337. /**
  31338. * An event triggered before drawing the mesh
  31339. */
  31340. get: function () {
  31341. if (!this._onBeforeDrawObservable) {
  31342. this._onBeforeDrawObservable = new BABYLON.Observable();
  31343. }
  31344. return this._onBeforeDrawObservable;
  31345. },
  31346. enumerable: true,
  31347. configurable: true
  31348. });
  31349. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31350. set: function (callback) {
  31351. if (this._onBeforeDrawObserver) {
  31352. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31353. }
  31354. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31355. },
  31356. enumerable: true,
  31357. configurable: true
  31358. });
  31359. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31360. get: function () {
  31361. return this._morphTargetManager;
  31362. },
  31363. set: function (value) {
  31364. if (this._morphTargetManager === value) {
  31365. return;
  31366. }
  31367. this._morphTargetManager = value;
  31368. this._syncGeometryWithMorphTargetManager();
  31369. },
  31370. enumerable: true,
  31371. configurable: true
  31372. });
  31373. Object.defineProperty(Mesh.prototype, "source", {
  31374. get: function () {
  31375. return this._source;
  31376. },
  31377. enumerable: true,
  31378. configurable: true
  31379. });
  31380. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31381. get: function () {
  31382. return this._unIndexed;
  31383. },
  31384. set: function (value) {
  31385. if (this._unIndexed !== value) {
  31386. this._unIndexed = value;
  31387. this._markSubMeshesAsAttributesDirty();
  31388. }
  31389. },
  31390. enumerable: true,
  31391. configurable: true
  31392. });
  31393. // Methods
  31394. /**
  31395. * Returns the string "Mesh".
  31396. */
  31397. Mesh.prototype.getClassName = function () {
  31398. return "Mesh";
  31399. };
  31400. /**
  31401. * Returns a string.
  31402. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31403. */
  31404. Mesh.prototype.toString = function (fullDetails) {
  31405. var ret = _super.prototype.toString.call(this, fullDetails);
  31406. ret += ", n vertices: " + this.getTotalVertices();
  31407. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31408. if (this.animations) {
  31409. for (var i = 0; i < this.animations.length; i++) {
  31410. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31411. }
  31412. }
  31413. if (fullDetails) {
  31414. if (this._geometry) {
  31415. var ib = this.getIndices();
  31416. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31417. if (vb && ib) {
  31418. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31419. }
  31420. }
  31421. else {
  31422. ret += ", flat shading: UNKNOWN";
  31423. }
  31424. }
  31425. return ret;
  31426. };
  31427. /** @hidden */
  31428. Mesh.prototype._unBindEffect = function () {
  31429. _super.prototype._unBindEffect.call(this);
  31430. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31431. var instance = _a[_i];
  31432. instance._unBindEffect();
  31433. }
  31434. };
  31435. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31436. /**
  31437. * True if the mesh has some Levels Of Details (LOD).
  31438. * Returns a boolean.
  31439. */
  31440. get: function () {
  31441. return this._LODLevels.length > 0;
  31442. },
  31443. enumerable: true,
  31444. configurable: true
  31445. });
  31446. /**
  31447. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31448. * @returns an array of {BABYLON.MeshLODLevel}
  31449. */
  31450. Mesh.prototype.getLODLevels = function () {
  31451. return this._LODLevels;
  31452. };
  31453. Mesh.prototype._sortLODLevels = function () {
  31454. this._LODLevels.sort(function (a, b) {
  31455. if (a.distance < b.distance) {
  31456. return 1;
  31457. }
  31458. if (a.distance > b.distance) {
  31459. return -1;
  31460. }
  31461. return 0;
  31462. });
  31463. };
  31464. /**
  31465. * Add a mesh as LOD level triggered at the given distance.
  31466. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31467. * @param distance The distance from the center of the object to show this level
  31468. * @param mesh The mesh to be added as LOD level (can be null)
  31469. * @return This mesh (for chaining)
  31470. */
  31471. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31472. if (mesh && mesh._masterMesh) {
  31473. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31474. return this;
  31475. }
  31476. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31477. this._LODLevels.push(level);
  31478. if (mesh) {
  31479. mesh._masterMesh = this;
  31480. }
  31481. this._sortLODLevels();
  31482. return this;
  31483. };
  31484. /**
  31485. * Returns the LOD level mesh at the passed distance or null if not found.
  31486. * It is related to the method `addLODLevel(distance, mesh)`.
  31487. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31488. * Returns an object Mesh or `null`.
  31489. */
  31490. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31491. for (var index = 0; index < this._LODLevels.length; index++) {
  31492. var level = this._LODLevels[index];
  31493. if (level.distance === distance) {
  31494. return level.mesh;
  31495. }
  31496. }
  31497. return null;
  31498. };
  31499. /**
  31500. * Remove a mesh from the LOD array
  31501. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31502. * @param {Mesh} mesh The mesh to be removed.
  31503. * @return {Mesh} This mesh (for chaining)
  31504. */
  31505. Mesh.prototype.removeLODLevel = function (mesh) {
  31506. for (var index = 0; index < this._LODLevels.length; index++) {
  31507. if (this._LODLevels[index].mesh === mesh) {
  31508. this._LODLevels.splice(index, 1);
  31509. if (mesh) {
  31510. mesh._masterMesh = null;
  31511. }
  31512. }
  31513. }
  31514. this._sortLODLevels();
  31515. return this;
  31516. };
  31517. /**
  31518. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31519. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31520. */
  31521. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31522. if (!this._LODLevels || this._LODLevels.length === 0) {
  31523. return this;
  31524. }
  31525. var bSphere;
  31526. if (boundingSphere) {
  31527. bSphere = boundingSphere;
  31528. }
  31529. else {
  31530. var boundingInfo = this.getBoundingInfo();
  31531. bSphere = boundingInfo.boundingSphere;
  31532. }
  31533. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31534. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31535. if (this.onLODLevelSelection) {
  31536. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31537. }
  31538. return this;
  31539. }
  31540. for (var index = 0; index < this._LODLevels.length; index++) {
  31541. var level = this._LODLevels[index];
  31542. if (level.distance < distanceToCamera) {
  31543. if (level.mesh) {
  31544. level.mesh._preActivate();
  31545. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31546. }
  31547. if (this.onLODLevelSelection) {
  31548. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31549. }
  31550. return level.mesh;
  31551. }
  31552. }
  31553. if (this.onLODLevelSelection) {
  31554. this.onLODLevelSelection(distanceToCamera, this, this);
  31555. }
  31556. return this;
  31557. };
  31558. Object.defineProperty(Mesh.prototype, "geometry", {
  31559. /**
  31560. * Returns the mesh internal Geometry object.
  31561. */
  31562. get: function () {
  31563. return this._geometry;
  31564. },
  31565. enumerable: true,
  31566. configurable: true
  31567. });
  31568. /**
  31569. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31570. */
  31571. Mesh.prototype.getTotalVertices = function () {
  31572. if (this._geometry === null || this._geometry === undefined) {
  31573. return 0;
  31574. }
  31575. return this._geometry.getTotalVertices();
  31576. };
  31577. /**
  31578. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31579. * 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.
  31580. * You can force the copy with forceCopy === true
  31581. * Returns null if the mesh has no geometry or no vertex buffer.
  31582. * Possible `kind` values :
  31583. * - BABYLON.VertexBuffer.PositionKind
  31584. * - BABYLON.VertexBuffer.UVKind
  31585. * - BABYLON.VertexBuffer.UV2Kind
  31586. * - BABYLON.VertexBuffer.UV3Kind
  31587. * - BABYLON.VertexBuffer.UV4Kind
  31588. * - BABYLON.VertexBuffer.UV5Kind
  31589. * - BABYLON.VertexBuffer.UV6Kind
  31590. * - BABYLON.VertexBuffer.ColorKind
  31591. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31592. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31593. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31594. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31595. */
  31596. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31597. if (!this._geometry) {
  31598. return null;
  31599. }
  31600. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31601. };
  31602. /**
  31603. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31604. * Returns `null` if the mesh has no geometry.
  31605. * Possible `kind` values :
  31606. * - BABYLON.VertexBuffer.PositionKind
  31607. * - BABYLON.VertexBuffer.UVKind
  31608. * - BABYLON.VertexBuffer.UV2Kind
  31609. * - BABYLON.VertexBuffer.UV3Kind
  31610. * - BABYLON.VertexBuffer.UV4Kind
  31611. * - BABYLON.VertexBuffer.UV5Kind
  31612. * - BABYLON.VertexBuffer.UV6Kind
  31613. * - BABYLON.VertexBuffer.ColorKind
  31614. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31615. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31616. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31617. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31618. */
  31619. Mesh.prototype.getVertexBuffer = function (kind) {
  31620. if (!this._geometry) {
  31621. return null;
  31622. }
  31623. return this._geometry.getVertexBuffer(kind);
  31624. };
  31625. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31626. if (!this._geometry) {
  31627. if (this._delayInfo) {
  31628. return this._delayInfo.indexOf(kind) !== -1;
  31629. }
  31630. return false;
  31631. }
  31632. return this._geometry.isVerticesDataPresent(kind);
  31633. };
  31634. /**
  31635. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31636. * Possible `kind` values :
  31637. * - BABYLON.VertexBuffer.PositionKind
  31638. * - BABYLON.VertexBuffer.UVKind
  31639. * - BABYLON.VertexBuffer.UV2Kind
  31640. * - BABYLON.VertexBuffer.UV3Kind
  31641. * - BABYLON.VertexBuffer.UV4Kind
  31642. * - BABYLON.VertexBuffer.UV5Kind
  31643. * - BABYLON.VertexBuffer.UV6Kind
  31644. * - BABYLON.VertexBuffer.ColorKind
  31645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31649. */
  31650. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31651. if (!this._geometry) {
  31652. if (this._delayInfo) {
  31653. return this._delayInfo.indexOf(kind) !== -1;
  31654. }
  31655. return false;
  31656. }
  31657. return this._geometry.isVertexBufferUpdatable(kind);
  31658. };
  31659. /**
  31660. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31661. * Possible `kind` values :
  31662. * - BABYLON.VertexBuffer.PositionKind
  31663. * - BABYLON.VertexBuffer.UVKind
  31664. * - BABYLON.VertexBuffer.UV2Kind
  31665. * - BABYLON.VertexBuffer.UV3Kind
  31666. * - BABYLON.VertexBuffer.UV4Kind
  31667. * - BABYLON.VertexBuffer.UV5Kind
  31668. * - BABYLON.VertexBuffer.UV6Kind
  31669. * - BABYLON.VertexBuffer.ColorKind
  31670. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31671. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31672. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31673. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31674. */
  31675. Mesh.prototype.getVerticesDataKinds = function () {
  31676. if (!this._geometry) {
  31677. var result = new Array();
  31678. if (this._delayInfo) {
  31679. this._delayInfo.forEach(function (kind, index, array) {
  31680. result.push(kind);
  31681. });
  31682. }
  31683. return result;
  31684. }
  31685. return this._geometry.getVerticesDataKinds();
  31686. };
  31687. /**
  31688. * Returns a positive integer : the total number of indices in this mesh geometry.
  31689. * Returns zero if the mesh has no geometry.
  31690. */
  31691. Mesh.prototype.getTotalIndices = function () {
  31692. if (!this._geometry) {
  31693. return 0;
  31694. }
  31695. return this._geometry.getTotalIndices();
  31696. };
  31697. /**
  31698. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31699. * @param copyWhenShared If 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.
  31700. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31701. * @returns the indices array or an empty array if the mesh has no geometry
  31702. */
  31703. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31704. if (!this._geometry) {
  31705. return [];
  31706. }
  31707. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31708. };
  31709. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31710. get: function () {
  31711. return this._masterMesh !== null && this._masterMesh !== undefined;
  31712. },
  31713. enumerable: true,
  31714. configurable: true
  31715. });
  31716. /**
  31717. * Determine if the current mesh is ready to be rendered
  31718. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31719. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31720. * @returns true if all associated assets are ready (material, textures, shaders)
  31721. */
  31722. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31723. if (completeCheck === void 0) { completeCheck = false; }
  31724. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31726. return false;
  31727. }
  31728. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31729. return false;
  31730. }
  31731. if (!this.subMeshes || this.subMeshes.length === 0) {
  31732. return true;
  31733. }
  31734. if (!completeCheck) {
  31735. return true;
  31736. }
  31737. var engine = this.getEngine();
  31738. var scene = this.getScene();
  31739. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31740. this.computeWorldMatrix();
  31741. var mat = this.material || scene.defaultMaterial;
  31742. if (mat) {
  31743. if (mat.storeEffectOnSubMeshes) {
  31744. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31745. var subMesh = _a[_i];
  31746. var effectiveMaterial = subMesh.getMaterial();
  31747. if (effectiveMaterial) {
  31748. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31749. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31750. return false;
  31751. }
  31752. }
  31753. else {
  31754. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31755. return false;
  31756. }
  31757. }
  31758. }
  31759. }
  31760. }
  31761. else {
  31762. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31763. return false;
  31764. }
  31765. }
  31766. }
  31767. // Shadows
  31768. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31769. var light = _c[_b];
  31770. var generator = light.getShadowGenerator();
  31771. if (generator) {
  31772. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31773. var subMesh = _e[_d];
  31774. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31775. return false;
  31776. }
  31777. }
  31778. }
  31779. }
  31780. // LOD
  31781. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31782. var lod = _g[_f];
  31783. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31784. return false;
  31785. }
  31786. }
  31787. return true;
  31788. };
  31789. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31790. /**
  31791. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31792. * This property is pertinent only for updatable parametric shapes.
  31793. */
  31794. get: function () {
  31795. return this._areNormalsFrozen;
  31796. },
  31797. enumerable: true,
  31798. configurable: true
  31799. });
  31800. /**
  31801. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31802. * It has no effect at all on other shapes.
  31803. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31804. * Returns the Mesh.
  31805. */
  31806. Mesh.prototype.freezeNormals = function () {
  31807. this._areNormalsFrozen = true;
  31808. return this;
  31809. };
  31810. /**
  31811. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31812. * It has no effect at all on other shapes.
  31813. * It reactivates the mesh normals computation if it was previously frozen.
  31814. * Returns the Mesh.
  31815. */
  31816. Mesh.prototype.unfreezeNormals = function () {
  31817. this._areNormalsFrozen = false;
  31818. return this;
  31819. };
  31820. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31821. /**
  31822. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31823. */
  31824. set: function (count) {
  31825. this._overridenInstanceCount = count;
  31826. },
  31827. enumerable: true,
  31828. configurable: true
  31829. });
  31830. // Methods
  31831. /** @hidden */
  31832. Mesh.prototype._preActivate = function () {
  31833. var sceneRenderId = this.getScene().getRenderId();
  31834. if (this._preActivateId === sceneRenderId) {
  31835. return this;
  31836. }
  31837. this._preActivateId = sceneRenderId;
  31838. this._visibleInstances = null;
  31839. return this;
  31840. };
  31841. /** @hidden */
  31842. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31843. if (this._visibleInstances) {
  31844. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31845. }
  31846. return this;
  31847. };
  31848. /** @hidden */
  31849. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31850. if (!this._visibleInstances) {
  31851. this._visibleInstances = {};
  31852. this._visibleInstances.defaultRenderId = renderId;
  31853. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31854. }
  31855. if (!this._visibleInstances[renderId]) {
  31856. this._visibleInstances[renderId] = new Array();
  31857. }
  31858. this._visibleInstances[renderId].push(instance);
  31859. return this;
  31860. };
  31861. /**
  31862. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31863. * This means the mesh underlying bounding box and sphere are recomputed.
  31864. * Returns the Mesh.
  31865. */
  31866. Mesh.prototype.refreshBoundingInfo = function () {
  31867. return this._refreshBoundingInfo(false);
  31868. };
  31869. /** @hidden */
  31870. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31871. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31872. return this;
  31873. }
  31874. var data = this._getPositionData(applySkeleton);
  31875. if (data) {
  31876. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31877. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31878. }
  31879. if (this.subMeshes) {
  31880. for (var index = 0; index < this.subMeshes.length; index++) {
  31881. this.subMeshes[index].refreshBoundingInfo();
  31882. }
  31883. }
  31884. this._updateBoundingInfo();
  31885. return this;
  31886. };
  31887. Mesh.prototype._getPositionData = function (applySkeleton) {
  31888. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31889. if (data && applySkeleton && this.skeleton) {
  31890. data = BABYLON.Tools.Slice(data);
  31891. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31892. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31893. if (matricesWeightsData && matricesIndicesData) {
  31894. var needExtras = this.numBoneInfluencers > 4;
  31895. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31896. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31897. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31898. var tempVector = BABYLON.Tmp.Vector3[0];
  31899. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31900. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31901. var matWeightIdx = 0;
  31902. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31903. finalMatrix.reset();
  31904. var inf;
  31905. var weight;
  31906. for (inf = 0; inf < 4; inf++) {
  31907. weight = matricesWeightsData[matWeightIdx + inf];
  31908. if (weight > 0) {
  31909. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31910. finalMatrix.addToSelf(tempMatrix);
  31911. }
  31912. }
  31913. if (needExtras) {
  31914. for (inf = 0; inf < 4; inf++) {
  31915. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31916. if (weight > 0) {
  31917. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31918. finalMatrix.addToSelf(tempMatrix);
  31919. }
  31920. }
  31921. }
  31922. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31923. tempVector.toArray(data, index);
  31924. }
  31925. }
  31926. }
  31927. return data;
  31928. };
  31929. /** @hidden */
  31930. Mesh.prototype._createGlobalSubMesh = function (force) {
  31931. var totalVertices = this.getTotalVertices();
  31932. if (!totalVertices || !this.getIndices()) {
  31933. return null;
  31934. }
  31935. // Check if we need to recreate the submeshes
  31936. if (this.subMeshes && this.subMeshes.length > 0) {
  31937. var ib = this.getIndices();
  31938. if (!ib) {
  31939. return null;
  31940. }
  31941. var totalIndices = ib.length;
  31942. var needToRecreate = false;
  31943. if (force) {
  31944. needToRecreate = true;
  31945. }
  31946. else {
  31947. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31948. var submesh = _a[_i];
  31949. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31950. needToRecreate = true;
  31951. break;
  31952. }
  31953. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31954. needToRecreate = true;
  31955. break;
  31956. }
  31957. }
  31958. }
  31959. if (!needToRecreate) {
  31960. return this.subMeshes[0];
  31961. }
  31962. }
  31963. this.releaseSubMeshes();
  31964. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31965. };
  31966. Mesh.prototype.subdivide = function (count) {
  31967. if (count < 1) {
  31968. return;
  31969. }
  31970. var totalIndices = this.getTotalIndices();
  31971. var subdivisionSize = (totalIndices / count) | 0;
  31972. var offset = 0;
  31973. // Ensure that subdivisionSize is a multiple of 3
  31974. while (subdivisionSize % 3 !== 0) {
  31975. subdivisionSize++;
  31976. }
  31977. this.releaseSubMeshes();
  31978. for (var index = 0; index < count; index++) {
  31979. if (offset >= totalIndices) {
  31980. break;
  31981. }
  31982. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31983. offset += subdivisionSize;
  31984. }
  31985. this.synchronizeInstances();
  31986. };
  31987. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31988. if (updatable === void 0) { updatable = false; }
  31989. if (!this._geometry) {
  31990. var vertexData = new BABYLON.VertexData();
  31991. vertexData.set(data, kind);
  31992. var scene = this.getScene();
  31993. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31994. }
  31995. else {
  31996. this._geometry.setVerticesData(kind, data, updatable, stride);
  31997. }
  31998. return this;
  31999. };
  32000. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32001. if (updatable === void 0) { updatable = true; }
  32002. var vb = this.getVertexBuffer(kind);
  32003. if (!vb || vb.isUpdatable() === updatable) {
  32004. return;
  32005. }
  32006. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32007. };
  32008. /**
  32009. * Sets the mesh VertexBuffer.
  32010. * Returns the Mesh.
  32011. */
  32012. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32013. if (!this._geometry) {
  32014. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32015. }
  32016. this._geometry.setVerticesBuffer(buffer);
  32017. return this;
  32018. };
  32019. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32020. if (!this._geometry) {
  32021. return this;
  32022. }
  32023. if (!makeItUnique) {
  32024. this._geometry.updateVerticesData(kind, data, updateExtends);
  32025. }
  32026. else {
  32027. this.makeGeometryUnique();
  32028. this.updateVerticesData(kind, data, updateExtends, false);
  32029. }
  32030. return this;
  32031. };
  32032. /**
  32033. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32034. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32035. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32036. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32037. * Returns the Mesh.
  32038. */
  32039. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32040. if (computeNormals === void 0) { computeNormals = true; }
  32041. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32042. if (!positions) {
  32043. return this;
  32044. }
  32045. positionFunction(positions);
  32046. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32047. if (computeNormals) {
  32048. var indices = this.getIndices();
  32049. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32050. if (!normals) {
  32051. return this;
  32052. }
  32053. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32054. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32055. }
  32056. return this;
  32057. };
  32058. /**
  32059. * Creates a un-shared specific occurence of the geometry for the mesh.
  32060. * Returns the Mesh.
  32061. */
  32062. Mesh.prototype.makeGeometryUnique = function () {
  32063. if (!this._geometry) {
  32064. return this;
  32065. }
  32066. var oldGeometry = this._geometry;
  32067. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32068. oldGeometry.releaseForMesh(this, true);
  32069. geometry.applyToMesh(this);
  32070. return this;
  32071. };
  32072. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32073. if (totalVertices === void 0) { totalVertices = null; }
  32074. if (updatable === void 0) { updatable = false; }
  32075. if (!this._geometry) {
  32076. var vertexData = new BABYLON.VertexData();
  32077. vertexData.indices = indices;
  32078. var scene = this.getScene();
  32079. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32080. }
  32081. else {
  32082. this._geometry.setIndices(indices, totalVertices, updatable);
  32083. }
  32084. return this;
  32085. };
  32086. /**
  32087. * Update the current index buffer
  32088. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32089. * Returns the Mesh.
  32090. */
  32091. Mesh.prototype.updateIndices = function (indices, offset) {
  32092. if (!this._geometry) {
  32093. return this;
  32094. }
  32095. this._geometry.updateIndices(indices, offset);
  32096. return this;
  32097. };
  32098. /**
  32099. * Invert the geometry to move from a right handed system to a left handed one.
  32100. * Returns the Mesh.
  32101. */
  32102. Mesh.prototype.toLeftHanded = function () {
  32103. if (!this._geometry) {
  32104. return this;
  32105. }
  32106. this._geometry.toLeftHanded();
  32107. return this;
  32108. };
  32109. /** @hidden */
  32110. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32111. if (!this._geometry) {
  32112. return this;
  32113. }
  32114. var engine = this.getScene().getEngine();
  32115. // Wireframe
  32116. var indexToBind;
  32117. if (this._unIndexed) {
  32118. indexToBind = null;
  32119. }
  32120. else {
  32121. switch (fillMode) {
  32122. case BABYLON.Material.PointFillMode:
  32123. indexToBind = null;
  32124. break;
  32125. case BABYLON.Material.WireFrameFillMode:
  32126. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32127. break;
  32128. default:
  32129. case BABYLON.Material.TriangleFillMode:
  32130. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32131. break;
  32132. }
  32133. }
  32134. // VBOs
  32135. this._geometry._bind(effect, indexToBind);
  32136. return this;
  32137. };
  32138. /** @hidden */
  32139. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32140. if (alternate === void 0) { alternate = false; }
  32141. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32142. return this;
  32143. }
  32144. if (this._onBeforeDrawObservable) {
  32145. this._onBeforeDrawObservable.notifyObservers(this);
  32146. }
  32147. var scene = this.getScene();
  32148. var engine = scene.getEngine();
  32149. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32150. // or triangles as points
  32151. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32152. }
  32153. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32154. // Triangles as wireframe
  32155. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32156. }
  32157. else {
  32158. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32159. }
  32160. if (scene._isAlternateRenderingEnabled && !alternate) {
  32161. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32162. if (!effect || !scene.activeCamera) {
  32163. return this;
  32164. }
  32165. scene._switchToAlternateCameraConfiguration(true);
  32166. this._effectiveMaterial.bindView(effect);
  32167. this._effectiveMaterial.bindViewProjection(effect);
  32168. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32169. this._draw(subMesh, fillMode, instancesCount, true);
  32170. engine.setViewport(scene.activeCamera.viewport);
  32171. scene._switchToAlternateCameraConfiguration(false);
  32172. this._effectiveMaterial.bindView(effect);
  32173. this._effectiveMaterial.bindViewProjection(effect);
  32174. }
  32175. return this;
  32176. };
  32177. /**
  32178. * Registers for this mesh a javascript function called just before the rendering process.
  32179. * This function is passed the current mesh.
  32180. * Return the Mesh.
  32181. */
  32182. Mesh.prototype.registerBeforeRender = function (func) {
  32183. this.onBeforeRenderObservable.add(func);
  32184. return this;
  32185. };
  32186. /**
  32187. * Disposes a previously registered javascript function called before the rendering.
  32188. * This function is passed the current mesh.
  32189. * Returns the Mesh.
  32190. */
  32191. Mesh.prototype.unregisterBeforeRender = function (func) {
  32192. this.onBeforeRenderObservable.removeCallback(func);
  32193. return this;
  32194. };
  32195. /**
  32196. * Registers for this mesh a javascript function called just after the rendering is complete.
  32197. * This function is passed the current mesh.
  32198. * Returns the Mesh.
  32199. */
  32200. Mesh.prototype.registerAfterRender = function (func) {
  32201. this.onAfterRenderObservable.add(func);
  32202. return this;
  32203. };
  32204. /**
  32205. * Disposes a previously registered javascript function called after the rendering.
  32206. * This function is passed the current mesh.
  32207. * Return the Mesh.
  32208. */
  32209. Mesh.prototype.unregisterAfterRender = function (func) {
  32210. this.onAfterRenderObservable.removeCallback(func);
  32211. return this;
  32212. };
  32213. /** @hidden */
  32214. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32215. var scene = this.getScene();
  32216. this._batchCache.mustReturn = false;
  32217. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32218. this._batchCache.visibleInstances[subMeshId] = null;
  32219. if (this._visibleInstances) {
  32220. var currentRenderId = scene.getRenderId();
  32221. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32222. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32223. var selfRenderId = this._renderId;
  32224. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32225. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32226. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32227. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32228. }
  32229. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32230. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32231. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32232. this._batchCache.mustReturn = true;
  32233. return this._batchCache;
  32234. }
  32235. if (currentRenderId !== selfRenderId) {
  32236. this._batchCache.renderSelf[subMeshId] = false;
  32237. }
  32238. }
  32239. this._renderIdForInstances[subMeshId] = currentRenderId;
  32240. }
  32241. return this._batchCache;
  32242. };
  32243. /** @hidden */
  32244. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32245. var visibleInstances = batch.visibleInstances[subMesh._id];
  32246. if (!visibleInstances) {
  32247. return this;
  32248. }
  32249. var matricesCount = visibleInstances.length + 1;
  32250. var bufferSize = matricesCount * 16 * 4;
  32251. var currentInstancesBufferSize = this._instancesBufferSize;
  32252. var instancesBuffer = this._instancesBuffer;
  32253. while (this._instancesBufferSize < bufferSize) {
  32254. this._instancesBufferSize *= 2;
  32255. }
  32256. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32257. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32258. }
  32259. var offset = 0;
  32260. var instancesCount = 0;
  32261. var world = this.getWorldMatrix();
  32262. if (batch.renderSelf[subMesh._id]) {
  32263. world.copyToArray(this._instancesData, offset);
  32264. offset += 16;
  32265. instancesCount++;
  32266. }
  32267. if (visibleInstances) {
  32268. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32269. var instance = visibleInstances[instanceIndex];
  32270. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32271. offset += 16;
  32272. instancesCount++;
  32273. }
  32274. }
  32275. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32276. if (instancesBuffer) {
  32277. instancesBuffer.dispose();
  32278. }
  32279. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32280. this._instancesBuffer = instancesBuffer;
  32281. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32282. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32283. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32284. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32285. }
  32286. else {
  32287. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32288. }
  32289. this._bind(subMesh, effect, fillMode);
  32290. this._draw(subMesh, fillMode, instancesCount);
  32291. engine.unbindInstanceAttributes();
  32292. return this;
  32293. };
  32294. /** @hidden */
  32295. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32296. var scene = this.getScene();
  32297. var engine = scene.getEngine();
  32298. if (hardwareInstancedRendering) {
  32299. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32300. }
  32301. else {
  32302. if (batch.renderSelf[subMesh._id]) {
  32303. // Draw
  32304. if (onBeforeDraw) {
  32305. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32306. }
  32307. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32308. }
  32309. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32310. if (visibleInstancesForSubMesh) {
  32311. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32312. var instance = visibleInstancesForSubMesh[instanceIndex];
  32313. // World
  32314. var world = instance.getWorldMatrix();
  32315. if (onBeforeDraw) {
  32316. onBeforeDraw(true, world, effectiveMaterial);
  32317. }
  32318. // Draw
  32319. this._draw(subMesh, fillMode);
  32320. }
  32321. }
  32322. }
  32323. return this;
  32324. };
  32325. /**
  32326. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32327. * @param subMesh defines the subMesh to render
  32328. * @param enableAlphaMode defines if alpha mode can be changed
  32329. * @returns the current mesh
  32330. */
  32331. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32332. this._checkOcclusionQuery();
  32333. if (this._isOccluded) {
  32334. return this;
  32335. }
  32336. var scene = this.getScene();
  32337. // Managing instances
  32338. var batch = this._getInstancesRenderList(subMesh._id);
  32339. if (batch.mustReturn) {
  32340. return this;
  32341. }
  32342. // Checking geometry state
  32343. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32344. return this;
  32345. }
  32346. if (this._onBeforeRenderObservable) {
  32347. this._onBeforeRenderObservable.notifyObservers(this);
  32348. }
  32349. var engine = scene.getEngine();
  32350. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32351. // Material
  32352. var material = subMesh.getMaterial();
  32353. if (!material) {
  32354. return this;
  32355. }
  32356. this._effectiveMaterial = material;
  32357. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32358. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32359. return this;
  32360. }
  32361. }
  32362. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32363. return this;
  32364. }
  32365. // Alpha mode
  32366. if (enableAlphaMode) {
  32367. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32368. }
  32369. // Outline - step 1
  32370. var savedDepthWrite = engine.getDepthWrite();
  32371. if (this.renderOutline) {
  32372. engine.setDepthWrite(false);
  32373. scene.getOutlineRenderer().render(subMesh, batch);
  32374. engine.setDepthWrite(savedDepthWrite);
  32375. }
  32376. var effect;
  32377. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32378. effect = subMesh.effect;
  32379. }
  32380. else {
  32381. effect = this._effectiveMaterial.getEffect();
  32382. }
  32383. if (!effect) {
  32384. return this;
  32385. }
  32386. var sideOrientation = this.overrideMaterialSideOrientation;
  32387. if (sideOrientation == null) {
  32388. sideOrientation = this._effectiveMaterial.sideOrientation;
  32389. if (this._getWorldMatrixDeterminant() < 0) {
  32390. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32391. }
  32392. }
  32393. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32394. if (this._effectiveMaterial.forceDepthWrite) {
  32395. engine.setDepthWrite(true);
  32396. }
  32397. // Bind
  32398. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32399. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32400. this._bind(subMesh, effect, fillMode);
  32401. }
  32402. var world = this.getWorldMatrix();
  32403. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32404. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32405. }
  32406. else {
  32407. this._effectiveMaterial.bind(world, this);
  32408. }
  32409. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32410. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32411. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32412. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32413. }
  32414. // Draw
  32415. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32416. // Unbind
  32417. this._effectiveMaterial.unbind();
  32418. // Outline - step 2
  32419. if (this.renderOutline && savedDepthWrite) {
  32420. engine.setDepthWrite(true);
  32421. engine.setColorWrite(false);
  32422. scene.getOutlineRenderer().render(subMesh, batch);
  32423. engine.setColorWrite(true);
  32424. }
  32425. // Overlay
  32426. if (this.renderOverlay) {
  32427. var currentMode = engine.getAlphaMode();
  32428. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32429. scene.getOutlineRenderer().render(subMesh, batch, true);
  32430. engine.setAlphaMode(currentMode);
  32431. }
  32432. if (this._onAfterRenderObservable) {
  32433. this._onAfterRenderObservable.notifyObservers(this);
  32434. }
  32435. return this;
  32436. };
  32437. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32438. if (isInstance && effectiveMaterial) {
  32439. effectiveMaterial.bindOnlyWorldMatrix(world);
  32440. }
  32441. };
  32442. /**
  32443. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32444. */
  32445. Mesh.prototype.getEmittedParticleSystems = function () {
  32446. var results = new Array();
  32447. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32448. var particleSystem = this.getScene().particleSystems[index];
  32449. if (particleSystem.emitter === this) {
  32450. results.push(particleSystem);
  32451. }
  32452. }
  32453. return results;
  32454. };
  32455. /**
  32456. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32457. */
  32458. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32459. var results = new Array();
  32460. var descendants = this.getDescendants();
  32461. descendants.push(this);
  32462. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32463. var particleSystem = this.getScene().particleSystems[index];
  32464. var emitter = particleSystem.emitter;
  32465. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32466. results.push(particleSystem);
  32467. }
  32468. }
  32469. return results;
  32470. };
  32471. /**
  32472. * Normalize matrix weights so that all vertices have a total weight set to 1
  32473. */
  32474. Mesh.prototype.cleanMatrixWeights = function () {
  32475. var epsilon = 1e-3;
  32476. var noInfluenceBoneIndex = 0.0;
  32477. if (this.skeleton) {
  32478. noInfluenceBoneIndex = this.skeleton.bones.length;
  32479. }
  32480. else {
  32481. return;
  32482. }
  32483. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32484. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32485. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32486. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32487. var influencers = this.numBoneInfluencers;
  32488. var size = matricesWeights.length;
  32489. for (var i = 0; i < size; i += 4) {
  32490. var weight = 0.0;
  32491. var firstZeroWeight = -1;
  32492. for (var j = 0; j < 4; j++) {
  32493. var w = matricesWeights[i + j];
  32494. weight += w;
  32495. if (w < epsilon && firstZeroWeight < 0) {
  32496. firstZeroWeight = j;
  32497. }
  32498. }
  32499. if (matricesWeightsExtra) {
  32500. for (var j = 0; j < 4; j++) {
  32501. var w = matricesWeightsExtra[i + j];
  32502. weight += w;
  32503. if (w < epsilon && firstZeroWeight < 0) {
  32504. firstZeroWeight = j + 4;
  32505. }
  32506. }
  32507. }
  32508. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32509. firstZeroWeight = influencers - 1;
  32510. }
  32511. if (weight > epsilon) {
  32512. var mweight = 1.0 / weight;
  32513. for (var j = 0; j < 4; j++) {
  32514. matricesWeights[i + j] *= mweight;
  32515. }
  32516. if (matricesWeightsExtra) {
  32517. for (var j = 0; j < 4; j++) {
  32518. matricesWeightsExtra[i + j] *= mweight;
  32519. }
  32520. }
  32521. }
  32522. else {
  32523. if (firstZeroWeight >= 4) {
  32524. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32525. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32526. }
  32527. else {
  32528. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32529. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32530. }
  32531. }
  32532. }
  32533. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32534. if (matricesIndicesExtra) {
  32535. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32536. }
  32537. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32538. if (matricesWeightsExtra) {
  32539. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32540. }
  32541. };
  32542. /** @hidden */
  32543. Mesh.prototype._checkDelayState = function () {
  32544. var scene = this.getScene();
  32545. if (this._geometry) {
  32546. this._geometry.load(scene);
  32547. }
  32548. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32549. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32550. this._queueLoad(scene);
  32551. }
  32552. return this;
  32553. };
  32554. Mesh.prototype._queueLoad = function (scene) {
  32555. var _this = this;
  32556. scene._addPendingData(this);
  32557. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32558. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32559. if (data instanceof ArrayBuffer) {
  32560. _this._delayLoadingFunction(data, _this);
  32561. }
  32562. else {
  32563. _this._delayLoadingFunction(JSON.parse(data), _this);
  32564. }
  32565. _this.instances.forEach(function (instance) {
  32566. instance._syncSubMeshes();
  32567. });
  32568. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32569. scene._removePendingData(_this);
  32570. }, function () { }, scene.database, getBinaryData);
  32571. return this;
  32572. };
  32573. /**
  32574. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32575. * A mesh is in the frustum if its bounding box intersects the frustum
  32576. * @param frustumPlanes defines the frustum to test
  32577. * @returns true if the mesh is in the frustum planes
  32578. */
  32579. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32580. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32581. return false;
  32582. }
  32583. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32584. return false;
  32585. }
  32586. this._checkDelayState();
  32587. return true;
  32588. };
  32589. /**
  32590. * Sets the mesh material by the material or multiMaterial `id` property.
  32591. * The material `id` is a string identifying the material or the multiMaterial.
  32592. * This method returns the Mesh.
  32593. */
  32594. Mesh.prototype.setMaterialByID = function (id) {
  32595. var materials = this.getScene().materials;
  32596. var index;
  32597. for (index = materials.length - 1; index > -1; index--) {
  32598. if (materials[index].id === id) {
  32599. this.material = materials[index];
  32600. return this;
  32601. }
  32602. }
  32603. // Multi
  32604. var multiMaterials = this.getScene().multiMaterials;
  32605. for (index = multiMaterials.length - 1; index > -1; index--) {
  32606. if (multiMaterials[index].id === id) {
  32607. this.material = multiMaterials[index];
  32608. return this;
  32609. }
  32610. }
  32611. return this;
  32612. };
  32613. /**
  32614. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32615. */
  32616. Mesh.prototype.getAnimatables = function () {
  32617. var results = new Array();
  32618. if (this.material) {
  32619. results.push(this.material);
  32620. }
  32621. if (this.skeleton) {
  32622. results.push(this.skeleton);
  32623. }
  32624. return results;
  32625. };
  32626. /**
  32627. * Modifies the mesh geometry according to the passed transformation matrix.
  32628. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32629. * The mesh normals are modified using the same transformation.
  32630. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32631. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32632. * Returns the Mesh.
  32633. */
  32634. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32635. // Position
  32636. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32637. return this;
  32638. }
  32639. var submeshes = this.subMeshes.splice(0);
  32640. this._resetPointsArrayCache();
  32641. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32642. var temp = new Array();
  32643. var index;
  32644. for (index = 0; index < data.length; index += 3) {
  32645. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32646. }
  32647. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32648. // Normals
  32649. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32650. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32651. temp = [];
  32652. for (index = 0; index < data.length; index += 3) {
  32653. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32654. }
  32655. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32656. }
  32657. // flip faces?
  32658. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32659. this.flipFaces();
  32660. }
  32661. // Restore submeshes
  32662. this.releaseSubMeshes();
  32663. this.subMeshes = submeshes;
  32664. return this;
  32665. };
  32666. /**
  32667. * Modifies the mesh geometry according to its own current World Matrix.
  32668. * The mesh World Matrix is then reset.
  32669. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32670. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32671. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32672. * Returns the Mesh.
  32673. */
  32674. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32675. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32676. this.scaling.copyFromFloats(1, 1, 1);
  32677. this.position.copyFromFloats(0, 0, 0);
  32678. this.rotation.copyFromFloats(0, 0, 0);
  32679. //only if quaternion is already set
  32680. if (this.rotationQuaternion) {
  32681. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32682. }
  32683. this._worldMatrix = BABYLON.Matrix.Identity();
  32684. return this;
  32685. };
  32686. Object.defineProperty(Mesh.prototype, "_positions", {
  32687. // Cache
  32688. get: function () {
  32689. if (this._geometry) {
  32690. return this._geometry._positions;
  32691. }
  32692. return null;
  32693. },
  32694. enumerable: true,
  32695. configurable: true
  32696. });
  32697. /** @hidden */
  32698. Mesh.prototype._resetPointsArrayCache = function () {
  32699. if (this._geometry) {
  32700. this._geometry._resetPointsArrayCache();
  32701. }
  32702. return this;
  32703. };
  32704. /** @hidden */
  32705. Mesh.prototype._generatePointsArray = function () {
  32706. if (this._geometry) {
  32707. return this._geometry._generatePointsArray();
  32708. }
  32709. return false;
  32710. };
  32711. /**
  32712. * Returns a new Mesh object generated from the current mesh properties.
  32713. * This method must not get confused with createInstance().
  32714. * The parameter `name` is a string, the name given to the new mesh.
  32715. * The optional parameter `newParent` can be any Node object (default `null`).
  32716. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32717. * 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.
  32718. */
  32719. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32720. if (name === void 0) { name = ""; }
  32721. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32722. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32723. };
  32724. /**
  32725. * Releases resources associated with this mesh.
  32726. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32727. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32728. */
  32729. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32730. var _this = this;
  32731. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32732. this.morphTargetManager = null;
  32733. if (this._geometry) {
  32734. this._geometry.releaseForMesh(this, true);
  32735. }
  32736. if (this._onBeforeDrawObservable) {
  32737. this._onBeforeDrawObservable.clear();
  32738. }
  32739. if (this._onBeforeRenderObservable) {
  32740. this._onBeforeRenderObservable.clear();
  32741. }
  32742. if (this._onAfterRenderObservable) {
  32743. this._onAfterRenderObservable.clear();
  32744. }
  32745. // Sources
  32746. var meshes = this.getScene().meshes;
  32747. meshes.forEach(function (abstractMesh) {
  32748. var mesh = abstractMesh;
  32749. if (mesh._source && mesh._source === _this) {
  32750. mesh._source = null;
  32751. }
  32752. });
  32753. this._source = null;
  32754. // Instances
  32755. if (this._instancesBuffer) {
  32756. this._instancesBuffer.dispose();
  32757. this._instancesBuffer = null;
  32758. }
  32759. while (this.instances.length) {
  32760. this.instances[0].dispose();
  32761. }
  32762. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32763. };
  32764. /**
  32765. * Modifies the mesh geometry according to a displacement map.
  32766. * 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.
  32767. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32768. * This method returns nothing.
  32769. * @param url is a string, the URL from the image file is to be downloaded.
  32770. * @param minHeight is the lower limit of the displacement.
  32771. * @param maxHeight is the upper limit of the displacement.
  32772. * @param 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.
  32773. * @param uvOffset is an optional vector2 used to offset UV.
  32774. * @param uvScale is an optional vector2 used to scale UV.
  32775. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32776. * @returns the Mesh.
  32777. */
  32778. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32779. var _this = this;
  32780. if (forceUpdate === void 0) { forceUpdate = false; }
  32781. var scene = this.getScene();
  32782. var onload = function (img) {
  32783. // Getting height map data
  32784. var canvas = document.createElement("canvas");
  32785. var context = canvas.getContext("2d");
  32786. var heightMapWidth = img.width;
  32787. var heightMapHeight = img.height;
  32788. canvas.width = heightMapWidth;
  32789. canvas.height = heightMapHeight;
  32790. context.drawImage(img, 0, 0);
  32791. // Create VertexData from map data
  32792. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32793. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32794. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32795. //execute success callback, if set
  32796. if (onSuccess) {
  32797. onSuccess(_this);
  32798. }
  32799. };
  32800. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32801. return this;
  32802. };
  32803. /**
  32804. * Modifies the mesh geometry according to a displacementMap buffer.
  32805. * 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.
  32806. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32807. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32808. * @param heightMapWidth is the width of the buffer image.
  32809. * @param heightMapHeight is the height of the buffer image.
  32810. * @param minHeight is the lower limit of the displacement.
  32811. * @param maxHeight is the upper limit of the displacement.
  32812. * @param 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.
  32813. * @param uvOffset is an optional vector2 used to offset UV.
  32814. * @param uvScale is an optional vector2 used to scale UV.
  32815. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32816. * @returns the Mesh.
  32817. */
  32818. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32819. if (forceUpdate === void 0) { forceUpdate = false; }
  32820. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32821. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32822. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32823. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32824. return this;
  32825. }
  32826. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32827. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32828. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32829. var position = BABYLON.Vector3.Zero();
  32830. var normal = BABYLON.Vector3.Zero();
  32831. var uv = BABYLON.Vector2.Zero();
  32832. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32833. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32834. for (var index = 0; index < positions.length; index += 3) {
  32835. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32836. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32837. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32838. // Compute height
  32839. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32840. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32841. var pos = (u + v * heightMapWidth) * 4;
  32842. var r = buffer[pos] / 255.0;
  32843. var g = buffer[pos + 1] / 255.0;
  32844. var b = buffer[pos + 2] / 255.0;
  32845. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32846. normal.normalize();
  32847. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32848. position = position.add(normal);
  32849. position.toArray(positions, index);
  32850. }
  32851. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32852. if (forceUpdate) {
  32853. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32854. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32855. }
  32856. else {
  32857. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32858. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32859. }
  32860. return this;
  32861. };
  32862. /**
  32863. * Modify the mesh to get a flat shading rendering.
  32864. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32865. * This method returns the Mesh.
  32866. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32867. */
  32868. Mesh.prototype.convertToFlatShadedMesh = function () {
  32869. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32870. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32871. var kinds = this.getVerticesDataKinds();
  32872. var vbs = {};
  32873. var data = {};
  32874. var newdata = {};
  32875. var updatableNormals = false;
  32876. var kindIndex;
  32877. var kind;
  32878. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32879. kind = kinds[kindIndex];
  32880. var vertexBuffer = this.getVertexBuffer(kind);
  32881. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32882. updatableNormals = vertexBuffer.isUpdatable();
  32883. kinds.splice(kindIndex, 1);
  32884. kindIndex--;
  32885. continue;
  32886. }
  32887. vbs[kind] = vertexBuffer;
  32888. data[kind] = vbs[kind].getData();
  32889. newdata[kind] = [];
  32890. }
  32891. // Save previous submeshes
  32892. var previousSubmeshes = this.subMeshes.slice(0);
  32893. var indices = this.getIndices();
  32894. var totalIndices = this.getTotalIndices();
  32895. // Generating unique vertices per face
  32896. var index;
  32897. for (index = 0; index < totalIndices; index++) {
  32898. var vertexIndex = indices[index];
  32899. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32900. kind = kinds[kindIndex];
  32901. var stride = vbs[kind].getStrideSize();
  32902. for (var offset = 0; offset < stride; offset++) {
  32903. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32904. }
  32905. }
  32906. }
  32907. // Updating faces & normal
  32908. var normals = [];
  32909. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32910. for (index = 0; index < totalIndices; index += 3) {
  32911. indices[index] = index;
  32912. indices[index + 1] = index + 1;
  32913. indices[index + 2] = index + 2;
  32914. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32915. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32916. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32917. var p1p2 = p1.subtract(p2);
  32918. var p3p2 = p3.subtract(p2);
  32919. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32920. // Store same normals for every vertex
  32921. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32922. normals.push(normal.x);
  32923. normals.push(normal.y);
  32924. normals.push(normal.z);
  32925. }
  32926. }
  32927. this.setIndices(indices);
  32928. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32929. // Updating vertex buffers
  32930. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32931. kind = kinds[kindIndex];
  32932. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32933. }
  32934. // Updating submeshes
  32935. this.releaseSubMeshes();
  32936. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32937. var previousOne = previousSubmeshes[submeshIndex];
  32938. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32939. }
  32940. this.synchronizeInstances();
  32941. return this;
  32942. };
  32943. /**
  32944. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32945. * In other words, more vertices, no more indices and a single bigger VBO.
  32946. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32947. * Returns the Mesh.
  32948. */
  32949. Mesh.prototype.convertToUnIndexedMesh = function () {
  32950. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32951. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32952. var kinds = this.getVerticesDataKinds();
  32953. var vbs = {};
  32954. var data = {};
  32955. var newdata = {};
  32956. var kindIndex;
  32957. var kind;
  32958. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32959. kind = kinds[kindIndex];
  32960. var vertexBuffer = this.getVertexBuffer(kind);
  32961. vbs[kind] = vertexBuffer;
  32962. data[kind] = vbs[kind].getData();
  32963. newdata[kind] = [];
  32964. }
  32965. // Save previous submeshes
  32966. var previousSubmeshes = this.subMeshes.slice(0);
  32967. var indices = this.getIndices();
  32968. var totalIndices = this.getTotalIndices();
  32969. // Generating unique vertices per face
  32970. var index;
  32971. for (index = 0; index < totalIndices; index++) {
  32972. var vertexIndex = indices[index];
  32973. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32974. kind = kinds[kindIndex];
  32975. var stride = vbs[kind].getStrideSize();
  32976. for (var offset = 0; offset < stride; offset++) {
  32977. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32978. }
  32979. }
  32980. }
  32981. // Updating indices
  32982. for (index = 0; index < totalIndices; index += 3) {
  32983. indices[index] = index;
  32984. indices[index + 1] = index + 1;
  32985. indices[index + 2] = index + 2;
  32986. }
  32987. this.setIndices(indices);
  32988. // Updating vertex buffers
  32989. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32990. kind = kinds[kindIndex];
  32991. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32992. }
  32993. // Updating submeshes
  32994. this.releaseSubMeshes();
  32995. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32996. var previousOne = previousSubmeshes[submeshIndex];
  32997. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32998. }
  32999. this._unIndexed = true;
  33000. this.synchronizeInstances();
  33001. return this;
  33002. };
  33003. /**
  33004. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33005. * This method returns the Mesh.
  33006. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33007. */
  33008. Mesh.prototype.flipFaces = function (flipNormals) {
  33009. if (flipNormals === void 0) { flipNormals = false; }
  33010. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33011. var i;
  33012. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33013. for (i = 0; i < vertex_data.normals.length; i++) {
  33014. vertex_data.normals[i] *= -1;
  33015. }
  33016. }
  33017. if (vertex_data.indices) {
  33018. var temp;
  33019. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33020. // reassign indices
  33021. temp = vertex_data.indices[i + 1];
  33022. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33023. vertex_data.indices[i + 2] = temp;
  33024. }
  33025. }
  33026. vertex_data.applyToMesh(this);
  33027. return this;
  33028. };
  33029. // Instances
  33030. /**
  33031. * Creates a new InstancedMesh object from the mesh model.
  33032. * An instance shares the same properties and the same material than its model.
  33033. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  33034. * Only these properties of each instance can then be set individually :
  33035. * - position
  33036. * - rotation
  33037. * - rotationQuaternion
  33038. * - setPivotMatrix
  33039. * - scaling
  33040. *
  33041. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33042. * Warning : this method is not supported for Line mesh and LineSystem
  33043. */
  33044. Mesh.prototype.createInstance = function (name) {
  33045. return new BABYLON.InstancedMesh(name, this);
  33046. };
  33047. /**
  33048. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33049. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33050. * This method returns the Mesh.
  33051. */
  33052. Mesh.prototype.synchronizeInstances = function () {
  33053. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33054. var instance = this.instances[instanceIndex];
  33055. instance._syncSubMeshes();
  33056. }
  33057. return this;
  33058. };
  33059. /**
  33060. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33061. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33062. * This should be used together with the simplification to avoid disappearing triangles.
  33063. * Returns the Mesh.
  33064. * @param successCallback an optional success callback to be called after the optimization finished.
  33065. */
  33066. Mesh.prototype.optimizeIndices = function (successCallback) {
  33067. var _this = this;
  33068. var indices = this.getIndices();
  33069. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33070. if (!positions || !indices) {
  33071. return this;
  33072. }
  33073. var vectorPositions = new Array();
  33074. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33075. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33076. }
  33077. var dupes = new Array();
  33078. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33079. var realPos = vectorPositions.length - 1 - iteration;
  33080. var testedPosition = vectorPositions[realPos];
  33081. for (var j = 0; j < realPos; ++j) {
  33082. var againstPosition = vectorPositions[j];
  33083. if (testedPosition.equals(againstPosition)) {
  33084. dupes[realPos] = j;
  33085. break;
  33086. }
  33087. }
  33088. }, function () {
  33089. for (var i = 0; i < indices.length; ++i) {
  33090. indices[i] = dupes[indices[i]] || indices[i];
  33091. }
  33092. //indices are now reordered
  33093. var originalSubMeshes = _this.subMeshes.slice(0);
  33094. _this.setIndices(indices);
  33095. _this.subMeshes = originalSubMeshes;
  33096. if (successCallback) {
  33097. successCallback(_this);
  33098. }
  33099. });
  33100. return this;
  33101. };
  33102. Mesh.prototype.serialize = function (serializationObject) {
  33103. serializationObject.name = this.name;
  33104. serializationObject.id = this.id;
  33105. serializationObject.type = this.getClassName();
  33106. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33107. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33108. }
  33109. serializationObject.position = this.position.asArray();
  33110. if (this.rotationQuaternion) {
  33111. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33112. }
  33113. else if (this.rotation) {
  33114. serializationObject.rotation = this.rotation.asArray();
  33115. }
  33116. serializationObject.scaling = this.scaling.asArray();
  33117. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33118. serializationObject.isEnabled = this.isEnabled(false);
  33119. serializationObject.isVisible = this.isVisible;
  33120. serializationObject.infiniteDistance = this.infiniteDistance;
  33121. serializationObject.pickable = this.isPickable;
  33122. serializationObject.receiveShadows = this.receiveShadows;
  33123. serializationObject.billboardMode = this.billboardMode;
  33124. serializationObject.visibility = this.visibility;
  33125. serializationObject.checkCollisions = this.checkCollisions;
  33126. serializationObject.isBlocker = this.isBlocker;
  33127. // Parent
  33128. if (this.parent) {
  33129. serializationObject.parentId = this.parent.id;
  33130. }
  33131. // Geometry
  33132. serializationObject.isUnIndexed = this.isUnIndexed;
  33133. var geometry = this._geometry;
  33134. if (geometry) {
  33135. var geometryId = geometry.id;
  33136. serializationObject.geometryId = geometryId;
  33137. // SubMeshes
  33138. serializationObject.subMeshes = [];
  33139. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33140. var subMesh = this.subMeshes[subIndex];
  33141. serializationObject.subMeshes.push({
  33142. materialIndex: subMesh.materialIndex,
  33143. verticesStart: subMesh.verticesStart,
  33144. verticesCount: subMesh.verticesCount,
  33145. indexStart: subMesh.indexStart,
  33146. indexCount: subMesh.indexCount
  33147. });
  33148. }
  33149. }
  33150. // Material
  33151. if (this.material) {
  33152. serializationObject.materialId = this.material.id;
  33153. }
  33154. else {
  33155. this.material = null;
  33156. }
  33157. // Morph targets
  33158. if (this.morphTargetManager) {
  33159. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33160. }
  33161. // Skeleton
  33162. if (this.skeleton) {
  33163. serializationObject.skeletonId = this.skeleton.id;
  33164. }
  33165. // Physics
  33166. //TODO implement correct serialization for physics impostors.
  33167. var impostor = this.getPhysicsImpostor();
  33168. if (impostor) {
  33169. serializationObject.physicsMass = impostor.getParam("mass");
  33170. serializationObject.physicsFriction = impostor.getParam("friction");
  33171. serializationObject.physicsRestitution = impostor.getParam("mass");
  33172. serializationObject.physicsImpostor = impostor.type;
  33173. }
  33174. // Metadata
  33175. if (this.metadata) {
  33176. serializationObject.metadata = this.metadata;
  33177. }
  33178. // Instances
  33179. serializationObject.instances = [];
  33180. for (var index = 0; index < this.instances.length; index++) {
  33181. var instance = this.instances[index];
  33182. if (instance.doNotSerialize) {
  33183. continue;
  33184. }
  33185. var serializationInstance = {
  33186. name: instance.name,
  33187. id: instance.id,
  33188. position: instance.position.asArray(),
  33189. scaling: instance.scaling.asArray()
  33190. };
  33191. if (instance.parent) {
  33192. serializationInstance.parentId = instance.parent.id;
  33193. }
  33194. if (instance.rotationQuaternion) {
  33195. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33196. }
  33197. else if (instance.rotation) {
  33198. serializationInstance.rotation = instance.rotation.asArray();
  33199. }
  33200. serializationObject.instances.push(serializationInstance);
  33201. // Animations
  33202. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33203. serializationInstance.ranges = instance.serializeAnimationRanges();
  33204. }
  33205. //
  33206. // Animations
  33207. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33208. serializationObject.ranges = this.serializeAnimationRanges();
  33209. // Layer mask
  33210. serializationObject.layerMask = this.layerMask;
  33211. // Alpha
  33212. serializationObject.alphaIndex = this.alphaIndex;
  33213. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33214. // Overlay
  33215. serializationObject.overlayAlpha = this.overlayAlpha;
  33216. serializationObject.overlayColor = this.overlayColor.asArray();
  33217. serializationObject.renderOverlay = this.renderOverlay;
  33218. // Fog
  33219. serializationObject.applyFog = this.applyFog;
  33220. // Action Manager
  33221. if (this.actionManager) {
  33222. serializationObject.actions = this.actionManager.serialize(this.name);
  33223. }
  33224. };
  33225. /** @hidden */
  33226. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33227. if (!this.geometry) {
  33228. return;
  33229. }
  33230. this._markSubMeshesAsAttributesDirty();
  33231. var morphTargetManager = this._morphTargetManager;
  33232. if (morphTargetManager && morphTargetManager.vertexCount) {
  33233. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33234. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33235. this.morphTargetManager = null;
  33236. return;
  33237. }
  33238. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33239. var morphTarget = morphTargetManager.getActiveTarget(index);
  33240. var positions = morphTarget.getPositions();
  33241. if (!positions) {
  33242. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33243. return;
  33244. }
  33245. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33246. var normals = morphTarget.getNormals();
  33247. if (normals) {
  33248. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33249. }
  33250. var tangents = morphTarget.getTangents();
  33251. if (tangents) {
  33252. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33253. }
  33254. }
  33255. }
  33256. else {
  33257. var index = 0;
  33258. // Positions
  33259. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33260. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33261. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33262. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33263. }
  33264. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33265. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33266. }
  33267. index++;
  33268. }
  33269. }
  33270. };
  33271. // Statics
  33272. /**
  33273. * Returns a new Mesh object parsed from the source provided.
  33274. * The parameter `parsedMesh` is the source.
  33275. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33276. */
  33277. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33278. var mesh;
  33279. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33280. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33281. }
  33282. else {
  33283. mesh = new Mesh(parsedMesh.name, scene);
  33284. }
  33285. mesh.id = parsedMesh.id;
  33286. if (BABYLON.Tags) {
  33287. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33288. }
  33289. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33290. if (parsedMesh.metadata !== undefined) {
  33291. mesh.metadata = parsedMesh.metadata;
  33292. }
  33293. if (parsedMesh.rotationQuaternion) {
  33294. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33295. }
  33296. else if (parsedMesh.rotation) {
  33297. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33298. }
  33299. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33300. if (parsedMesh.localMatrix) {
  33301. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33302. }
  33303. else if (parsedMesh.pivotMatrix) {
  33304. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33305. }
  33306. mesh.setEnabled(parsedMesh.isEnabled);
  33307. mesh.isVisible = parsedMesh.isVisible;
  33308. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33309. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33310. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33311. if (parsedMesh.applyFog !== undefined) {
  33312. mesh.applyFog = parsedMesh.applyFog;
  33313. }
  33314. if (parsedMesh.pickable !== undefined) {
  33315. mesh.isPickable = parsedMesh.pickable;
  33316. }
  33317. if (parsedMesh.alphaIndex !== undefined) {
  33318. mesh.alphaIndex = parsedMesh.alphaIndex;
  33319. }
  33320. mesh.receiveShadows = parsedMesh.receiveShadows;
  33321. mesh.billboardMode = parsedMesh.billboardMode;
  33322. if (parsedMesh.visibility !== undefined) {
  33323. mesh.visibility = parsedMesh.visibility;
  33324. }
  33325. mesh.checkCollisions = parsedMesh.checkCollisions;
  33326. if (parsedMesh.isBlocker !== undefined) {
  33327. mesh.isBlocker = parsedMesh.isBlocker;
  33328. }
  33329. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33330. // freezeWorldMatrix
  33331. if (parsedMesh.freezeWorldMatrix) {
  33332. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33333. }
  33334. // Parent
  33335. if (parsedMesh.parentId) {
  33336. mesh._waitingParentId = parsedMesh.parentId;
  33337. }
  33338. // Actions
  33339. if (parsedMesh.actions !== undefined) {
  33340. mesh._waitingActions = parsedMesh.actions;
  33341. }
  33342. // Overlay
  33343. if (parsedMesh.overlayAlpha !== undefined) {
  33344. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33345. }
  33346. if (parsedMesh.overlayColor !== undefined) {
  33347. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33348. }
  33349. if (parsedMesh.renderOverlay !== undefined) {
  33350. mesh.renderOverlay = parsedMesh.renderOverlay;
  33351. }
  33352. // Geometry
  33353. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33354. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33355. if (parsedMesh.delayLoadingFile) {
  33356. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33357. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33358. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33359. if (parsedMesh._binaryInfo) {
  33360. mesh._binaryInfo = parsedMesh._binaryInfo;
  33361. }
  33362. mesh._delayInfo = [];
  33363. if (parsedMesh.hasUVs) {
  33364. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33365. }
  33366. if (parsedMesh.hasUVs2) {
  33367. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33368. }
  33369. if (parsedMesh.hasUVs3) {
  33370. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33371. }
  33372. if (parsedMesh.hasUVs4) {
  33373. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33374. }
  33375. if (parsedMesh.hasUVs5) {
  33376. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33377. }
  33378. if (parsedMesh.hasUVs6) {
  33379. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33380. }
  33381. if (parsedMesh.hasColors) {
  33382. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33383. }
  33384. if (parsedMesh.hasMatricesIndices) {
  33385. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33386. }
  33387. if (parsedMesh.hasMatricesWeights) {
  33388. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33389. }
  33390. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33391. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33392. mesh._checkDelayState();
  33393. }
  33394. }
  33395. else {
  33396. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33397. }
  33398. // Material
  33399. if (parsedMesh.materialId) {
  33400. mesh.setMaterialByID(parsedMesh.materialId);
  33401. }
  33402. else {
  33403. mesh.material = null;
  33404. }
  33405. // Morph targets
  33406. if (parsedMesh.morphTargetManagerId > -1) {
  33407. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33408. }
  33409. // Skeleton
  33410. if (parsedMesh.skeletonId > -1) {
  33411. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33412. if (parsedMesh.numBoneInfluencers) {
  33413. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33414. }
  33415. }
  33416. // Animations
  33417. if (parsedMesh.animations) {
  33418. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33419. var parsedAnimation = parsedMesh.animations[animationIndex];
  33420. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33421. }
  33422. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33423. }
  33424. if (parsedMesh.autoAnimate) {
  33425. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33426. }
  33427. // Layer Mask
  33428. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33429. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33430. }
  33431. else {
  33432. mesh.layerMask = 0x0FFFFFFF;
  33433. }
  33434. // Physics
  33435. if (parsedMesh.physicsImpostor) {
  33436. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33437. mass: parsedMesh.physicsMass,
  33438. friction: parsedMesh.physicsFriction,
  33439. restitution: parsedMesh.physicsRestitution
  33440. }, scene);
  33441. }
  33442. // Instances
  33443. if (parsedMesh.instances) {
  33444. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33445. var parsedInstance = parsedMesh.instances[index];
  33446. var instance = mesh.createInstance(parsedInstance.name);
  33447. if (parsedInstance.id) {
  33448. instance.id = parsedInstance.id;
  33449. }
  33450. if (BABYLON.Tags) {
  33451. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33452. }
  33453. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33454. if (parsedInstance.parentId) {
  33455. instance._waitingParentId = parsedInstance.parentId;
  33456. }
  33457. if (parsedInstance.rotationQuaternion) {
  33458. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33459. }
  33460. else if (parsedInstance.rotation) {
  33461. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33462. }
  33463. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33464. instance.checkCollisions = mesh.checkCollisions;
  33465. if (parsedMesh.animations) {
  33466. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33467. parsedAnimation = parsedMesh.animations[animationIndex];
  33468. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33469. }
  33470. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33471. if (parsedMesh.autoAnimate) {
  33472. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33473. }
  33474. }
  33475. }
  33476. }
  33477. return mesh;
  33478. };
  33479. /**
  33480. * Creates a ribbon mesh.
  33481. * Please consider using the same method from the MeshBuilder class instead.
  33482. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33483. *
  33484. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33485. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33486. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33487. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33488. * 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.
  33489. * 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.
  33490. * 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
  33491. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33492. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33494. */
  33495. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33496. if (closeArray === void 0) { closeArray = false; }
  33497. if (updatable === void 0) { updatable = false; }
  33498. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33499. pathArray: pathArray,
  33500. closeArray: closeArray,
  33501. closePath: closePath,
  33502. offset: offset,
  33503. updatable: updatable,
  33504. sideOrientation: sideOrientation,
  33505. instance: instance
  33506. }, scene);
  33507. };
  33508. /**
  33509. * Creates a plane polygonal mesh. By default, this is a disc.
  33510. * Please consider using the same method from the MeshBuilder class instead.
  33511. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33512. * 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.
  33513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33514. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33516. */
  33517. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33518. if (scene === void 0) { scene = null; }
  33519. var options = {
  33520. radius: radius,
  33521. tessellation: tessellation,
  33522. sideOrientation: sideOrientation,
  33523. updatable: updatable
  33524. };
  33525. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33526. };
  33527. /**
  33528. * Creates a box mesh.
  33529. * Please consider using the same method from the MeshBuilder class instead.
  33530. * The parameter `size` sets the size (float) of each box side (default 1).
  33531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33532. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33534. */
  33535. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33536. if (scene === void 0) { scene = null; }
  33537. var options = {
  33538. size: size,
  33539. sideOrientation: sideOrientation,
  33540. updatable: updatable
  33541. };
  33542. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33543. };
  33544. /**
  33545. * Creates a sphere mesh.
  33546. * Please consider using the same method from the MeshBuilder class instead.
  33547. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33548. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33550. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33552. */
  33553. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33554. var options = {
  33555. segments: segments,
  33556. diameterX: diameter,
  33557. diameterY: diameter,
  33558. diameterZ: diameter,
  33559. sideOrientation: sideOrientation,
  33560. updatable: updatable
  33561. };
  33562. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33563. };
  33564. /**
  33565. * Creates a cylinder or a cone mesh.
  33566. * Please consider using the same method from the MeshBuilder class instead.
  33567. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33568. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33569. * 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.
  33570. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33571. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33573. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33575. */
  33576. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33577. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33578. if (scene !== undefined) {
  33579. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33580. updatable = scene;
  33581. }
  33582. scene = subdivisions;
  33583. subdivisions = 1;
  33584. }
  33585. var options = {
  33586. height: height,
  33587. diameterTop: diameterTop,
  33588. diameterBottom: diameterBottom,
  33589. tessellation: tessellation,
  33590. subdivisions: subdivisions,
  33591. sideOrientation: sideOrientation,
  33592. updatable: updatable
  33593. };
  33594. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33595. };
  33596. // Torus (Code from SharpDX.org)
  33597. /**
  33598. * Creates a torus mesh.
  33599. * Please consider using the same method from the MeshBuilder class instead.
  33600. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33601. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33602. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33604. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33606. */
  33607. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33608. var options = {
  33609. diameter: diameter,
  33610. thickness: thickness,
  33611. tessellation: tessellation,
  33612. sideOrientation: sideOrientation,
  33613. updatable: updatable
  33614. };
  33615. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33616. };
  33617. /**
  33618. * Creates a torus knot mesh.
  33619. * Please consider using the same method from the MeshBuilder class instead.
  33620. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33621. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33622. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33623. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33625. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33627. */
  33628. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33629. var options = {
  33630. radius: radius,
  33631. tube: tube,
  33632. radialSegments: radialSegments,
  33633. tubularSegments: tubularSegments,
  33634. p: p,
  33635. q: q,
  33636. sideOrientation: sideOrientation,
  33637. updatable: updatable
  33638. };
  33639. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33640. };
  33641. /**
  33642. * Creates a line mesh.
  33643. * Please consider using the same method from the MeshBuilder class instead.
  33644. * 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.
  33645. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33646. * The parameter `points` is an array successive Vector3.
  33647. * 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
  33648. * When updating an instance, remember that only point positions can change, not the number of points.
  33649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33650. */
  33651. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33652. if (scene === void 0) { scene = null; }
  33653. if (updatable === void 0) { updatable = false; }
  33654. if (instance === void 0) { instance = null; }
  33655. var options = {
  33656. points: points,
  33657. updatable: updatable,
  33658. instance: instance
  33659. };
  33660. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33661. };
  33662. /**
  33663. * Creates a dashed line mesh.
  33664. * Please consider using the same method from the MeshBuilder class instead.
  33665. * 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.
  33666. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33667. * The parameter `points` is an array successive Vector3.
  33668. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33669. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33670. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33671. * 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
  33672. * When updating an instance, remember that only point positions can change, not the number of points.
  33673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33674. */
  33675. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33676. if (scene === void 0) { scene = null; }
  33677. var options = {
  33678. points: points,
  33679. dashSize: dashSize,
  33680. gapSize: gapSize,
  33681. dashNb: dashNb,
  33682. updatable: updatable,
  33683. instance: instance
  33684. };
  33685. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33686. };
  33687. /**
  33688. * Creates a polygon mesh.
  33689. * Please consider using the same method from the MeshBuilder class instead.
  33690. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33691. * 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.
  33692. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33694. * Remember you can only change the shape positions, not their number when updating a polygon.
  33695. */
  33696. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33697. var options = {
  33698. shape: shape,
  33699. holes: holes,
  33700. updatable: updatable,
  33701. sideOrientation: sideOrientation
  33702. };
  33703. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33704. };
  33705. /**
  33706. * Creates an extruded polygon mesh, with depth in the Y direction.
  33707. * Please consider using the same method from the MeshBuilder class instead.
  33708. */
  33709. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33710. var options = {
  33711. shape: shape,
  33712. holes: holes,
  33713. depth: depth,
  33714. updatable: updatable,
  33715. sideOrientation: sideOrientation
  33716. };
  33717. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33718. };
  33719. /**
  33720. * Creates an extruded shape mesh.
  33721. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33722. * Please consider using the same method from the MeshBuilder class instead.
  33723. *
  33724. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33725. * 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
  33726. * extruded along the Z axis.
  33727. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33728. * 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.
  33729. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33730. * 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
  33731. * 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
  33732. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  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.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33738. if (scene === void 0) { scene = null; }
  33739. var options = {
  33740. shape: shape,
  33741. path: path,
  33742. scale: scale,
  33743. rotation: rotation,
  33744. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33745. sideOrientation: sideOrientation,
  33746. instance: instance,
  33747. updatable: updatable
  33748. };
  33749. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33750. };
  33751. /**
  33752. * Creates an custom extruded shape mesh.
  33753. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33754. * Please consider using the same method from the MeshBuilder class instead.
  33755. *
  33756. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33757. * 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
  33758. * extruded along the Z axis.
  33759. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33760. * 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
  33761. * and the distance of this point from the begining of the path :
  33762. * ```javascript
  33763. * var rotationFunction = function(i, distance) {
  33764. * // do things
  33765. * return rotationValue; }
  33766. * ```
  33767. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33768. * 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
  33769. * and the distance of this point from the begining of the path :
  33770. * ```javascript
  33771. * var scaleFunction = function(i, distance) {
  33772. * // do things
  33773. * return scaleValue;}
  33774. * ```
  33775. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33776. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33777. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33778. * 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
  33779. * 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
  33780. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33782. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33784. */
  33785. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33786. var options = {
  33787. shape: shape,
  33788. path: path,
  33789. scaleFunction: scaleFunction,
  33790. rotationFunction: rotationFunction,
  33791. ribbonCloseArray: ribbonCloseArray,
  33792. ribbonClosePath: ribbonClosePath,
  33793. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33794. sideOrientation: sideOrientation,
  33795. instance: instance,
  33796. updatable: updatable
  33797. };
  33798. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33799. };
  33800. /**
  33801. * Creates lathe mesh.
  33802. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33803. * Please consider using the same method from the MeshBuilder class instead.
  33804. * 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
  33805. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33806. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33807. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33808. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33809. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33811. */
  33812. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33813. var options = {
  33814. shape: shape,
  33815. radius: radius,
  33816. tessellation: tessellation,
  33817. sideOrientation: sideOrientation,
  33818. updatable: updatable
  33819. };
  33820. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33821. };
  33822. /**
  33823. * Creates a plane mesh.
  33824. * Please consider using the same method from the MeshBuilder class instead.
  33825. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33826. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33827. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33829. */
  33830. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33831. var options = {
  33832. size: size,
  33833. width: size,
  33834. height: size,
  33835. sideOrientation: sideOrientation,
  33836. updatable: updatable
  33837. };
  33838. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33839. };
  33840. /**
  33841. * Creates a ground mesh.
  33842. * Please consider using the same method from the MeshBuilder class instead.
  33843. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33844. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33846. */
  33847. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33848. var options = {
  33849. width: width,
  33850. height: height,
  33851. subdivisions: subdivisions,
  33852. updatable: updatable
  33853. };
  33854. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33855. };
  33856. /**
  33857. * Creates a tiled ground mesh.
  33858. * Please consider using the same method from the MeshBuilder class instead.
  33859. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33860. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33861. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33862. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33863. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33864. * numbers of subdivisions on the ground width and height of each tile.
  33865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33866. */
  33867. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33868. var options = {
  33869. xmin: xmin,
  33870. zmin: zmin,
  33871. xmax: xmax,
  33872. zmax: zmax,
  33873. subdivisions: subdivisions,
  33874. precision: precision,
  33875. updatable: updatable
  33876. };
  33877. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33878. };
  33879. /**
  33880. * Creates a ground mesh from a height map.
  33881. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33882. * Please consider using the same method from the MeshBuilder class instead.
  33883. * The parameter `url` sets the URL of the height map image resource.
  33884. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33885. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33886. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33887. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33888. * 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).
  33889. * This function is passed the newly built mesh :
  33890. * ```javascript
  33891. * function(mesh) { // do things
  33892. * return; }
  33893. * ```
  33894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33895. */
  33896. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33897. var options = {
  33898. width: width,
  33899. height: height,
  33900. subdivisions: subdivisions,
  33901. minHeight: minHeight,
  33902. maxHeight: maxHeight,
  33903. updatable: updatable,
  33904. onReady: onReady
  33905. };
  33906. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33907. };
  33908. /**
  33909. * Creates a tube mesh.
  33910. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33911. * Please consider using the same method from the MeshBuilder class instead.
  33912. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33913. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33914. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33915. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33916. * 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.
  33917. * It must return a radius value (positive float) :
  33918. * ```javascript
  33919. * var radiusFunction = function(i, distance) {
  33920. * // do things
  33921. * return radius; }
  33922. * ```
  33923. * 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
  33924. * 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
  33925. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33926. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33928. */
  33929. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33930. var options = {
  33931. path: path,
  33932. radius: radius,
  33933. tessellation: tessellation,
  33934. radiusFunction: radiusFunction,
  33935. arc: 1,
  33936. cap: cap,
  33937. updatable: updatable,
  33938. sideOrientation: sideOrientation,
  33939. instance: instance
  33940. };
  33941. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33942. };
  33943. /**
  33944. * Creates a polyhedron mesh.
  33945. * Please consider using the same method from the MeshBuilder class instead.
  33946. * 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
  33947. * to choose the wanted type.
  33948. * The parameter `size` (positive float, default 1) sets the polygon size.
  33949. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33950. * 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`.
  33951. * 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
  33952. * 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)`).
  33953. * 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
  33954. * 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.
  33955. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33956. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33958. */
  33959. Mesh.CreatePolyhedron = function (name, options, scene) {
  33960. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33961. };
  33962. /**
  33963. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33964. * Please consider using the same method from the MeshBuilder class instead.
  33965. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33966. * 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`).
  33967. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33968. * 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.
  33969. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33970. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33972. */
  33973. Mesh.CreateIcoSphere = function (name, options, scene) {
  33974. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33975. };
  33976. /**
  33977. * Creates a decal mesh.
  33978. * Please consider using the same method from the MeshBuilder class instead.
  33979. * 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.
  33980. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33981. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33982. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33983. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33984. */
  33985. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33986. var options = {
  33987. position: position,
  33988. normal: normal,
  33989. size: size,
  33990. angle: angle
  33991. };
  33992. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33993. };
  33994. // Skeletons
  33995. /**
  33996. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33997. */
  33998. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33999. if (!this._sourcePositions) {
  34000. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34001. if (!source) {
  34002. return this._sourcePositions;
  34003. }
  34004. this._sourcePositions = new Float32Array(source);
  34005. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34006. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34007. }
  34008. }
  34009. return this._sourcePositions;
  34010. };
  34011. /**
  34012. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34013. */
  34014. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34015. if (!this._sourceNormals) {
  34016. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34017. if (!source) {
  34018. return this._sourceNormals;
  34019. }
  34020. this._sourceNormals = new Float32Array(source);
  34021. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34022. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34023. }
  34024. }
  34025. return this._sourceNormals;
  34026. };
  34027. /**
  34028. * Updates the vertex buffer by applying transformation from the bones.
  34029. * Returns the Mesh.
  34030. *
  34031. * @param {skeleton} skeleton to apply
  34032. */
  34033. Mesh.prototype.applySkeleton = function (skeleton) {
  34034. if (!this.geometry) {
  34035. return this;
  34036. }
  34037. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34038. return this;
  34039. }
  34040. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34041. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34042. return this;
  34043. }
  34044. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34045. return this;
  34046. }
  34047. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34048. return this;
  34049. }
  34050. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34051. return this;
  34052. }
  34053. if (!this._sourcePositions) {
  34054. var submeshes = this.subMeshes.slice();
  34055. this.setPositionsForCPUSkinning();
  34056. this.subMeshes = submeshes;
  34057. }
  34058. if (!this._sourceNormals) {
  34059. this.setNormalsForCPUSkinning();
  34060. }
  34061. // positionsData checks for not being Float32Array will only pass at most once
  34062. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34063. if (!positionsData) {
  34064. return this;
  34065. }
  34066. if (!(positionsData instanceof Float32Array)) {
  34067. positionsData = new Float32Array(positionsData);
  34068. }
  34069. // normalsData checks for not being Float32Array will only pass at most once
  34070. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34071. if (!normalsData) {
  34072. return this;
  34073. }
  34074. if (!(normalsData instanceof Float32Array)) {
  34075. normalsData = new Float32Array(normalsData);
  34076. }
  34077. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34078. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34079. if (!matricesWeightsData || !matricesIndicesData) {
  34080. return this;
  34081. }
  34082. var needExtras = this.numBoneInfluencers > 4;
  34083. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34084. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34085. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34086. var tempVector3 = BABYLON.Vector3.Zero();
  34087. var finalMatrix = new BABYLON.Matrix();
  34088. var tempMatrix = new BABYLON.Matrix();
  34089. var matWeightIdx = 0;
  34090. var inf;
  34091. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34092. var weight;
  34093. for (inf = 0; inf < 4; inf++) {
  34094. weight = matricesWeightsData[matWeightIdx + inf];
  34095. if (weight > 0) {
  34096. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34097. finalMatrix.addToSelf(tempMatrix);
  34098. }
  34099. }
  34100. if (needExtras) {
  34101. for (inf = 0; inf < 4; inf++) {
  34102. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34103. if (weight > 0) {
  34104. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34105. finalMatrix.addToSelf(tempMatrix);
  34106. }
  34107. }
  34108. }
  34109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34110. tempVector3.toArray(positionsData, index);
  34111. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34112. tempVector3.toArray(normalsData, index);
  34113. finalMatrix.reset();
  34114. }
  34115. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34116. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34117. return this;
  34118. };
  34119. // Tools
  34120. /**
  34121. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34122. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34123. */
  34124. Mesh.MinMax = function (meshes) {
  34125. var minVector = null;
  34126. var maxVector = null;
  34127. meshes.forEach(function (mesh, index, array) {
  34128. var boundingInfo = mesh.getBoundingInfo();
  34129. var boundingBox = boundingInfo.boundingBox;
  34130. if (!minVector || !maxVector) {
  34131. minVector = boundingBox.minimumWorld;
  34132. maxVector = boundingBox.maximumWorld;
  34133. }
  34134. else {
  34135. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34136. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34137. }
  34138. });
  34139. if (!minVector || !maxVector) {
  34140. return {
  34141. min: BABYLON.Vector3.Zero(),
  34142. max: BABYLON.Vector3.Zero()
  34143. };
  34144. }
  34145. return {
  34146. min: minVector,
  34147. max: maxVector
  34148. };
  34149. };
  34150. /**
  34151. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34152. */
  34153. Mesh.Center = function (meshesOrMinMaxVector) {
  34154. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34155. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34156. };
  34157. /**
  34158. * Merge the array of meshes into a single mesh for performance reasons.
  34159. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34160. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34161. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34162. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34163. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34164. */
  34165. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34166. if (disposeSource === void 0) { disposeSource = true; }
  34167. var index;
  34168. if (!allow32BitsIndices) {
  34169. var totalVertices = 0;
  34170. // Counting vertices
  34171. for (index = 0; index < meshes.length; index++) {
  34172. if (meshes[index]) {
  34173. totalVertices += meshes[index].getTotalVertices();
  34174. if (totalVertices > 65536) {
  34175. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34176. return null;
  34177. }
  34178. }
  34179. }
  34180. }
  34181. // Merge
  34182. var vertexData = null;
  34183. var otherVertexData;
  34184. var indiceArray = new Array();
  34185. var source = null;
  34186. for (index = 0; index < meshes.length; index++) {
  34187. if (meshes[index]) {
  34188. var wm = meshes[index].computeWorldMatrix(true);
  34189. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34190. otherVertexData.transform(wm);
  34191. if (vertexData) {
  34192. vertexData.merge(otherVertexData, allow32BitsIndices);
  34193. }
  34194. else {
  34195. vertexData = otherVertexData;
  34196. source = meshes[index];
  34197. }
  34198. if (subdivideWithSubMeshes) {
  34199. indiceArray.push(meshes[index].getTotalIndices());
  34200. }
  34201. }
  34202. }
  34203. source = source;
  34204. if (!meshSubclass) {
  34205. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34206. }
  34207. vertexData.applyToMesh(meshSubclass);
  34208. // Setting properties
  34209. meshSubclass.material = source.material;
  34210. meshSubclass.checkCollisions = source.checkCollisions;
  34211. // Cleaning
  34212. if (disposeSource) {
  34213. for (index = 0; index < meshes.length; index++) {
  34214. if (meshes[index]) {
  34215. meshes[index].dispose();
  34216. }
  34217. }
  34218. }
  34219. // Subdivide
  34220. if (subdivideWithSubMeshes) {
  34221. //-- removal of global submesh
  34222. meshSubclass.releaseSubMeshes();
  34223. index = 0;
  34224. var offset = 0;
  34225. //-- apply subdivision according to index table
  34226. while (index < indiceArray.length) {
  34227. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34228. offset += indiceArray[index];
  34229. index++;
  34230. }
  34231. }
  34232. return meshSubclass;
  34233. };
  34234. // Consts
  34235. Mesh._FRONTSIDE = 0;
  34236. Mesh._BACKSIDE = 1;
  34237. Mesh._DOUBLESIDE = 2;
  34238. Mesh._DEFAULTSIDE = 0;
  34239. Mesh._NO_CAP = 0;
  34240. Mesh._CAP_START = 1;
  34241. Mesh._CAP_END = 2;
  34242. Mesh._CAP_ALL = 3;
  34243. return Mesh;
  34244. }(BABYLON.AbstractMesh));
  34245. BABYLON.Mesh = Mesh;
  34246. })(BABYLON || (BABYLON = {}));
  34247. //# sourceMappingURL=babylon.mesh.js.map
  34248. var BABYLON;
  34249. (function (BABYLON) {
  34250. var BaseSubMesh = /** @class */ (function () {
  34251. function BaseSubMesh() {
  34252. }
  34253. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34254. get: function () {
  34255. return this._materialEffect;
  34256. },
  34257. enumerable: true,
  34258. configurable: true
  34259. });
  34260. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34261. if (defines === void 0) { defines = null; }
  34262. if (this._materialEffect === effect) {
  34263. if (!effect) {
  34264. this._materialDefines = null;
  34265. }
  34266. return;
  34267. }
  34268. this._materialDefines = defines;
  34269. this._materialEffect = effect;
  34270. };
  34271. return BaseSubMesh;
  34272. }());
  34273. BABYLON.BaseSubMesh = BaseSubMesh;
  34274. var SubMesh = /** @class */ (function (_super) {
  34275. __extends(SubMesh, _super);
  34276. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34277. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34278. var _this = _super.call(this) || this;
  34279. _this.materialIndex = materialIndex;
  34280. _this.verticesStart = verticesStart;
  34281. _this.verticesCount = verticesCount;
  34282. _this.indexStart = indexStart;
  34283. _this.indexCount = indexCount;
  34284. /** @hidden */
  34285. _this._renderId = 0;
  34286. _this._mesh = mesh;
  34287. _this._renderingMesh = renderingMesh || mesh;
  34288. mesh.subMeshes.push(_this);
  34289. _this._trianglePlanes = [];
  34290. _this._id = mesh.subMeshes.length - 1;
  34291. if (createBoundingBox) {
  34292. _this.refreshBoundingInfo();
  34293. mesh.computeWorldMatrix(true);
  34294. }
  34295. return _this;
  34296. }
  34297. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34298. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34299. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34300. };
  34301. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34302. get: function () {
  34303. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34304. },
  34305. enumerable: true,
  34306. configurable: true
  34307. });
  34308. /**
  34309. * Returns the submesh BoudingInfo object.
  34310. */
  34311. SubMesh.prototype.getBoundingInfo = function () {
  34312. if (this.IsGlobal) {
  34313. return this._mesh.getBoundingInfo();
  34314. }
  34315. return this._boundingInfo;
  34316. };
  34317. /**
  34318. * Sets the submesh BoundingInfo.
  34319. * Return the SubMesh.
  34320. */
  34321. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34322. this._boundingInfo = boundingInfo;
  34323. return this;
  34324. };
  34325. /**
  34326. * Returns the mesh of the current submesh.
  34327. */
  34328. SubMesh.prototype.getMesh = function () {
  34329. return this._mesh;
  34330. };
  34331. /**
  34332. * Returns the rendering mesh of the submesh.
  34333. */
  34334. SubMesh.prototype.getRenderingMesh = function () {
  34335. return this._renderingMesh;
  34336. };
  34337. /**
  34338. * Returns the submesh material.
  34339. */
  34340. SubMesh.prototype.getMaterial = function () {
  34341. var rootMaterial = this._renderingMesh.material;
  34342. if (rootMaterial === null || rootMaterial === undefined) {
  34343. return this._mesh.getScene().defaultMaterial;
  34344. }
  34345. else if (rootMaterial.getSubMaterial) {
  34346. var multiMaterial = rootMaterial;
  34347. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34348. if (this._currentMaterial !== effectiveMaterial) {
  34349. this._currentMaterial = effectiveMaterial;
  34350. this._materialDefines = null;
  34351. }
  34352. return effectiveMaterial;
  34353. }
  34354. return rootMaterial;
  34355. };
  34356. // Methods
  34357. /**
  34358. * Sets a new updated BoundingInfo object to the submesh.
  34359. * Returns the SubMesh.
  34360. */
  34361. SubMesh.prototype.refreshBoundingInfo = function () {
  34362. this._lastColliderWorldVertices = null;
  34363. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34364. return this;
  34365. }
  34366. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34367. if (!data) {
  34368. this._boundingInfo = this._mesh.getBoundingInfo();
  34369. return this;
  34370. }
  34371. var indices = this._renderingMesh.getIndices();
  34372. var extend;
  34373. //is this the only submesh?
  34374. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34375. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34376. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34377. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34378. }
  34379. else {
  34380. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34381. }
  34382. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34383. return this;
  34384. };
  34385. /** @hidden */
  34386. SubMesh.prototype._checkCollision = function (collider) {
  34387. var boundingInfo = this.getBoundingInfo();
  34388. return boundingInfo._checkCollision(collider);
  34389. };
  34390. /**
  34391. * Updates the submesh BoundingInfo.
  34392. * Returns the Submesh.
  34393. */
  34394. SubMesh.prototype.updateBoundingInfo = function (world) {
  34395. var boundingInfo = this.getBoundingInfo();
  34396. if (!boundingInfo) {
  34397. this.refreshBoundingInfo();
  34398. boundingInfo = this.getBoundingInfo();
  34399. }
  34400. boundingInfo.update(world);
  34401. return this;
  34402. };
  34403. /**
  34404. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34405. * Boolean returned.
  34406. */
  34407. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34408. var boundingInfo = this.getBoundingInfo();
  34409. if (!boundingInfo) {
  34410. return false;
  34411. }
  34412. return boundingInfo.isInFrustum(frustumPlanes);
  34413. };
  34414. /**
  34415. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34416. * Boolean returned.
  34417. */
  34418. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34419. var boundingInfo = this.getBoundingInfo();
  34420. if (!boundingInfo) {
  34421. return false;
  34422. }
  34423. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34424. };
  34425. /**
  34426. * Renders the submesh.
  34427. * Returns it.
  34428. */
  34429. SubMesh.prototype.render = function (enableAlphaMode) {
  34430. this._renderingMesh.render(this, enableAlphaMode);
  34431. return this;
  34432. };
  34433. /**
  34434. * Returns a new Index Buffer.
  34435. * Type returned : WebGLBuffer.
  34436. */
  34437. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34438. if (!this._linesIndexBuffer) {
  34439. var linesIndices = [];
  34440. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34441. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34442. }
  34443. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34444. this.linesIndexCount = linesIndices.length;
  34445. }
  34446. return this._linesIndexBuffer;
  34447. };
  34448. /**
  34449. * True is the passed Ray intersects the submesh bounding box.
  34450. * Boolean returned.
  34451. */
  34452. SubMesh.prototype.canIntersects = function (ray) {
  34453. var boundingInfo = this.getBoundingInfo();
  34454. if (!boundingInfo) {
  34455. return false;
  34456. }
  34457. return ray.intersectsBox(boundingInfo.boundingBox);
  34458. };
  34459. /**
  34460. * Returns an object IntersectionInfo.
  34461. */
  34462. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34463. var intersectInfo = null;
  34464. var material = this.getMaterial();
  34465. if (!material) {
  34466. return null;
  34467. }
  34468. switch (material.fillMode) {
  34469. case BABYLON.Material.PointListDrawMode:
  34470. case BABYLON.Material.LineListDrawMode:
  34471. case BABYLON.Material.LineLoopDrawMode:
  34472. case BABYLON.Material.LineStripDrawMode:
  34473. case BABYLON.Material.TriangleFanDrawMode:
  34474. case BABYLON.Material.TriangleStripDrawMode:
  34475. return null;
  34476. }
  34477. // LineMesh first as it's also a Mesh...
  34478. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34479. var lineMesh = this._mesh;
  34480. // Line test
  34481. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34482. var p0 = positions[indices[index]];
  34483. var p1 = positions[indices[index + 1]];
  34484. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34485. if (length < 0) {
  34486. continue;
  34487. }
  34488. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34489. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34490. if (fastCheck) {
  34491. break;
  34492. }
  34493. }
  34494. }
  34495. }
  34496. else {
  34497. // Triangles test
  34498. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34499. var p0 = positions[indices[index]];
  34500. var p1 = positions[indices[index + 1]];
  34501. var p2 = positions[indices[index + 2]];
  34502. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34503. if (currentIntersectInfo) {
  34504. if (currentIntersectInfo.distance < 0) {
  34505. continue;
  34506. }
  34507. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34508. intersectInfo = currentIntersectInfo;
  34509. intersectInfo.faceId = index / 3;
  34510. if (fastCheck) {
  34511. break;
  34512. }
  34513. }
  34514. }
  34515. }
  34516. }
  34517. return intersectInfo;
  34518. };
  34519. /** @hidden */
  34520. SubMesh.prototype._rebuild = function () {
  34521. if (this._linesIndexBuffer) {
  34522. this._linesIndexBuffer = null;
  34523. }
  34524. };
  34525. // Clone
  34526. /**
  34527. * Creates a new Submesh from the passed Mesh.
  34528. */
  34529. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34530. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34531. if (!this.IsGlobal) {
  34532. var boundingInfo = this.getBoundingInfo();
  34533. if (!boundingInfo) {
  34534. return result;
  34535. }
  34536. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34537. }
  34538. return result;
  34539. };
  34540. // Dispose
  34541. /**
  34542. * Disposes the Submesh.
  34543. * Returns nothing.
  34544. */
  34545. SubMesh.prototype.dispose = function () {
  34546. if (this._linesIndexBuffer) {
  34547. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34548. this._linesIndexBuffer = null;
  34549. }
  34550. // Remove from mesh
  34551. var index = this._mesh.subMeshes.indexOf(this);
  34552. this._mesh.subMeshes.splice(index, 1);
  34553. };
  34554. // Statics
  34555. /**
  34556. * Creates a new Submesh from the passed parameters :
  34557. * - materialIndex (integer) : the index of the main mesh material.
  34558. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34559. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34560. * - mesh (Mesh) : the main mesh to create the submesh from.
  34561. * - renderingMesh (optional Mesh) : rendering mesh.
  34562. */
  34563. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34564. var minVertexIndex = Number.MAX_VALUE;
  34565. var maxVertexIndex = -Number.MAX_VALUE;
  34566. renderingMesh = (renderingMesh || mesh);
  34567. var indices = renderingMesh.getIndices();
  34568. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34569. var vertexIndex = indices[index];
  34570. if (vertexIndex < minVertexIndex)
  34571. minVertexIndex = vertexIndex;
  34572. if (vertexIndex > maxVertexIndex)
  34573. maxVertexIndex = vertexIndex;
  34574. }
  34575. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34576. };
  34577. return SubMesh;
  34578. }(BaseSubMesh));
  34579. BABYLON.SubMesh = SubMesh;
  34580. })(BABYLON || (BABYLON = {}));
  34581. //# sourceMappingURL=babylon.subMesh.js.map
  34582. var __assign = (this && this.__assign) || function () {
  34583. __assign = Object.assign || function(t) {
  34584. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34585. s = arguments[i];
  34586. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34587. t[p] = s[p];
  34588. }
  34589. return t;
  34590. };
  34591. return __assign.apply(this, arguments);
  34592. };
  34593. var BABYLON;
  34594. (function (BABYLON) {
  34595. /**
  34596. * Manages the defines for the Material
  34597. */
  34598. var MaterialDefines = /** @class */ (function () {
  34599. function MaterialDefines() {
  34600. this._isDirty = true;
  34601. /** @hidden */
  34602. this._areLightsDirty = true;
  34603. /** @hidden */
  34604. this._areAttributesDirty = true;
  34605. /** @hidden */
  34606. this._areTexturesDirty = true;
  34607. /** @hidden */
  34608. this._areFresnelDirty = true;
  34609. /** @hidden */
  34610. this._areMiscDirty = true;
  34611. /** @hidden */
  34612. this._areImageProcessingDirty = true;
  34613. /** @hidden */
  34614. this._normals = false;
  34615. /** @hidden */
  34616. this._uvs = false;
  34617. /** @hidden */
  34618. this._needNormals = false;
  34619. /** @hidden */
  34620. this._needUVs = false;
  34621. }
  34622. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34623. /**
  34624. * Specifies if the material needs to be re-calculated
  34625. */
  34626. get: function () {
  34627. return this._isDirty;
  34628. },
  34629. enumerable: true,
  34630. configurable: true
  34631. });
  34632. /**
  34633. * Marks the material to indicate that it has been re-calculated
  34634. */
  34635. MaterialDefines.prototype.markAsProcessed = function () {
  34636. this._isDirty = false;
  34637. this._areAttributesDirty = false;
  34638. this._areTexturesDirty = false;
  34639. this._areFresnelDirty = false;
  34640. this._areLightsDirty = false;
  34641. this._areMiscDirty = false;
  34642. this._areImageProcessingDirty = false;
  34643. };
  34644. /**
  34645. * Marks the material to indicate that it needs to be re-calculated
  34646. */
  34647. MaterialDefines.prototype.markAsUnprocessed = function () {
  34648. this._isDirty = true;
  34649. };
  34650. /**
  34651. * Marks the material to indicate all of its defines need to be re-calculated
  34652. */
  34653. MaterialDefines.prototype.markAllAsDirty = function () {
  34654. this._areTexturesDirty = true;
  34655. this._areAttributesDirty = true;
  34656. this._areLightsDirty = true;
  34657. this._areFresnelDirty = true;
  34658. this._areMiscDirty = true;
  34659. this._areImageProcessingDirty = true;
  34660. this._isDirty = true;
  34661. };
  34662. /**
  34663. * Marks the material to indicate that image processing needs to be re-calculated
  34664. */
  34665. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34666. this._areImageProcessingDirty = true;
  34667. this._isDirty = true;
  34668. };
  34669. /**
  34670. * Marks the material to indicate the lights need to be re-calculated
  34671. */
  34672. MaterialDefines.prototype.markAsLightDirty = function () {
  34673. this._areLightsDirty = true;
  34674. this._isDirty = true;
  34675. };
  34676. /**
  34677. * Marks the attribute state as changed
  34678. */
  34679. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34680. this._areAttributesDirty = true;
  34681. this._isDirty = true;
  34682. };
  34683. /**
  34684. * Marks the texture state as changed
  34685. */
  34686. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34687. this._areTexturesDirty = true;
  34688. this._isDirty = true;
  34689. };
  34690. /**
  34691. * Marks the fresnel state as changed
  34692. */
  34693. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34694. this._areFresnelDirty = true;
  34695. this._isDirty = true;
  34696. };
  34697. /**
  34698. * Marks the misc state as changed
  34699. */
  34700. MaterialDefines.prototype.markAsMiscDirty = function () {
  34701. this._areMiscDirty = true;
  34702. this._isDirty = true;
  34703. };
  34704. /**
  34705. * Rebuilds the material defines
  34706. */
  34707. MaterialDefines.prototype.rebuild = function () {
  34708. if (this._keys) {
  34709. delete this._keys;
  34710. }
  34711. this._keys = [];
  34712. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34713. var key = _a[_i];
  34714. if (key[0] === "_") {
  34715. continue;
  34716. }
  34717. this._keys.push(key);
  34718. }
  34719. };
  34720. /**
  34721. * Specifies if two material defines are equal
  34722. * @param other - A material define instance to compare to
  34723. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34724. */
  34725. MaterialDefines.prototype.isEqual = function (other) {
  34726. if (this._keys.length !== other._keys.length) {
  34727. return false;
  34728. }
  34729. for (var index = 0; index < this._keys.length; index++) {
  34730. var prop = this._keys[index];
  34731. if (this[prop] !== other[prop]) {
  34732. return false;
  34733. }
  34734. }
  34735. return true;
  34736. };
  34737. /**
  34738. * Clones this instance's defines to another instance
  34739. * @param other - material defines to clone values to
  34740. */
  34741. MaterialDefines.prototype.cloneTo = function (other) {
  34742. if (this._keys.length !== other._keys.length) {
  34743. other._keys = this._keys.slice(0);
  34744. }
  34745. for (var index = 0; index < this._keys.length; index++) {
  34746. var prop = this._keys[index];
  34747. other[prop] = this[prop];
  34748. }
  34749. };
  34750. /**
  34751. * Resets the material define values
  34752. */
  34753. MaterialDefines.prototype.reset = function () {
  34754. for (var index = 0; index < this._keys.length; index++) {
  34755. var prop = this._keys[index];
  34756. var type = typeof this[prop];
  34757. switch (type) {
  34758. case "number":
  34759. this[prop] = 0;
  34760. break;
  34761. case "string":
  34762. this[prop] = "";
  34763. break;
  34764. default:
  34765. this[prop] = false;
  34766. break;
  34767. }
  34768. }
  34769. };
  34770. /**
  34771. * Converts the material define values to a string
  34772. * @returns - String of material define information
  34773. */
  34774. MaterialDefines.prototype.toString = function () {
  34775. var result = "";
  34776. for (var index = 0; index < this._keys.length; index++) {
  34777. var prop = this._keys[index];
  34778. var value = this[prop];
  34779. var type = typeof value;
  34780. switch (type) {
  34781. case "number":
  34782. case "string":
  34783. result += "#define " + prop + " " + value + "\n";
  34784. break;
  34785. default:
  34786. if (value) {
  34787. result += "#define " + prop + "\n";
  34788. }
  34789. break;
  34790. }
  34791. }
  34792. return result;
  34793. };
  34794. return MaterialDefines;
  34795. }());
  34796. BABYLON.MaterialDefines = MaterialDefines;
  34797. /**
  34798. * Base class for the main features of a material in Babylon.js
  34799. */
  34800. var Material = /** @class */ (function () {
  34801. /**
  34802. * Creates a material instance
  34803. * @param name defines the name of the material
  34804. * @param scene defines the scene to reference
  34805. * @param doNotAdd specifies if the material should be added to the scene
  34806. */
  34807. function Material(name, scene, doNotAdd) {
  34808. /**
  34809. * Specifies if the ready state should be checked on each call
  34810. */
  34811. this.checkReadyOnEveryCall = false;
  34812. /**
  34813. * Specifies if the ready state should be checked once
  34814. */
  34815. this.checkReadyOnlyOnce = false;
  34816. /**
  34817. * The state of the material
  34818. */
  34819. this.state = "";
  34820. /**
  34821. * The alpha value of the material
  34822. */
  34823. this._alpha = 1.0;
  34824. /**
  34825. * Specifies if back face culling is enabled
  34826. */
  34827. this._backFaceCulling = true;
  34828. /**
  34829. * Specifies if the material should be serialized
  34830. */
  34831. this.doNotSerialize = false;
  34832. /**
  34833. * Specifies if the effect should be stored on sub meshes
  34834. */
  34835. this.storeEffectOnSubMeshes = false;
  34836. /**
  34837. * An event triggered when the material is disposed
  34838. */
  34839. this.onDisposeObservable = new BABYLON.Observable();
  34840. /**
  34841. * Stores the value of the alpha mode
  34842. */
  34843. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34844. /**
  34845. * Stores the state of the need depth pre-pass value
  34846. */
  34847. this._needDepthPrePass = false;
  34848. /**
  34849. * Specifies if depth writing should be disabled
  34850. */
  34851. this.disableDepthWrite = false;
  34852. /**
  34853. * Specifies if depth writing should be forced
  34854. */
  34855. this.forceDepthWrite = false;
  34856. /**
  34857. * Specifies if there should be a separate pass for culling
  34858. */
  34859. this.separateCullingPass = false;
  34860. /**
  34861. * Stores the state specifing if fog should be enabled
  34862. */
  34863. this._fogEnabled = true;
  34864. /**
  34865. * Stores the size of points
  34866. */
  34867. this.pointSize = 1.0;
  34868. /**
  34869. * Stores the z offset value
  34870. */
  34871. this.zOffset = 0;
  34872. /**
  34873. * @hidden
  34874. * Specifies if the material was previously ready
  34875. */
  34876. this._wasPreviouslyReady = false;
  34877. /**
  34878. * Stores the fill mode state
  34879. */
  34880. this._fillMode = Material.TriangleFillMode;
  34881. this.name = name;
  34882. this.id = name || BABYLON.Tools.RandomId();
  34883. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34884. this.uniqueId = this._scene.getUniqueId();
  34885. if (this._scene.useRightHandedSystem) {
  34886. this.sideOrientation = Material.ClockWiseSideOrientation;
  34887. }
  34888. else {
  34889. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34890. }
  34891. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34892. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34893. if (!doNotAdd) {
  34894. this._scene.materials.push(this);
  34895. }
  34896. }
  34897. Object.defineProperty(Material, "TriangleFillMode", {
  34898. /**
  34899. * Returns the triangle fill mode
  34900. */
  34901. get: function () {
  34902. return Material._TriangleFillMode;
  34903. },
  34904. enumerable: true,
  34905. configurable: true
  34906. });
  34907. Object.defineProperty(Material, "WireFrameFillMode", {
  34908. /**
  34909. * Returns the wireframe mode
  34910. */
  34911. get: function () {
  34912. return Material._WireFrameFillMode;
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(Material, "PointFillMode", {
  34918. /**
  34919. * Returns the point fill mode
  34920. */
  34921. get: function () {
  34922. return Material._PointFillMode;
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. Object.defineProperty(Material, "PointListDrawMode", {
  34928. /**
  34929. * Returns the point list draw mode
  34930. */
  34931. get: function () {
  34932. return Material._PointListDrawMode;
  34933. },
  34934. enumerable: true,
  34935. configurable: true
  34936. });
  34937. Object.defineProperty(Material, "LineListDrawMode", {
  34938. /**
  34939. * Returns the line list draw mode
  34940. */
  34941. get: function () {
  34942. return Material._LineListDrawMode;
  34943. },
  34944. enumerable: true,
  34945. configurable: true
  34946. });
  34947. Object.defineProperty(Material, "LineLoopDrawMode", {
  34948. /**
  34949. * Returns the line loop draw mode
  34950. */
  34951. get: function () {
  34952. return Material._LineLoopDrawMode;
  34953. },
  34954. enumerable: true,
  34955. configurable: true
  34956. });
  34957. Object.defineProperty(Material, "LineStripDrawMode", {
  34958. /**
  34959. * Returns the line strip draw mode
  34960. */
  34961. get: function () {
  34962. return Material._LineStripDrawMode;
  34963. },
  34964. enumerable: true,
  34965. configurable: true
  34966. });
  34967. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34968. /**
  34969. * Returns the triangle strip draw mode
  34970. */
  34971. get: function () {
  34972. return Material._TriangleStripDrawMode;
  34973. },
  34974. enumerable: true,
  34975. configurable: true
  34976. });
  34977. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34978. /**
  34979. * Returns the triangle fan draw mode
  34980. */
  34981. get: function () {
  34982. return Material._TriangleFanDrawMode;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34988. /**
  34989. * Returns the clock-wise side orientation
  34990. */
  34991. get: function () {
  34992. return Material._ClockWiseSideOrientation;
  34993. },
  34994. enumerable: true,
  34995. configurable: true
  34996. });
  34997. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34998. /**
  34999. * Returns the counter clock-wise side orientation
  35000. */
  35001. get: function () {
  35002. return Material._CounterClockWiseSideOrientation;
  35003. },
  35004. enumerable: true,
  35005. configurable: true
  35006. });
  35007. Object.defineProperty(Material, "TextureDirtyFlag", {
  35008. /**
  35009. * Returns the dirty texture flag value
  35010. */
  35011. get: function () {
  35012. return Material._TextureDirtyFlag;
  35013. },
  35014. enumerable: true,
  35015. configurable: true
  35016. });
  35017. Object.defineProperty(Material, "LightDirtyFlag", {
  35018. /**
  35019. * Returns the dirty light flag value
  35020. */
  35021. get: function () {
  35022. return Material._LightDirtyFlag;
  35023. },
  35024. enumerable: true,
  35025. configurable: true
  35026. });
  35027. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35028. /**
  35029. * Returns the dirty fresnel flag value
  35030. */
  35031. get: function () {
  35032. return Material._FresnelDirtyFlag;
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35038. /**
  35039. * Returns the dirty attributes flag value
  35040. */
  35041. get: function () {
  35042. return Material._AttributesDirtyFlag;
  35043. },
  35044. enumerable: true,
  35045. configurable: true
  35046. });
  35047. Object.defineProperty(Material, "MiscDirtyFlag", {
  35048. /**
  35049. * Returns the dirty misc flag value
  35050. */
  35051. get: function () {
  35052. return Material._MiscDirtyFlag;
  35053. },
  35054. enumerable: true,
  35055. configurable: true
  35056. });
  35057. Object.defineProperty(Material.prototype, "alpha", {
  35058. /**
  35059. * Gets the alpha value of the material
  35060. */
  35061. get: function () {
  35062. return this._alpha;
  35063. },
  35064. /**
  35065. * Sets the alpha value of the material
  35066. */
  35067. set: function (value) {
  35068. if (this._alpha === value) {
  35069. return;
  35070. }
  35071. this._alpha = value;
  35072. this.markAsDirty(Material.MiscDirtyFlag);
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35078. /**
  35079. * Gets the back-face culling state
  35080. */
  35081. get: function () {
  35082. return this._backFaceCulling;
  35083. },
  35084. /**
  35085. * Sets the back-face culling state
  35086. */
  35087. set: function (value) {
  35088. if (this._backFaceCulling === value) {
  35089. return;
  35090. }
  35091. this._backFaceCulling = value;
  35092. this.markAsDirty(Material.TextureDirtyFlag);
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. Object.defineProperty(Material.prototype, "onDispose", {
  35098. /**
  35099. * Called during a dispose event
  35100. */
  35101. set: function (callback) {
  35102. if (this._onDisposeObserver) {
  35103. this.onDisposeObservable.remove(this._onDisposeObserver);
  35104. }
  35105. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35106. },
  35107. enumerable: true,
  35108. configurable: true
  35109. });
  35110. Object.defineProperty(Material.prototype, "onBindObservable", {
  35111. /**
  35112. * An event triggered when the material is bound
  35113. */
  35114. get: function () {
  35115. if (!this._onBindObservable) {
  35116. this._onBindObservable = new BABYLON.Observable();
  35117. }
  35118. return this._onBindObservable;
  35119. },
  35120. enumerable: true,
  35121. configurable: true
  35122. });
  35123. Object.defineProperty(Material.prototype, "onBind", {
  35124. /**
  35125. * Called during a bind event
  35126. */
  35127. set: function (callback) {
  35128. if (this._onBindObserver) {
  35129. this.onBindObservable.remove(this._onBindObserver);
  35130. }
  35131. this._onBindObserver = this.onBindObservable.add(callback);
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35137. /**
  35138. * An event triggered when the material is unbound
  35139. */
  35140. get: function () {
  35141. if (!this._onUnBindObservable) {
  35142. this._onUnBindObservable = new BABYLON.Observable();
  35143. }
  35144. return this._onUnBindObservable;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material.prototype, "alphaMode", {
  35150. /**
  35151. * Gets the value of the alpha mode
  35152. */
  35153. get: function () {
  35154. return this._alphaMode;
  35155. },
  35156. /**
  35157. * Sets the value of the alpha mode.
  35158. *
  35159. * | Value | Type | Description |
  35160. * | --- | --- | --- |
  35161. * | 0 | ALPHA_DISABLE | |
  35162. * | 1 | ALPHA_ADD | |
  35163. * | 2 | ALPHA_COMBINE | |
  35164. * | 3 | ALPHA_SUBTRACT | |
  35165. * | 4 | ALPHA_MULTIPLY | |
  35166. * | 5 | ALPHA_MAXIMIZED | |
  35167. * | 6 | ALPHA_ONEONE | |
  35168. * | 7 | ALPHA_PREMULTIPLIED | |
  35169. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35170. * | 9 | ALPHA_INTERPOLATE | |
  35171. * | 10 | ALPHA_SCREENMODE | |
  35172. *
  35173. */
  35174. set: function (value) {
  35175. if (this._alphaMode === value) {
  35176. return;
  35177. }
  35178. this._alphaMode = value;
  35179. this.markAsDirty(Material.TextureDirtyFlag);
  35180. },
  35181. enumerable: true,
  35182. configurable: true
  35183. });
  35184. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35185. /**
  35186. * Gets the depth pre-pass value
  35187. */
  35188. get: function () {
  35189. return this._needDepthPrePass;
  35190. },
  35191. /**
  35192. * Sets the need depth pre-pass value
  35193. */
  35194. set: function (value) {
  35195. if (this._needDepthPrePass === value) {
  35196. return;
  35197. }
  35198. this._needDepthPrePass = value;
  35199. if (this._needDepthPrePass) {
  35200. this.checkReadyOnEveryCall = true;
  35201. }
  35202. },
  35203. enumerable: true,
  35204. configurable: true
  35205. });
  35206. Object.defineProperty(Material.prototype, "fogEnabled", {
  35207. /**
  35208. * Gets the value of the fog enabled state
  35209. */
  35210. get: function () {
  35211. return this._fogEnabled;
  35212. },
  35213. /**
  35214. * Sets the state for enabling fog
  35215. */
  35216. set: function (value) {
  35217. if (this._fogEnabled === value) {
  35218. return;
  35219. }
  35220. this._fogEnabled = value;
  35221. this.markAsDirty(Material.MiscDirtyFlag);
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(Material.prototype, "wireframe", {
  35227. /**
  35228. * Gets a value specifying if wireframe mode is enabled
  35229. */
  35230. get: function () {
  35231. switch (this._fillMode) {
  35232. case Material.WireFrameFillMode:
  35233. case Material.LineListDrawMode:
  35234. case Material.LineLoopDrawMode:
  35235. case Material.LineStripDrawMode:
  35236. return true;
  35237. }
  35238. return this._scene.forceWireframe;
  35239. },
  35240. /**
  35241. * Sets the state of wireframe mode
  35242. */
  35243. set: function (value) {
  35244. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. Object.defineProperty(Material.prototype, "pointsCloud", {
  35250. /**
  35251. * Gets the value specifying if point clouds are enabled
  35252. */
  35253. get: function () {
  35254. switch (this._fillMode) {
  35255. case Material.PointFillMode:
  35256. case Material.PointListDrawMode:
  35257. return true;
  35258. }
  35259. return this._scene.forcePointsCloud;
  35260. },
  35261. /**
  35262. * Sets the state of point cloud mode
  35263. */
  35264. set: function (value) {
  35265. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(Material.prototype, "fillMode", {
  35271. /**
  35272. * Gets the material fill mode
  35273. */
  35274. get: function () {
  35275. return this._fillMode;
  35276. },
  35277. /**
  35278. * Sets the material fill mode
  35279. */
  35280. set: function (value) {
  35281. if (this._fillMode === value) {
  35282. return;
  35283. }
  35284. this._fillMode = value;
  35285. this.markAsDirty(Material.MiscDirtyFlag);
  35286. },
  35287. enumerable: true,
  35288. configurable: true
  35289. });
  35290. /**
  35291. * Returns a string representation of the current material
  35292. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35293. * @returns a string with material information
  35294. */
  35295. Material.prototype.toString = function (fullDetails) {
  35296. var ret = "Name: " + this.name;
  35297. if (fullDetails) {
  35298. }
  35299. return ret;
  35300. };
  35301. /**
  35302. * Gets the class name of the material
  35303. * @returns a string with the class name of the material
  35304. */
  35305. Material.prototype.getClassName = function () {
  35306. return "Material";
  35307. };
  35308. Object.defineProperty(Material.prototype, "isFrozen", {
  35309. /**
  35310. * Specifies if updates for the material been locked
  35311. */
  35312. get: function () {
  35313. return this.checkReadyOnlyOnce;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. /**
  35319. * Locks updates for the material
  35320. */
  35321. Material.prototype.freeze = function () {
  35322. this.checkReadyOnlyOnce = true;
  35323. };
  35324. /**
  35325. * Unlocks updates for the material
  35326. */
  35327. Material.prototype.unfreeze = function () {
  35328. this.checkReadyOnlyOnce = false;
  35329. };
  35330. /**
  35331. * Specifies if the material is ready to be used
  35332. * @param mesh defines the mesh to check
  35333. * @param useInstances specifies if instances should be used
  35334. * @returns a boolean indicating if the material is ready to be used
  35335. */
  35336. Material.prototype.isReady = function (mesh, useInstances) {
  35337. return true;
  35338. };
  35339. /**
  35340. * Specifies that the submesh is ready to be used
  35341. * @param mesh defines the mesh to check
  35342. * @param subMesh defines which submesh to check
  35343. * @param useInstances specifies that instances should be used
  35344. * @returns a boolean indicating that the submesh is ready or not
  35345. */
  35346. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35347. return false;
  35348. };
  35349. /**
  35350. * Returns the material effect
  35351. * @returns the effect associated with the material
  35352. */
  35353. Material.prototype.getEffect = function () {
  35354. return this._effect;
  35355. };
  35356. /**
  35357. * Returns the current scene
  35358. * @returns a Scene
  35359. */
  35360. Material.prototype.getScene = function () {
  35361. return this._scene;
  35362. };
  35363. /**
  35364. * Specifies if the material will require alpha blending
  35365. * @returns a boolean specifying if alpha blending is needed
  35366. */
  35367. Material.prototype.needAlphaBlending = function () {
  35368. return (this.alpha < 1.0);
  35369. };
  35370. /**
  35371. * Specifies if the mesh will require alpha blending
  35372. * @param mesh defines the mesh to check
  35373. * @returns a boolean specifying if alpha blending is needed for the mesh
  35374. */
  35375. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35376. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35377. };
  35378. /**
  35379. * Specifies if this material should be rendered in alpha test mode
  35380. * @returns a boolean specifying if an alpha test is needed.
  35381. */
  35382. Material.prototype.needAlphaTesting = function () {
  35383. return false;
  35384. };
  35385. /**
  35386. * Gets the texture used for the alpha test
  35387. * @returns the texture to use for alpha testing
  35388. */
  35389. Material.prototype.getAlphaTestTexture = function () {
  35390. return null;
  35391. };
  35392. /**
  35393. * Marks the material to indicate that it needs to be re-calculated
  35394. */
  35395. Material.prototype.markDirty = function () {
  35396. this._wasPreviouslyReady = false;
  35397. };
  35398. /** @hidden */
  35399. Material.prototype._preBind = function (effect, overrideOrientation) {
  35400. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35401. var engine = this._scene.getEngine();
  35402. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35403. var reverse = orientation === Material.ClockWiseSideOrientation;
  35404. engine.enableEffect(effect ? effect : this._effect);
  35405. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35406. return reverse;
  35407. };
  35408. /**
  35409. * Binds the material to the mesh
  35410. * @param world defines the world transformation matrix
  35411. * @param mesh defines the mesh to bind the material to
  35412. */
  35413. Material.prototype.bind = function (world, mesh) {
  35414. };
  35415. /**
  35416. * Binds the submesh to the material
  35417. * @param world defines the world transformation matrix
  35418. * @param mesh defines the mesh containing the submesh
  35419. * @param subMesh defines the submesh to bind the material to
  35420. */
  35421. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35422. };
  35423. /**
  35424. * Binds the world matrix to the material
  35425. * @param world defines the world transformation matrix
  35426. */
  35427. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35428. };
  35429. /**
  35430. * Binds the scene's uniform buffer to the effect.
  35431. * @param effect defines the effect to bind to the scene uniform buffer
  35432. * @param sceneUbo defines the uniform buffer storing scene data
  35433. */
  35434. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35435. sceneUbo.bindToEffect(effect, "Scene");
  35436. };
  35437. /**
  35438. * Binds the view matrix to the effect
  35439. * @param effect defines the effect to bind the view matrix to
  35440. */
  35441. Material.prototype.bindView = function (effect) {
  35442. if (!this._useUBO) {
  35443. effect.setMatrix("view", this.getScene().getViewMatrix());
  35444. }
  35445. else {
  35446. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35447. }
  35448. };
  35449. /**
  35450. * Binds the view projection matrix to the effect
  35451. * @param effect defines the effect to bind the view projection matrix to
  35452. */
  35453. Material.prototype.bindViewProjection = function (effect) {
  35454. if (!this._useUBO) {
  35455. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35456. }
  35457. else {
  35458. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35459. }
  35460. };
  35461. /**
  35462. * Specifies if material alpha testing should be turned on for the mesh
  35463. * @param mesh defines the mesh to check
  35464. */
  35465. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35466. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35467. };
  35468. /**
  35469. * Processes to execute after binding the material to a mesh
  35470. * @param mesh defines the rendered mesh
  35471. */
  35472. Material.prototype._afterBind = function (mesh) {
  35473. this._scene._cachedMaterial = this;
  35474. if (mesh) {
  35475. this._scene._cachedVisibility = mesh.visibility;
  35476. }
  35477. else {
  35478. this._scene._cachedVisibility = 1;
  35479. }
  35480. if (this._onBindObservable && mesh) {
  35481. this._onBindObservable.notifyObservers(mesh);
  35482. }
  35483. if (this.disableDepthWrite) {
  35484. var engine = this._scene.getEngine();
  35485. this._cachedDepthWriteState = engine.getDepthWrite();
  35486. engine.setDepthWrite(false);
  35487. }
  35488. };
  35489. /**
  35490. * Unbinds the material from the mesh
  35491. */
  35492. Material.prototype.unbind = function () {
  35493. if (this._onUnBindObservable) {
  35494. this._onUnBindObservable.notifyObservers(this);
  35495. }
  35496. if (this.disableDepthWrite) {
  35497. var engine = this._scene.getEngine();
  35498. engine.setDepthWrite(this._cachedDepthWriteState);
  35499. }
  35500. };
  35501. /**
  35502. * Gets the active textures from the material
  35503. * @returns an array of textures
  35504. */
  35505. Material.prototype.getActiveTextures = function () {
  35506. return [];
  35507. };
  35508. /**
  35509. * Specifies if the material uses a texture
  35510. * @param texture defines the texture to check against the material
  35511. * @returns a boolean specifying if the material uses the texture
  35512. */
  35513. Material.prototype.hasTexture = function (texture) {
  35514. return false;
  35515. };
  35516. /**
  35517. * Makes a duplicate of the material, and gives it a new name
  35518. * @param name defines the new name for the duplicated material
  35519. * @returns the cloned material
  35520. */
  35521. Material.prototype.clone = function (name) {
  35522. return null;
  35523. };
  35524. /**
  35525. * Gets the meshes bound to the material
  35526. * @returns an array of meshes bound to the material
  35527. */
  35528. Material.prototype.getBindedMeshes = function () {
  35529. var result = new Array();
  35530. for (var index = 0; index < this._scene.meshes.length; index++) {
  35531. var mesh = this._scene.meshes[index];
  35532. if (mesh.material === this) {
  35533. result.push(mesh);
  35534. }
  35535. }
  35536. return result;
  35537. };
  35538. /**
  35539. * Force shader compilation
  35540. * @param mesh defines the mesh associated with this material
  35541. * @param onCompiled defines a function to execute once the material is compiled
  35542. * @param options defines the options to configure the compilation
  35543. */
  35544. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35545. var _this = this;
  35546. var localOptions = __assign({ clipPlane: false }, options);
  35547. var subMesh = new BABYLON.BaseSubMesh();
  35548. var scene = this.getScene();
  35549. var checkReady = function () {
  35550. if (!_this._scene || !_this._scene.getEngine()) {
  35551. return;
  35552. }
  35553. if (subMesh._materialDefines) {
  35554. subMesh._materialDefines._renderId = -1;
  35555. }
  35556. var clipPlaneState = scene.clipPlane;
  35557. if (localOptions.clipPlane) {
  35558. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35559. }
  35560. if (_this.storeEffectOnSubMeshes) {
  35561. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35562. if (onCompiled) {
  35563. onCompiled(_this);
  35564. }
  35565. }
  35566. else {
  35567. setTimeout(checkReady, 16);
  35568. }
  35569. }
  35570. else {
  35571. if (_this.isReady(mesh)) {
  35572. if (onCompiled) {
  35573. onCompiled(_this);
  35574. }
  35575. }
  35576. else {
  35577. setTimeout(checkReady, 16);
  35578. }
  35579. }
  35580. if (localOptions.clipPlane) {
  35581. scene.clipPlane = clipPlaneState;
  35582. }
  35583. };
  35584. checkReady();
  35585. };
  35586. /**
  35587. * Force shader compilation
  35588. * @param mesh defines the mesh that will use this material
  35589. * @param options defines additional options for compiling the shaders
  35590. * @returns a promise that resolves when the compilation completes
  35591. */
  35592. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35593. var _this = this;
  35594. return new Promise(function (resolve) {
  35595. _this.forceCompilation(mesh, function () {
  35596. resolve();
  35597. }, options);
  35598. });
  35599. };
  35600. /**
  35601. * Marks a define in the material to indicate that it needs to be re-computed
  35602. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35603. */
  35604. Material.prototype.markAsDirty = function (flag) {
  35605. if (flag & Material.TextureDirtyFlag) {
  35606. this._markAllSubMeshesAsTexturesDirty();
  35607. }
  35608. if (flag & Material.LightDirtyFlag) {
  35609. this._markAllSubMeshesAsLightsDirty();
  35610. }
  35611. if (flag & Material.FresnelDirtyFlag) {
  35612. this._markAllSubMeshesAsFresnelDirty();
  35613. }
  35614. if (flag & Material.AttributesDirtyFlag) {
  35615. this._markAllSubMeshesAsAttributesDirty();
  35616. }
  35617. if (flag & Material.MiscDirtyFlag) {
  35618. this._markAllSubMeshesAsMiscDirty();
  35619. }
  35620. this.getScene().resetCachedMaterial();
  35621. };
  35622. /**
  35623. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35624. * @param func defines a function which checks material defines against the submeshes
  35625. */
  35626. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35627. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35628. var mesh = _a[_i];
  35629. if (!mesh.subMeshes) {
  35630. continue;
  35631. }
  35632. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35633. var subMesh = _c[_b];
  35634. if (subMesh.getMaterial() !== this) {
  35635. continue;
  35636. }
  35637. if (!subMesh._materialDefines) {
  35638. continue;
  35639. }
  35640. func(subMesh._materialDefines);
  35641. }
  35642. }
  35643. };
  35644. /**
  35645. * Indicates that image processing needs to be re-calculated for all submeshes
  35646. */
  35647. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35648. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35649. };
  35650. /**
  35651. * Indicates that textures need to be re-calculated for all submeshes
  35652. */
  35653. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35654. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35655. };
  35656. /**
  35657. * Indicates that fresnel needs to be re-calculated for all submeshes
  35658. */
  35659. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35660. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35661. };
  35662. /**
  35663. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35664. */
  35665. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35666. this._markAllSubMeshesAsDirty(function (defines) {
  35667. defines.markAsFresnelDirty();
  35668. defines.markAsMiscDirty();
  35669. });
  35670. };
  35671. /**
  35672. * Indicates that lights need to be re-calculated for all submeshes
  35673. */
  35674. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35675. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35676. };
  35677. /**
  35678. * Indicates that attributes need to be re-calculated for all submeshes
  35679. */
  35680. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35681. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35682. };
  35683. /**
  35684. * Indicates that misc needs to be re-calculated for all submeshes
  35685. */
  35686. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35687. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35688. };
  35689. /**
  35690. * Indicates that textures and misc need to be re-calculated for all submeshes
  35691. */
  35692. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35693. this._markAllSubMeshesAsDirty(function (defines) {
  35694. defines.markAsTexturesDirty();
  35695. defines.markAsMiscDirty();
  35696. });
  35697. };
  35698. /**
  35699. * Disposes the material
  35700. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35701. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35702. */
  35703. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35704. // Animations
  35705. this.getScene().stopAnimation(this);
  35706. this.getScene().freeProcessedMaterials();
  35707. // Remove from scene
  35708. var index = this._scene.materials.indexOf(this);
  35709. if (index >= 0) {
  35710. this._scene.materials.splice(index, 1);
  35711. }
  35712. // Remove from meshes
  35713. for (index = 0; index < this._scene.meshes.length; index++) {
  35714. var mesh = this._scene.meshes[index];
  35715. if (mesh.material === this) {
  35716. mesh.material = null;
  35717. if (mesh.geometry) {
  35718. var geometry = (mesh.geometry);
  35719. if (this.storeEffectOnSubMeshes) {
  35720. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35721. var subMesh = _a[_i];
  35722. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35723. if (forceDisposeEffect && subMesh._materialEffect) {
  35724. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35725. }
  35726. }
  35727. }
  35728. else {
  35729. geometry._releaseVertexArrayObject(this._effect);
  35730. }
  35731. }
  35732. }
  35733. }
  35734. this._uniformBuffer.dispose();
  35735. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35736. if (forceDisposeEffect && this._effect) {
  35737. if (!this.storeEffectOnSubMeshes) {
  35738. this._scene.getEngine()._releaseEffect(this._effect);
  35739. }
  35740. this._effect = null;
  35741. }
  35742. // Callback
  35743. this.onDisposeObservable.notifyObservers(this);
  35744. this.onDisposeObservable.clear();
  35745. if (this._onBindObservable) {
  35746. this._onBindObservable.clear();
  35747. }
  35748. if (this._onUnBindObservable) {
  35749. this._onUnBindObservable.clear();
  35750. }
  35751. };
  35752. /**
  35753. * Serializes this material
  35754. * @returns the serialized material object
  35755. */
  35756. Material.prototype.serialize = function () {
  35757. return BABYLON.SerializationHelper.Serialize(this);
  35758. };
  35759. /**
  35760. * Creates a MultiMaterial from parsed MultiMaterial data.
  35761. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35762. * @param scene defines the hosting scene
  35763. * @returns a new MultiMaterial
  35764. */
  35765. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35766. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35767. multiMaterial.id = parsedMultiMaterial.id;
  35768. if (BABYLON.Tags) {
  35769. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35770. }
  35771. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35772. var subMatId = parsedMultiMaterial.materials[matIndex];
  35773. if (subMatId) {
  35774. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35775. }
  35776. else {
  35777. multiMaterial.subMaterials.push(null);
  35778. }
  35779. }
  35780. return multiMaterial;
  35781. };
  35782. /**
  35783. * Creates a material from parsed material data
  35784. * @param parsedMaterial defines parsed material data
  35785. * @param scene defines the hosting scene
  35786. * @param rootUrl defines the root URL to use to load textures
  35787. * @returns a new material
  35788. */
  35789. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35790. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35791. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35792. }
  35793. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35794. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35795. if (!BABYLON.LegacyPBRMaterial) {
  35796. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35797. return;
  35798. }
  35799. }
  35800. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35801. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35802. };
  35803. // Triangle views
  35804. Material._TriangleFillMode = 0;
  35805. Material._WireFrameFillMode = 1;
  35806. Material._PointFillMode = 2;
  35807. // Draw modes
  35808. Material._PointListDrawMode = 3;
  35809. Material._LineListDrawMode = 4;
  35810. Material._LineLoopDrawMode = 5;
  35811. Material._LineStripDrawMode = 6;
  35812. Material._TriangleStripDrawMode = 7;
  35813. Material._TriangleFanDrawMode = 8;
  35814. /**
  35815. * Stores the clock-wise side orientation
  35816. */
  35817. Material._ClockWiseSideOrientation = 0;
  35818. /**
  35819. * Stores the counter clock-wise side orientation
  35820. */
  35821. Material._CounterClockWiseSideOrientation = 1;
  35822. /**
  35823. * The dirty texture flag value
  35824. */
  35825. Material._TextureDirtyFlag = 1;
  35826. /**
  35827. * The dirty light flag value
  35828. */
  35829. Material._LightDirtyFlag = 2;
  35830. /**
  35831. * The dirty fresnel flag value
  35832. */
  35833. Material._FresnelDirtyFlag = 4;
  35834. /**
  35835. * The dirty attribute flag value
  35836. */
  35837. Material._AttributesDirtyFlag = 8;
  35838. /**
  35839. * The dirty misc flag value
  35840. */
  35841. Material._MiscDirtyFlag = 16;
  35842. __decorate([
  35843. BABYLON.serialize()
  35844. ], Material.prototype, "id", void 0);
  35845. __decorate([
  35846. BABYLON.serialize()
  35847. ], Material.prototype, "uniqueId", void 0);
  35848. __decorate([
  35849. BABYLON.serialize()
  35850. ], Material.prototype, "name", void 0);
  35851. __decorate([
  35852. BABYLON.serialize()
  35853. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35854. __decorate([
  35855. BABYLON.serialize()
  35856. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35857. __decorate([
  35858. BABYLON.serialize()
  35859. ], Material.prototype, "state", void 0);
  35860. __decorate([
  35861. BABYLON.serialize("alpha")
  35862. ], Material.prototype, "_alpha", void 0);
  35863. __decorate([
  35864. BABYLON.serialize("backFaceCulling")
  35865. ], Material.prototype, "_backFaceCulling", void 0);
  35866. __decorate([
  35867. BABYLON.serialize()
  35868. ], Material.prototype, "sideOrientation", void 0);
  35869. __decorate([
  35870. BABYLON.serialize("alphaMode")
  35871. ], Material.prototype, "_alphaMode", void 0);
  35872. __decorate([
  35873. BABYLON.serialize()
  35874. ], Material.prototype, "_needDepthPrePass", void 0);
  35875. __decorate([
  35876. BABYLON.serialize()
  35877. ], Material.prototype, "disableDepthWrite", void 0);
  35878. __decorate([
  35879. BABYLON.serialize()
  35880. ], Material.prototype, "forceDepthWrite", void 0);
  35881. __decorate([
  35882. BABYLON.serialize()
  35883. ], Material.prototype, "separateCullingPass", void 0);
  35884. __decorate([
  35885. BABYLON.serialize("fogEnabled")
  35886. ], Material.prototype, "_fogEnabled", void 0);
  35887. __decorate([
  35888. BABYLON.serialize()
  35889. ], Material.prototype, "pointSize", void 0);
  35890. __decorate([
  35891. BABYLON.serialize()
  35892. ], Material.prototype, "zOffset", void 0);
  35893. __decorate([
  35894. BABYLON.serialize()
  35895. ], Material.prototype, "wireframe", null);
  35896. __decorate([
  35897. BABYLON.serialize()
  35898. ], Material.prototype, "pointsCloud", null);
  35899. __decorate([
  35900. BABYLON.serialize()
  35901. ], Material.prototype, "fillMode", null);
  35902. return Material;
  35903. }());
  35904. BABYLON.Material = Material;
  35905. })(BABYLON || (BABYLON = {}));
  35906. //# sourceMappingURL=babylon.material.js.map
  35907. var BABYLON;
  35908. (function (BABYLON) {
  35909. var UniformBuffer = /** @class */ (function () {
  35910. /**
  35911. * Uniform buffer objects.
  35912. *
  35913. * Handles blocks of uniform on the GPU.
  35914. *
  35915. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35916. *
  35917. * For more information, please refer to :
  35918. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35919. */
  35920. function UniformBuffer(engine, data, dynamic) {
  35921. this._engine = engine;
  35922. this._noUBO = !engine.supportsUniformBuffers;
  35923. this._dynamic = dynamic;
  35924. this._data = data || [];
  35925. this._uniformLocations = {};
  35926. this._uniformSizes = {};
  35927. this._uniformLocationPointer = 0;
  35928. this._needSync = false;
  35929. if (this._noUBO) {
  35930. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35931. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35932. this.updateFloat = this._updateFloatForEffect;
  35933. this.updateFloat2 = this._updateFloat2ForEffect;
  35934. this.updateFloat3 = this._updateFloat3ForEffect;
  35935. this.updateFloat4 = this._updateFloat4ForEffect;
  35936. this.updateMatrix = this._updateMatrixForEffect;
  35937. this.updateVector3 = this._updateVector3ForEffect;
  35938. this.updateVector4 = this._updateVector4ForEffect;
  35939. this.updateColor3 = this._updateColor3ForEffect;
  35940. this.updateColor4 = this._updateColor4ForEffect;
  35941. }
  35942. else {
  35943. this._engine._uniformBuffers.push(this);
  35944. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35945. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35946. this.updateFloat = this._updateFloatForUniform;
  35947. this.updateFloat2 = this._updateFloat2ForUniform;
  35948. this.updateFloat3 = this._updateFloat3ForUniform;
  35949. this.updateFloat4 = this._updateFloat4ForUniform;
  35950. this.updateMatrix = this._updateMatrixForUniform;
  35951. this.updateVector3 = this._updateVector3ForUniform;
  35952. this.updateVector4 = this._updateVector4ForUniform;
  35953. this.updateColor3 = this._updateColor3ForUniform;
  35954. this.updateColor4 = this._updateColor4ForUniform;
  35955. }
  35956. }
  35957. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35958. // Properties
  35959. /**
  35960. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35961. * or just falling back on setUniformXXX calls.
  35962. */
  35963. get: function () {
  35964. return !this._noUBO;
  35965. },
  35966. enumerable: true,
  35967. configurable: true
  35968. });
  35969. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35970. /**
  35971. * Indicates if the WebGL underlying uniform buffer is in sync
  35972. * with the javascript cache data.
  35973. */
  35974. get: function () {
  35975. return !this._needSync;
  35976. },
  35977. enumerable: true,
  35978. configurable: true
  35979. });
  35980. /**
  35981. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35982. * Also, a dynamic UniformBuffer will disable cache verification and always
  35983. * update the underlying WebGL uniform buffer to the GPU.
  35984. */
  35985. UniformBuffer.prototype.isDynamic = function () {
  35986. return this._dynamic !== undefined;
  35987. };
  35988. /**
  35989. * The data cache on JS side.
  35990. */
  35991. UniformBuffer.prototype.getData = function () {
  35992. return this._bufferData;
  35993. };
  35994. /**
  35995. * The underlying WebGL Uniform buffer.
  35996. */
  35997. UniformBuffer.prototype.getBuffer = function () {
  35998. return this._buffer;
  35999. };
  36000. /**
  36001. * std140 layout specifies how to align data within an UBO structure.
  36002. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36003. * for specs.
  36004. */
  36005. UniformBuffer.prototype._fillAlignment = function (size) {
  36006. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36007. // and 4x4 matrices
  36008. // TODO : change if other types are used
  36009. var alignment;
  36010. if (size <= 2) {
  36011. alignment = size;
  36012. }
  36013. else {
  36014. alignment = 4;
  36015. }
  36016. if ((this._uniformLocationPointer % alignment) !== 0) {
  36017. var oldPointer = this._uniformLocationPointer;
  36018. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36019. var diff = this._uniformLocationPointer - oldPointer;
  36020. for (var i = 0; i < diff; i++) {
  36021. this._data.push(0);
  36022. }
  36023. }
  36024. };
  36025. /**
  36026. * Adds an uniform in the buffer.
  36027. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36028. * for the layout to be correct !
  36029. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36030. * @param {number|number[]} size Data size, or data directly.
  36031. */
  36032. UniformBuffer.prototype.addUniform = function (name, size) {
  36033. if (this._noUBO) {
  36034. return;
  36035. }
  36036. if (this._uniformLocations[name] !== undefined) {
  36037. // Already existing uniform
  36038. return;
  36039. }
  36040. // This function must be called in the order of the shader layout !
  36041. // size can be the size of the uniform, or data directly
  36042. var data;
  36043. if (size instanceof Array) {
  36044. data = size;
  36045. size = data.length;
  36046. }
  36047. else {
  36048. size = size;
  36049. data = [];
  36050. // Fill with zeros
  36051. for (var i = 0; i < size; i++) {
  36052. data.push(0);
  36053. }
  36054. }
  36055. this._fillAlignment(size);
  36056. this._uniformSizes[name] = size;
  36057. this._uniformLocations[name] = this._uniformLocationPointer;
  36058. this._uniformLocationPointer += size;
  36059. for (var i = 0; i < size; i++) {
  36060. this._data.push(data[i]);
  36061. }
  36062. this._needSync = true;
  36063. };
  36064. /**
  36065. * Wrapper for addUniform.
  36066. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36067. * @param {Matrix} mat A 4x4 matrix.
  36068. */
  36069. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36070. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36071. };
  36072. /**
  36073. * Wrapper for addUniform.
  36074. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36075. * @param {number} x
  36076. * @param {number} y
  36077. */
  36078. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36079. var temp = [x, y];
  36080. this.addUniform(name, temp);
  36081. };
  36082. /**
  36083. * Wrapper for addUniform.
  36084. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36085. * @param {number} x
  36086. * @param {number} y
  36087. * @param {number} z
  36088. */
  36089. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36090. var temp = [x, y, z];
  36091. this.addUniform(name, temp);
  36092. };
  36093. /**
  36094. * Wrapper for addUniform.
  36095. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36096. * @param {Color3} color
  36097. */
  36098. UniformBuffer.prototype.addColor3 = function (name, color) {
  36099. var temp = new Array();
  36100. color.toArray(temp);
  36101. this.addUniform(name, temp);
  36102. };
  36103. /**
  36104. * Wrapper for addUniform.
  36105. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36106. * @param {Color3} color
  36107. * @param {number} alpha
  36108. */
  36109. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36110. var temp = new Array();
  36111. color.toArray(temp);
  36112. temp.push(alpha);
  36113. this.addUniform(name, temp);
  36114. };
  36115. /**
  36116. * Wrapper for addUniform.
  36117. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36118. * @param {Vector3} vector
  36119. */
  36120. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36121. var temp = new Array();
  36122. vector.toArray(temp);
  36123. this.addUniform(name, temp);
  36124. };
  36125. /**
  36126. * Wrapper for addUniform.
  36127. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36128. */
  36129. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36130. this.addUniform(name, 12);
  36131. };
  36132. /**
  36133. * Wrapper for addUniform.
  36134. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36135. */
  36136. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36137. this.addUniform(name, 8);
  36138. };
  36139. /**
  36140. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36141. */
  36142. UniformBuffer.prototype.create = function () {
  36143. if (this._noUBO) {
  36144. return;
  36145. }
  36146. if (this._buffer) {
  36147. return; // nothing to do
  36148. }
  36149. // See spec, alignment must be filled as a vec4
  36150. this._fillAlignment(4);
  36151. this._bufferData = new Float32Array(this._data);
  36152. this._rebuild();
  36153. this._needSync = true;
  36154. };
  36155. /** @hidden */
  36156. UniformBuffer.prototype._rebuild = function () {
  36157. if (this._noUBO) {
  36158. return;
  36159. }
  36160. if (this._dynamic) {
  36161. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36162. }
  36163. else {
  36164. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36165. }
  36166. };
  36167. /**
  36168. * Updates the WebGL Uniform Buffer on the GPU.
  36169. * If the `dynamic` flag is set to true, no cache comparison is done.
  36170. * Otherwise, the buffer will be updated only if the cache differs.
  36171. */
  36172. UniformBuffer.prototype.update = function () {
  36173. if (!this._buffer) {
  36174. this.create();
  36175. return;
  36176. }
  36177. if (!this._dynamic && !this._needSync) {
  36178. return;
  36179. }
  36180. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36181. this._needSync = false;
  36182. };
  36183. /**
  36184. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36185. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36186. * @param {number[]|Float32Array} data Flattened data
  36187. * @param {number} size Size of the data.
  36188. */
  36189. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36190. var location = this._uniformLocations[uniformName];
  36191. if (location === undefined) {
  36192. if (this._buffer) {
  36193. // Cannot add an uniform if the buffer is already created
  36194. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36195. return;
  36196. }
  36197. this.addUniform(uniformName, size);
  36198. location = this._uniformLocations[uniformName];
  36199. }
  36200. if (!this._buffer) {
  36201. this.create();
  36202. }
  36203. if (!this._dynamic) {
  36204. // Cache for static uniform buffers
  36205. var changed = false;
  36206. for (var i = 0; i < size; i++) {
  36207. if (this._bufferData[location + i] !== data[i]) {
  36208. changed = true;
  36209. this._bufferData[location + i] = data[i];
  36210. }
  36211. }
  36212. this._needSync = this._needSync || changed;
  36213. }
  36214. else {
  36215. // No cache for dynamic
  36216. for (var i = 0; i < size; i++) {
  36217. this._bufferData[location + i] = data[i];
  36218. }
  36219. }
  36220. };
  36221. // Update methods
  36222. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36223. // To match std140, matrix must be realigned
  36224. for (var i = 0; i < 3; i++) {
  36225. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36226. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36227. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36228. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36229. }
  36230. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36231. };
  36232. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36233. this._currentEffect.setMatrix3x3(name, matrix);
  36234. };
  36235. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36236. this._currentEffect.setMatrix2x2(name, matrix);
  36237. };
  36238. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36239. // To match std140, matrix must be realigned
  36240. for (var i = 0; i < 2; i++) {
  36241. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36242. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36243. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36244. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36245. }
  36246. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36247. };
  36248. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36249. this._currentEffect.setFloat(name, x);
  36250. };
  36251. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36252. UniformBuffer._tempBuffer[0] = x;
  36253. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36254. };
  36255. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36256. if (suffix === void 0) { suffix = ""; }
  36257. this._currentEffect.setFloat2(name + suffix, x, y);
  36258. };
  36259. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36260. if (suffix === void 0) { suffix = ""; }
  36261. UniformBuffer._tempBuffer[0] = x;
  36262. UniformBuffer._tempBuffer[1] = y;
  36263. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36264. };
  36265. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36266. if (suffix === void 0) { suffix = ""; }
  36267. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36268. };
  36269. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36270. if (suffix === void 0) { suffix = ""; }
  36271. UniformBuffer._tempBuffer[0] = x;
  36272. UniformBuffer._tempBuffer[1] = y;
  36273. UniformBuffer._tempBuffer[2] = z;
  36274. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36275. };
  36276. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36277. if (suffix === void 0) { suffix = ""; }
  36278. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36279. };
  36280. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36281. if (suffix === void 0) { suffix = ""; }
  36282. UniformBuffer._tempBuffer[0] = x;
  36283. UniformBuffer._tempBuffer[1] = y;
  36284. UniformBuffer._tempBuffer[2] = z;
  36285. UniformBuffer._tempBuffer[3] = w;
  36286. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36287. };
  36288. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36289. this._currentEffect.setMatrix(name, mat);
  36290. };
  36291. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36292. this.updateUniform(name, mat.toArray(), 16);
  36293. };
  36294. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36295. this._currentEffect.setVector3(name, vector);
  36296. };
  36297. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36298. vector.toArray(UniformBuffer._tempBuffer);
  36299. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36300. };
  36301. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36302. this._currentEffect.setVector4(name, vector);
  36303. };
  36304. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36305. vector.toArray(UniformBuffer._tempBuffer);
  36306. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36307. };
  36308. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36309. if (suffix === void 0) { suffix = ""; }
  36310. this._currentEffect.setColor3(name + suffix, color);
  36311. };
  36312. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36313. if (suffix === void 0) { suffix = ""; }
  36314. color.toArray(UniformBuffer._tempBuffer);
  36315. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36316. };
  36317. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36318. if (suffix === void 0) { suffix = ""; }
  36319. this._currentEffect.setColor4(name + suffix, color, alpha);
  36320. };
  36321. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36322. if (suffix === void 0) { suffix = ""; }
  36323. color.toArray(UniformBuffer._tempBuffer);
  36324. UniformBuffer._tempBuffer[3] = alpha;
  36325. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36326. };
  36327. /**
  36328. * Sets a sampler uniform on the effect.
  36329. * @param {string} name Name of the sampler.
  36330. * @param {Texture} texture
  36331. */
  36332. UniformBuffer.prototype.setTexture = function (name, texture) {
  36333. this._currentEffect.setTexture(name, texture);
  36334. };
  36335. /**
  36336. * Directly updates the value of the uniform in the cache AND on the GPU.
  36337. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36338. * @param {number[]|Float32Array} data Flattened data
  36339. */
  36340. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36341. this.updateUniform(uniformName, data, data.length);
  36342. this.update();
  36343. };
  36344. /**
  36345. * Binds this uniform buffer to an effect.
  36346. * @param {Effect} effect
  36347. * @param {string} name Name of the uniform block in the shader.
  36348. */
  36349. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36350. this._currentEffect = effect;
  36351. if (this._noUBO || !this._buffer) {
  36352. return;
  36353. }
  36354. effect.bindUniformBuffer(this._buffer, name);
  36355. };
  36356. /**
  36357. * Disposes the uniform buffer.
  36358. */
  36359. UniformBuffer.prototype.dispose = function () {
  36360. if (this._noUBO) {
  36361. return;
  36362. }
  36363. var index = this._engine._uniformBuffers.indexOf(this);
  36364. if (index !== -1) {
  36365. this._engine._uniformBuffers.splice(index, 1);
  36366. }
  36367. if (!this._buffer) {
  36368. return;
  36369. }
  36370. if (this._engine._releaseBuffer(this._buffer)) {
  36371. this._buffer = null;
  36372. }
  36373. };
  36374. // Pool for avoiding memory leaks
  36375. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36376. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36377. return UniformBuffer;
  36378. }());
  36379. BABYLON.UniformBuffer = UniformBuffer;
  36380. })(BABYLON || (BABYLON = {}));
  36381. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36382. var BABYLON;
  36383. (function (BABYLON) {
  36384. /**
  36385. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36386. */
  36387. var VertexData = /** @class */ (function () {
  36388. function VertexData() {
  36389. }
  36390. /**
  36391. * Uses the passed data array to set the set the values for the specified kind of data
  36392. * @param data a linear array of floating numbers
  36393. * @param kind the type of data that is being set, eg positions, colors etc
  36394. */
  36395. VertexData.prototype.set = function (data, kind) {
  36396. switch (kind) {
  36397. case BABYLON.VertexBuffer.PositionKind:
  36398. this.positions = data;
  36399. break;
  36400. case BABYLON.VertexBuffer.NormalKind:
  36401. this.normals = data;
  36402. break;
  36403. case BABYLON.VertexBuffer.TangentKind:
  36404. this.tangents = data;
  36405. break;
  36406. case BABYLON.VertexBuffer.UVKind:
  36407. this.uvs = data;
  36408. break;
  36409. case BABYLON.VertexBuffer.UV2Kind:
  36410. this.uvs2 = data;
  36411. break;
  36412. case BABYLON.VertexBuffer.UV3Kind:
  36413. this.uvs3 = data;
  36414. break;
  36415. case BABYLON.VertexBuffer.UV4Kind:
  36416. this.uvs4 = data;
  36417. break;
  36418. case BABYLON.VertexBuffer.UV5Kind:
  36419. this.uvs5 = data;
  36420. break;
  36421. case BABYLON.VertexBuffer.UV6Kind:
  36422. this.uvs6 = data;
  36423. break;
  36424. case BABYLON.VertexBuffer.ColorKind:
  36425. this.colors = data;
  36426. break;
  36427. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36428. this.matricesIndices = data;
  36429. break;
  36430. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36431. this.matricesWeights = data;
  36432. break;
  36433. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36434. this.matricesIndicesExtra = data;
  36435. break;
  36436. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36437. this.matricesWeightsExtra = data;
  36438. break;
  36439. }
  36440. };
  36441. /**
  36442. * Associates the vertexData to the passed Mesh.
  36443. * Sets it as updatable or not (default `false`)
  36444. * @param mesh the mesh the vertexData is applied to
  36445. * @param updatable when used and having the value true allows new data to update the vertexData
  36446. * @returns the VertexData
  36447. */
  36448. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36449. this._applyTo(mesh, updatable);
  36450. return this;
  36451. };
  36452. /**
  36453. * Associates the vertexData to the passed Geometry.
  36454. * Sets it as updatable or not (default `false`)
  36455. * @param geometry the geometry the vertexData is applied to
  36456. * @param updatable when used and having the value true allows new data to update the vertexData
  36457. * @returns VertexData
  36458. */
  36459. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36460. this._applyTo(geometry, updatable);
  36461. return this;
  36462. };
  36463. /**
  36464. * Updates the associated mesh
  36465. * @param mesh the mesh to be updated
  36466. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36467. * @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
  36468. * @returns VertexData
  36469. */
  36470. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36471. this._update(mesh);
  36472. return this;
  36473. };
  36474. /**
  36475. * Updates the associated geometry
  36476. * @param geometry the geometry to be updated
  36477. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36478. * @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
  36479. * @returns VertexData.
  36480. */
  36481. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36482. this._update(geometry);
  36483. return this;
  36484. };
  36485. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36486. if (updatable === void 0) { updatable = false; }
  36487. if (this.positions) {
  36488. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36489. }
  36490. if (this.normals) {
  36491. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36492. }
  36493. if (this.tangents) {
  36494. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36495. }
  36496. if (this.uvs) {
  36497. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36498. }
  36499. if (this.uvs2) {
  36500. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36501. }
  36502. if (this.uvs3) {
  36503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36504. }
  36505. if (this.uvs4) {
  36506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36507. }
  36508. if (this.uvs5) {
  36509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36510. }
  36511. if (this.uvs6) {
  36512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36513. }
  36514. if (this.colors) {
  36515. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36516. }
  36517. if (this.matricesIndices) {
  36518. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36519. }
  36520. if (this.matricesWeights) {
  36521. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36522. }
  36523. if (this.matricesIndicesExtra) {
  36524. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36525. }
  36526. if (this.matricesWeightsExtra) {
  36527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36528. }
  36529. if (this.indices) {
  36530. meshOrGeometry.setIndices(this.indices, null, updatable);
  36531. }
  36532. else {
  36533. meshOrGeometry.setIndices([], null);
  36534. }
  36535. return this;
  36536. };
  36537. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36538. if (this.positions) {
  36539. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36540. }
  36541. if (this.normals) {
  36542. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36543. }
  36544. if (this.tangents) {
  36545. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36546. }
  36547. if (this.uvs) {
  36548. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36549. }
  36550. if (this.uvs2) {
  36551. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36552. }
  36553. if (this.uvs3) {
  36554. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36555. }
  36556. if (this.uvs4) {
  36557. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36558. }
  36559. if (this.uvs5) {
  36560. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36561. }
  36562. if (this.uvs6) {
  36563. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36564. }
  36565. if (this.colors) {
  36566. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36567. }
  36568. if (this.matricesIndices) {
  36569. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36570. }
  36571. if (this.matricesWeights) {
  36572. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36573. }
  36574. if (this.matricesIndicesExtra) {
  36575. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36576. }
  36577. if (this.matricesWeightsExtra) {
  36578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36579. }
  36580. if (this.indices) {
  36581. meshOrGeometry.setIndices(this.indices, null);
  36582. }
  36583. return this;
  36584. };
  36585. /**
  36586. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36587. * @param matrix the transforming matrix
  36588. * @returns the VertexData
  36589. */
  36590. VertexData.prototype.transform = function (matrix) {
  36591. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36592. var transformed = BABYLON.Vector3.Zero();
  36593. var index;
  36594. if (this.positions) {
  36595. var position = BABYLON.Vector3.Zero();
  36596. for (index = 0; index < this.positions.length; index += 3) {
  36597. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36598. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36599. this.positions[index] = transformed.x;
  36600. this.positions[index + 1] = transformed.y;
  36601. this.positions[index + 2] = transformed.z;
  36602. }
  36603. }
  36604. if (this.normals) {
  36605. var normal = BABYLON.Vector3.Zero();
  36606. for (index = 0; index < this.normals.length; index += 3) {
  36607. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36608. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36609. this.normals[index] = transformed.x;
  36610. this.normals[index + 1] = transformed.y;
  36611. this.normals[index + 2] = transformed.z;
  36612. }
  36613. }
  36614. if (this.tangents) {
  36615. var tangent = BABYLON.Vector4.Zero();
  36616. var tangentTransformed = BABYLON.Vector4.Zero();
  36617. for (index = 0; index < this.tangents.length; index += 4) {
  36618. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36619. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36620. this.tangents[index] = tangentTransformed.x;
  36621. this.tangents[index + 1] = tangentTransformed.y;
  36622. this.tangents[index + 2] = tangentTransformed.z;
  36623. this.tangents[index + 3] = tangentTransformed.w;
  36624. }
  36625. }
  36626. if (flip && this.indices) {
  36627. for (index = 0; index < this.indices.length; index += 3) {
  36628. var tmp = this.indices[index + 1];
  36629. this.indices[index + 1] = this.indices[index + 2];
  36630. this.indices[index + 2] = tmp;
  36631. }
  36632. }
  36633. return this;
  36634. };
  36635. /**
  36636. * Merges the passed VertexData into the current one
  36637. * @param other the VertexData to be merged into the current one
  36638. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36639. * @returns the modified VertexData
  36640. */
  36641. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36642. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36643. this._validate();
  36644. other._validate();
  36645. if (!this.normals !== !other.normals ||
  36646. !this.tangents !== !other.tangents ||
  36647. !this.uvs !== !other.uvs ||
  36648. !this.uvs2 !== !other.uvs2 ||
  36649. !this.uvs3 !== !other.uvs3 ||
  36650. !this.uvs4 !== !other.uvs4 ||
  36651. !this.uvs5 !== !other.uvs5 ||
  36652. !this.uvs6 !== !other.uvs6 ||
  36653. !this.colors !== !other.colors ||
  36654. !this.matricesIndices !== !other.matricesIndices ||
  36655. !this.matricesWeights !== !other.matricesWeights ||
  36656. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36657. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36658. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36659. }
  36660. if (other.indices) {
  36661. if (!this.indices) {
  36662. this.indices = [];
  36663. }
  36664. var offset = this.positions ? this.positions.length / 3 : 0;
  36665. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36666. if (isSrcTypedArray) {
  36667. var len = this.indices.length + other.indices.length;
  36668. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36669. temp.set(this.indices);
  36670. var decal = this.indices.length;
  36671. for (var index = 0; index < other.indices.length; index++) {
  36672. temp[decal + index] = other.indices[index] + offset;
  36673. }
  36674. this.indices = temp;
  36675. }
  36676. else {
  36677. for (var index = 0; index < other.indices.length; index++) {
  36678. this.indices.push(other.indices[index] + offset);
  36679. }
  36680. }
  36681. }
  36682. this.positions = this._mergeElement(this.positions, other.positions);
  36683. this.normals = this._mergeElement(this.normals, other.normals);
  36684. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36685. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36686. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36687. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36688. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36689. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36690. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36691. this.colors = this._mergeElement(this.colors, other.colors);
  36692. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36693. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36694. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36695. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36696. return this;
  36697. };
  36698. VertexData.prototype._mergeElement = function (source, other) {
  36699. if (!source) {
  36700. return other;
  36701. }
  36702. if (!other) {
  36703. return source;
  36704. }
  36705. var len = other.length + source.length;
  36706. var isSrcTypedArray = source instanceof Float32Array;
  36707. var isOthTypedArray = other instanceof Float32Array;
  36708. // use non-loop method when the source is Float32Array
  36709. if (isSrcTypedArray) {
  36710. var ret32 = new Float32Array(len);
  36711. ret32.set(source);
  36712. ret32.set(other, source.length);
  36713. return ret32;
  36714. // source is number[], when other is also use concat
  36715. }
  36716. else if (!isOthTypedArray) {
  36717. return source.concat(other);
  36718. // source is a number[], but other is a Float32Array, loop required
  36719. }
  36720. else {
  36721. var ret = source.slice(0); // copy source to a separate array
  36722. for (var i = 0, len = other.length; i < len; i++) {
  36723. ret.push(other[i]);
  36724. }
  36725. return ret;
  36726. }
  36727. };
  36728. VertexData.prototype._validate = function () {
  36729. if (!this.positions) {
  36730. throw new Error("Positions are required");
  36731. }
  36732. var getElementCount = function (kind, values) {
  36733. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36734. if ((values.length % stride) !== 0) {
  36735. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36736. }
  36737. return values.length / stride;
  36738. };
  36739. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36740. var validateElementCount = function (kind, values) {
  36741. var elementCount = getElementCount(kind, values);
  36742. if (elementCount !== positionsElementCount) {
  36743. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36744. }
  36745. };
  36746. if (this.normals)
  36747. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36748. if (this.tangents)
  36749. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36750. if (this.uvs)
  36751. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36752. if (this.uvs2)
  36753. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36754. if (this.uvs3)
  36755. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36756. if (this.uvs4)
  36757. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36758. if (this.uvs5)
  36759. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36760. if (this.uvs6)
  36761. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36762. if (this.colors)
  36763. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36764. if (this.matricesIndices)
  36765. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36766. if (this.matricesWeights)
  36767. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36768. if (this.matricesIndicesExtra)
  36769. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36770. if (this.matricesWeightsExtra)
  36771. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36772. };
  36773. /**
  36774. * Serializes the VertexData
  36775. * @returns a serialized object
  36776. */
  36777. VertexData.prototype.serialize = function () {
  36778. var serializationObject = this.serialize();
  36779. if (this.positions) {
  36780. serializationObject.positions = this.positions;
  36781. }
  36782. if (this.normals) {
  36783. serializationObject.normals = this.normals;
  36784. }
  36785. if (this.tangents) {
  36786. serializationObject.tangents = this.tangents;
  36787. }
  36788. if (this.uvs) {
  36789. serializationObject.uvs = this.uvs;
  36790. }
  36791. if (this.uvs2) {
  36792. serializationObject.uvs2 = this.uvs2;
  36793. }
  36794. if (this.uvs3) {
  36795. serializationObject.uvs3 = this.uvs3;
  36796. }
  36797. if (this.uvs4) {
  36798. serializationObject.uvs4 = this.uvs4;
  36799. }
  36800. if (this.uvs5) {
  36801. serializationObject.uvs5 = this.uvs5;
  36802. }
  36803. if (this.uvs6) {
  36804. serializationObject.uvs6 = this.uvs6;
  36805. }
  36806. if (this.colors) {
  36807. serializationObject.colors = this.colors;
  36808. }
  36809. if (this.matricesIndices) {
  36810. serializationObject.matricesIndices = this.matricesIndices;
  36811. serializationObject.matricesIndices._isExpanded = true;
  36812. }
  36813. if (this.matricesWeights) {
  36814. serializationObject.matricesWeights = this.matricesWeights;
  36815. }
  36816. if (this.matricesIndicesExtra) {
  36817. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36818. serializationObject.matricesIndicesExtra._isExpanded = true;
  36819. }
  36820. if (this.matricesWeightsExtra) {
  36821. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36822. }
  36823. serializationObject.indices = this.indices;
  36824. return serializationObject;
  36825. };
  36826. // Statics
  36827. /**
  36828. * Extracts the vertexData from a mesh
  36829. * @param mesh the mesh from which to extract the VertexData
  36830. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36831. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36832. * @returns the object VertexData associated to the passed mesh
  36833. */
  36834. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36835. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36836. };
  36837. /**
  36838. * Extracts the vertexData from the geometry
  36839. * @param geometry the geometry from which to extract the VertexData
  36840. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36841. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36842. * @returns the object VertexData associated to the passed mesh
  36843. */
  36844. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36845. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36846. };
  36847. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36848. var result = new VertexData();
  36849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36850. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36851. }
  36852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36853. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36854. }
  36855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36856. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36857. }
  36858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36859. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36860. }
  36861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36862. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36863. }
  36864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36865. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36866. }
  36867. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36868. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36869. }
  36870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36871. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36872. }
  36873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36874. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36875. }
  36876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36877. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36878. }
  36879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36880. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36881. }
  36882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36883. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36884. }
  36885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36886. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36887. }
  36888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36889. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36890. }
  36891. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36892. return result;
  36893. };
  36894. /**
  36895. * Creates the VertexData for a Ribbon
  36896. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36897. * * pathArray array of paths, each of which an array of successive Vector3
  36898. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36899. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36900. * * 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
  36901. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36902. * * 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)
  36903. * * 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)
  36904. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36905. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36906. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36907. * @returns the VertexData of the ribbon
  36908. */
  36909. VertexData.CreateRibbon = function (options) {
  36910. var pathArray = options.pathArray;
  36911. var closeArray = options.closeArray || false;
  36912. var closePath = options.closePath || false;
  36913. var invertUV = options.invertUV || false;
  36914. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36915. var offset = options.offset || defaultOffset;
  36916. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36917. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36918. var customUV = options.uvs;
  36919. var customColors = options.colors;
  36920. var positions = [];
  36921. var indices = [];
  36922. var normals = [];
  36923. var uvs = [];
  36924. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36925. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36926. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36927. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36928. var minlg; // minimal length among all paths from pathArray
  36929. var lg = []; // array of path lengths : nb of vertex per path
  36930. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36931. var p; // path iterator
  36932. var i; // point iterator
  36933. var j; // point iterator
  36934. // if single path in pathArray
  36935. if (pathArray.length < 2) {
  36936. var ar1 = [];
  36937. var ar2 = [];
  36938. for (i = 0; i < pathArray[0].length - offset; i++) {
  36939. ar1.push(pathArray[0][i]);
  36940. ar2.push(pathArray[0][i + offset]);
  36941. }
  36942. pathArray = [ar1, ar2];
  36943. }
  36944. // positions and horizontal distances (u)
  36945. var idc = 0;
  36946. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36947. var path;
  36948. var l;
  36949. minlg = pathArray[0].length;
  36950. var vectlg;
  36951. var dist;
  36952. for (p = 0; p < pathArray.length; p++) {
  36953. uTotalDistance[p] = 0;
  36954. us[p] = [0];
  36955. path = pathArray[p];
  36956. l = path.length;
  36957. minlg = (minlg < l) ? minlg : l;
  36958. j = 0;
  36959. while (j < l) {
  36960. positions.push(path[j].x, path[j].y, path[j].z);
  36961. if (j > 0) {
  36962. vectlg = path[j].subtract(path[j - 1]).length();
  36963. dist = vectlg + uTotalDistance[p];
  36964. us[p].push(dist);
  36965. uTotalDistance[p] = dist;
  36966. }
  36967. j++;
  36968. }
  36969. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36970. j--;
  36971. positions.push(path[0].x, path[0].y, path[0].z);
  36972. vectlg = path[j].subtract(path[0]).length();
  36973. dist = vectlg + uTotalDistance[p];
  36974. us[p].push(dist);
  36975. uTotalDistance[p] = dist;
  36976. }
  36977. lg[p] = l + closePathCorr;
  36978. idx[p] = idc;
  36979. idc += (l + closePathCorr);
  36980. }
  36981. // vertical distances (v)
  36982. var path1;
  36983. var path2;
  36984. var vertex1 = null;
  36985. var vertex2 = null;
  36986. for (i = 0; i < minlg + closePathCorr; i++) {
  36987. vTotalDistance[i] = 0;
  36988. vs[i] = [0];
  36989. for (p = 0; p < pathArray.length - 1; p++) {
  36990. path1 = pathArray[p];
  36991. path2 = pathArray[p + 1];
  36992. if (i === minlg) { // closePath
  36993. vertex1 = path1[0];
  36994. vertex2 = path2[0];
  36995. }
  36996. else {
  36997. vertex1 = path1[i];
  36998. vertex2 = path2[i];
  36999. }
  37000. vectlg = vertex2.subtract(vertex1).length();
  37001. dist = vectlg + vTotalDistance[i];
  37002. vs[i].push(dist);
  37003. vTotalDistance[i] = dist;
  37004. }
  37005. if (closeArray && vertex2 && vertex1) {
  37006. path1 = pathArray[p];
  37007. path2 = pathArray[0];
  37008. if (i === minlg) { // closePath
  37009. vertex2 = path2[0];
  37010. }
  37011. vectlg = vertex2.subtract(vertex1).length();
  37012. dist = vectlg + vTotalDistance[i];
  37013. vTotalDistance[i] = dist;
  37014. }
  37015. }
  37016. // uvs
  37017. var u;
  37018. var v;
  37019. if (customUV) {
  37020. for (p = 0; p < customUV.length; p++) {
  37021. uvs.push(customUV[p].x, customUV[p].y);
  37022. }
  37023. }
  37024. else {
  37025. for (p = 0; p < pathArray.length; p++) {
  37026. for (i = 0; i < minlg + closePathCorr; i++) {
  37027. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37028. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37029. if (invertUV) {
  37030. uvs.push(v, u);
  37031. }
  37032. else {
  37033. uvs.push(u, v);
  37034. }
  37035. }
  37036. }
  37037. }
  37038. // indices
  37039. p = 0; // path index
  37040. var pi = 0; // positions array index
  37041. var l1 = lg[p] - 1; // path1 length
  37042. var l2 = lg[p + 1] - 1; // path2 length
  37043. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37044. var shft = idx[1] - idx[0]; // shift
  37045. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37046. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37047. // 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
  37048. indices.push(pi, pi + shft, pi + 1);
  37049. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37050. pi += 1;
  37051. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37052. p++;
  37053. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37054. shft = idx[0] - idx[p];
  37055. l1 = lg[p] - 1;
  37056. l2 = lg[0] - 1;
  37057. }
  37058. else {
  37059. shft = idx[p + 1] - idx[p];
  37060. l1 = lg[p] - 1;
  37061. l2 = lg[p + 1] - 1;
  37062. }
  37063. pi = idx[p];
  37064. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37065. }
  37066. }
  37067. // normals
  37068. VertexData.ComputeNormals(positions, indices, normals);
  37069. if (closePath) { // update both the first and last vertex normals to their average value
  37070. var indexFirst = 0;
  37071. var indexLast = 0;
  37072. for (p = 0; p < pathArray.length; p++) {
  37073. indexFirst = idx[p] * 3;
  37074. if (p + 1 < pathArray.length) {
  37075. indexLast = (idx[p + 1] - 1) * 3;
  37076. }
  37077. else {
  37078. indexLast = normals.length - 3;
  37079. }
  37080. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37081. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37082. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37083. normals[indexLast] = normals[indexFirst];
  37084. normals[indexLast + 1] = normals[indexFirst + 1];
  37085. normals[indexLast + 2] = normals[indexFirst + 2];
  37086. }
  37087. }
  37088. // sides
  37089. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37090. // Colors
  37091. var colors = null;
  37092. if (customColors) {
  37093. colors = new Float32Array(customColors.length * 4);
  37094. for (var c = 0; c < customColors.length; c++) {
  37095. colors[c * 4] = customColors[c].r;
  37096. colors[c * 4 + 1] = customColors[c].g;
  37097. colors[c * 4 + 2] = customColors[c].b;
  37098. colors[c * 4 + 3] = customColors[c].a;
  37099. }
  37100. }
  37101. // Result
  37102. var vertexData = new VertexData();
  37103. var positions32 = new Float32Array(positions);
  37104. var normals32 = new Float32Array(normals);
  37105. var uvs32 = new Float32Array(uvs);
  37106. vertexData.indices = indices;
  37107. vertexData.positions = positions32;
  37108. vertexData.normals = normals32;
  37109. vertexData.uvs = uvs32;
  37110. if (colors) {
  37111. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37112. }
  37113. if (closePath) {
  37114. vertexData._idx = idx;
  37115. }
  37116. return vertexData;
  37117. };
  37118. /**
  37119. * Creates the VertexData for a box
  37120. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37121. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37122. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37123. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37124. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37125. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37126. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37127. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37128. * * 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)
  37129. * * 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)
  37130. * @returns the VertexData of the box
  37131. */
  37132. VertexData.CreateBox = function (options) {
  37133. var normalsSource = [
  37134. new BABYLON.Vector3(0, 0, 1),
  37135. new BABYLON.Vector3(0, 0, -1),
  37136. new BABYLON.Vector3(1, 0, 0),
  37137. new BABYLON.Vector3(-1, 0, 0),
  37138. new BABYLON.Vector3(0, 1, 0),
  37139. new BABYLON.Vector3(0, -1, 0)
  37140. ];
  37141. var indices = [];
  37142. var positions = [];
  37143. var normals = [];
  37144. var uvs = [];
  37145. var width = options.width || options.size || 1;
  37146. var height = options.height || options.size || 1;
  37147. var depth = options.depth || options.size || 1;
  37148. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37149. var faceUV = options.faceUV || new Array(6);
  37150. var faceColors = options.faceColors;
  37151. var colors = [];
  37152. // default face colors and UV if undefined
  37153. for (var f = 0; f < 6; f++) {
  37154. if (faceUV[f] === undefined) {
  37155. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37156. }
  37157. if (faceColors && faceColors[f] === undefined) {
  37158. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37159. }
  37160. }
  37161. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37162. // Create each face in turn.
  37163. for (var index = 0; index < normalsSource.length; index++) {
  37164. var normal = normalsSource[index];
  37165. // Get two vectors perpendicular to the face normal and to each other.
  37166. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37167. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37168. // Six indices (two triangles) per face.
  37169. var verticesLength = positions.length / 3;
  37170. indices.push(verticesLength);
  37171. indices.push(verticesLength + 1);
  37172. indices.push(verticesLength + 2);
  37173. indices.push(verticesLength);
  37174. indices.push(verticesLength + 2);
  37175. indices.push(verticesLength + 3);
  37176. // Four vertices per face.
  37177. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37178. positions.push(vertex.x, vertex.y, vertex.z);
  37179. normals.push(normal.x, normal.y, normal.z);
  37180. uvs.push(faceUV[index].z, faceUV[index].w);
  37181. if (faceColors) {
  37182. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37183. }
  37184. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37185. positions.push(vertex.x, vertex.y, vertex.z);
  37186. normals.push(normal.x, normal.y, normal.z);
  37187. uvs.push(faceUV[index].x, faceUV[index].w);
  37188. if (faceColors) {
  37189. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37190. }
  37191. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37192. positions.push(vertex.x, vertex.y, vertex.z);
  37193. normals.push(normal.x, normal.y, normal.z);
  37194. uvs.push(faceUV[index].x, faceUV[index].y);
  37195. if (faceColors) {
  37196. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37197. }
  37198. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37199. positions.push(vertex.x, vertex.y, vertex.z);
  37200. normals.push(normal.x, normal.y, normal.z);
  37201. uvs.push(faceUV[index].z, faceUV[index].y);
  37202. if (faceColors) {
  37203. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37204. }
  37205. }
  37206. // sides
  37207. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37208. // Result
  37209. var vertexData = new VertexData();
  37210. vertexData.indices = indices;
  37211. vertexData.positions = positions;
  37212. vertexData.normals = normals;
  37213. vertexData.uvs = uvs;
  37214. if (faceColors) {
  37215. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37216. vertexData.colors = totalColors;
  37217. }
  37218. return vertexData;
  37219. };
  37220. /**
  37221. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37222. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37223. * * segments sets the number of horizontal strips optional, default 32
  37224. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37225. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37226. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37227. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37228. * * 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
  37229. * * 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
  37230. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37231. * * 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)
  37232. * * 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)
  37233. * @returns the VertexData of the ellipsoid
  37234. */
  37235. VertexData.CreateSphere = function (options) {
  37236. var segments = options.segments || 32;
  37237. var diameterX = options.diameterX || options.diameter || 1;
  37238. var diameterY = options.diameterY || options.diameter || 1;
  37239. var diameterZ = options.diameterZ || options.diameter || 1;
  37240. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37241. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37242. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37243. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37244. var totalZRotationSteps = 2 + segments;
  37245. var totalYRotationSteps = 2 * totalZRotationSteps;
  37246. var indices = [];
  37247. var positions = [];
  37248. var normals = [];
  37249. var uvs = [];
  37250. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37251. var normalizedZ = zRotationStep / totalZRotationSteps;
  37252. var angleZ = normalizedZ * Math.PI * slice;
  37253. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37254. var normalizedY = yRotationStep / totalYRotationSteps;
  37255. var angleY = normalizedY * Math.PI * 2 * arc;
  37256. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37257. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37258. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37259. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37260. var vertex = complete.multiply(radius);
  37261. var normal = complete.divide(radius).normalize();
  37262. positions.push(vertex.x, vertex.y, vertex.z);
  37263. normals.push(normal.x, normal.y, normal.z);
  37264. uvs.push(normalizedY, normalizedZ);
  37265. }
  37266. if (zRotationStep > 0) {
  37267. var verticesCount = positions.length / 3;
  37268. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37269. indices.push((firstIndex));
  37270. indices.push((firstIndex + 1));
  37271. indices.push(firstIndex + totalYRotationSteps + 1);
  37272. indices.push((firstIndex + totalYRotationSteps + 1));
  37273. indices.push((firstIndex + 1));
  37274. indices.push((firstIndex + totalYRotationSteps + 2));
  37275. }
  37276. }
  37277. }
  37278. // Sides
  37279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37280. // Result
  37281. var vertexData = new VertexData();
  37282. vertexData.indices = indices;
  37283. vertexData.positions = positions;
  37284. vertexData.normals = normals;
  37285. vertexData.uvs = uvs;
  37286. return vertexData;
  37287. };
  37288. /**
  37289. * Creates the VertexData for a cylinder, cone or prism
  37290. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37291. * * height sets the height (y direction) of the cylinder, optional, default 2
  37292. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37293. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37294. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37295. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37296. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37297. * * 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
  37298. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37299. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37300. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37301. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37302. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37303. * * 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)
  37304. * * 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)
  37305. * @returns the VertexData of the cylinder, cone or prism
  37306. */
  37307. VertexData.CreateCylinder = function (options) {
  37308. var height = options.height || 2;
  37309. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37310. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37311. var tessellation = options.tessellation || 24;
  37312. var subdivisions = options.subdivisions || 1;
  37313. var hasRings = options.hasRings ? true : false;
  37314. var enclose = options.enclose ? true : false;
  37315. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37317. var faceUV = options.faceUV || new Array(3);
  37318. var faceColors = options.faceColors;
  37319. // default face colors and UV if undefined
  37320. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37321. var ringNb = (hasRings) ? subdivisions : 1;
  37322. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37323. var f;
  37324. for (f = 0; f < surfaceNb; f++) {
  37325. if (faceColors && faceColors[f] === undefined) {
  37326. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37327. }
  37328. }
  37329. for (f = 0; f < surfaceNb; f++) {
  37330. if (faceUV && faceUV[f] === undefined) {
  37331. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37332. }
  37333. }
  37334. var indices = new Array();
  37335. var positions = new Array();
  37336. var normals = new Array();
  37337. var uvs = new Array();
  37338. var colors = new Array();
  37339. var angle_step = Math.PI * 2 * arc / tessellation;
  37340. var angle;
  37341. var h;
  37342. var radius;
  37343. var tan = (diameterBottom - diameterTop) / 2 / height;
  37344. var ringVertex = BABYLON.Vector3.Zero();
  37345. var ringNormal = BABYLON.Vector3.Zero();
  37346. var ringFirstVertex = BABYLON.Vector3.Zero();
  37347. var ringFirstNormal = BABYLON.Vector3.Zero();
  37348. var quadNormal = BABYLON.Vector3.Zero();
  37349. var Y = BABYLON.Axis.Y;
  37350. // positions, normals, uvs
  37351. var i;
  37352. var j;
  37353. var r;
  37354. var ringIdx = 1;
  37355. var s = 1; // surface index
  37356. var cs = 0;
  37357. var v = 0;
  37358. for (i = 0; i <= subdivisions; i++) {
  37359. h = i / subdivisions;
  37360. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37361. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37362. for (r = 0; r < ringIdx; r++) {
  37363. if (hasRings) {
  37364. s += r;
  37365. }
  37366. if (enclose) {
  37367. s += 2 * r;
  37368. }
  37369. for (j = 0; j <= tessellation; j++) {
  37370. angle = j * angle_step;
  37371. // position
  37372. ringVertex.x = Math.cos(-angle) * radius;
  37373. ringVertex.y = -height / 2 + h * height;
  37374. ringVertex.z = Math.sin(-angle) * radius;
  37375. // normal
  37376. if (diameterTop === 0 && i === subdivisions) {
  37377. // if no top cap, reuse former normals
  37378. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37379. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37380. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37381. }
  37382. else {
  37383. ringNormal.x = ringVertex.x;
  37384. ringNormal.z = ringVertex.z;
  37385. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37386. ringNormal.normalize();
  37387. }
  37388. // keep first ring vertex values for enclose
  37389. if (j === 0) {
  37390. ringFirstVertex.copyFrom(ringVertex);
  37391. ringFirstNormal.copyFrom(ringNormal);
  37392. }
  37393. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37394. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37395. if (hasRings) {
  37396. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37397. }
  37398. else {
  37399. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37400. }
  37401. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37402. if (faceColors) {
  37403. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37404. }
  37405. }
  37406. // if enclose, add four vertices and their dedicated normals
  37407. if (arc !== 1 && enclose) {
  37408. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37409. positions.push(0, ringVertex.y, 0);
  37410. positions.push(0, ringVertex.y, 0);
  37411. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37412. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37413. quadNormal.normalize();
  37414. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37415. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37416. quadNormal.normalize();
  37417. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37418. if (hasRings) {
  37419. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37420. }
  37421. else {
  37422. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37423. }
  37424. uvs.push(faceUV[s + 1].x, v);
  37425. uvs.push(faceUV[s + 1].z, v);
  37426. if (hasRings) {
  37427. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37428. }
  37429. else {
  37430. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37431. }
  37432. uvs.push(faceUV[s + 2].x, v);
  37433. uvs.push(faceUV[s + 2].z, v);
  37434. if (faceColors) {
  37435. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37436. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37437. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37438. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37439. }
  37440. }
  37441. if (cs !== s) {
  37442. cs = s;
  37443. }
  37444. }
  37445. }
  37446. // indices
  37447. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37448. var s;
  37449. i = 0;
  37450. for (s = 0; s < subdivisions; s++) {
  37451. var i0 = 0;
  37452. var i1 = 0;
  37453. var i2 = 0;
  37454. var i3 = 0;
  37455. for (j = 0; j < tessellation; j++) {
  37456. i0 = i * (e + 1) + j;
  37457. i1 = (i + 1) * (e + 1) + j;
  37458. i2 = i * (e + 1) + (j + 1);
  37459. i3 = (i + 1) * (e + 1) + (j + 1);
  37460. indices.push(i0, i1, i2);
  37461. indices.push(i3, i2, i1);
  37462. }
  37463. if (arc !== 1 && enclose) { // if enclose, add two quads
  37464. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37465. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37466. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37467. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37468. }
  37469. i = (hasRings) ? (i + 2) : (i + 1);
  37470. }
  37471. // Caps
  37472. var createCylinderCap = function (isTop) {
  37473. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37474. if (radius === 0) {
  37475. return;
  37476. }
  37477. // Cap positions, normals & uvs
  37478. var angle;
  37479. var circleVector;
  37480. var i;
  37481. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37482. var c = null;
  37483. if (faceColors) {
  37484. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37485. }
  37486. // cap center
  37487. var vbase = positions.length / 3;
  37488. var offset = isTop ? height / 2 : -height / 2;
  37489. var center = new BABYLON.Vector3(0, offset, 0);
  37490. positions.push(center.x, center.y, center.z);
  37491. normals.push(0, isTop ? 1 : -1, 0);
  37492. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37493. if (c) {
  37494. colors.push(c.r, c.g, c.b, c.a);
  37495. }
  37496. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37497. for (i = 0; i <= tessellation; i++) {
  37498. angle = Math.PI * 2 * i * arc / tessellation;
  37499. var cos = Math.cos(-angle);
  37500. var sin = Math.sin(-angle);
  37501. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37502. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37503. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37504. normals.push(0, isTop ? 1 : -1, 0);
  37505. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37506. if (c) {
  37507. colors.push(c.r, c.g, c.b, c.a);
  37508. }
  37509. }
  37510. // Cap indices
  37511. for (i = 0; i < tessellation; i++) {
  37512. if (!isTop) {
  37513. indices.push(vbase);
  37514. indices.push(vbase + (i + 1));
  37515. indices.push(vbase + (i + 2));
  37516. }
  37517. else {
  37518. indices.push(vbase);
  37519. indices.push(vbase + (i + 2));
  37520. indices.push(vbase + (i + 1));
  37521. }
  37522. }
  37523. };
  37524. // add caps to geometry
  37525. createCylinderCap(false);
  37526. createCylinderCap(true);
  37527. // Sides
  37528. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37529. var vertexData = new VertexData();
  37530. vertexData.indices = indices;
  37531. vertexData.positions = positions;
  37532. vertexData.normals = normals;
  37533. vertexData.uvs = uvs;
  37534. if (faceColors) {
  37535. vertexData.colors = colors;
  37536. }
  37537. return vertexData;
  37538. };
  37539. /**
  37540. * Creates the VertexData for a torus
  37541. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37542. * * diameter the diameter of the torus, optional default 1
  37543. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37544. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37545. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37546. * * 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)
  37547. * * 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)
  37548. * @returns the VertexData of the torus
  37549. */
  37550. VertexData.CreateTorus = function (options) {
  37551. var indices = [];
  37552. var positions = [];
  37553. var normals = [];
  37554. var uvs = [];
  37555. var diameter = options.diameter || 1;
  37556. var thickness = options.thickness || 0.5;
  37557. var tessellation = options.tessellation || 16;
  37558. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37559. var stride = tessellation + 1;
  37560. for (var i = 0; i <= tessellation; i++) {
  37561. var u = i / tessellation;
  37562. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37563. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37564. for (var j = 0; j <= tessellation; j++) {
  37565. var v = 1 - j / tessellation;
  37566. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37567. var dx = Math.cos(innerAngle);
  37568. var dy = Math.sin(innerAngle);
  37569. // Create a vertex.
  37570. var normal = new BABYLON.Vector3(dx, dy, 0);
  37571. var position = normal.scale(thickness / 2);
  37572. var textureCoordinate = new BABYLON.Vector2(u, v);
  37573. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37574. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37575. positions.push(position.x, position.y, position.z);
  37576. normals.push(normal.x, normal.y, normal.z);
  37577. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37578. // And create indices for two triangles.
  37579. var nextI = (i + 1) % stride;
  37580. var nextJ = (j + 1) % stride;
  37581. indices.push(i * stride + j);
  37582. indices.push(i * stride + nextJ);
  37583. indices.push(nextI * stride + j);
  37584. indices.push(i * stride + nextJ);
  37585. indices.push(nextI * stride + nextJ);
  37586. indices.push(nextI * stride + j);
  37587. }
  37588. }
  37589. // Sides
  37590. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37591. // Result
  37592. var vertexData = new VertexData();
  37593. vertexData.indices = indices;
  37594. vertexData.positions = positions;
  37595. vertexData.normals = normals;
  37596. vertexData.uvs = uvs;
  37597. return vertexData;
  37598. };
  37599. /**
  37600. * Creates the VertexData of the LineSystem
  37601. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37602. * - lines an array of lines, each line being an array of successive Vector3
  37603. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37604. * @returns the VertexData of the LineSystem
  37605. */
  37606. VertexData.CreateLineSystem = function (options) {
  37607. var indices = [];
  37608. var positions = [];
  37609. var lines = options.lines;
  37610. var colors = options.colors;
  37611. var vertexColors = [];
  37612. var idx = 0;
  37613. for (var l = 0; l < lines.length; l++) {
  37614. var points = lines[l];
  37615. for (var index = 0; index < points.length; index++) {
  37616. positions.push(points[index].x, points[index].y, points[index].z);
  37617. if (colors) {
  37618. var color = colors[l];
  37619. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37620. }
  37621. if (index > 0) {
  37622. indices.push(idx - 1);
  37623. indices.push(idx);
  37624. }
  37625. idx++;
  37626. }
  37627. }
  37628. var vertexData = new VertexData();
  37629. vertexData.indices = indices;
  37630. vertexData.positions = positions;
  37631. if (colors) {
  37632. vertexData.colors = vertexColors;
  37633. }
  37634. return vertexData;
  37635. };
  37636. /**
  37637. * Create the VertexData for a DashedLines
  37638. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37639. * - points an array successive Vector3
  37640. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37641. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37642. * - dashNb the intended total number of dashes, optional, default 200
  37643. * @returns the VertexData for the DashedLines
  37644. */
  37645. VertexData.CreateDashedLines = function (options) {
  37646. var dashSize = options.dashSize || 3;
  37647. var gapSize = options.gapSize || 1;
  37648. var dashNb = options.dashNb || 200;
  37649. var points = options.points;
  37650. var positions = new Array();
  37651. var indices = new Array();
  37652. var curvect = BABYLON.Vector3.Zero();
  37653. var lg = 0;
  37654. var nb = 0;
  37655. var shft = 0;
  37656. var dashshft = 0;
  37657. var curshft = 0;
  37658. var idx = 0;
  37659. var i = 0;
  37660. for (i = 0; i < points.length - 1; i++) {
  37661. points[i + 1].subtractToRef(points[i], curvect);
  37662. lg += curvect.length();
  37663. }
  37664. shft = lg / dashNb;
  37665. dashshft = dashSize * shft / (dashSize + gapSize);
  37666. for (i = 0; i < points.length - 1; i++) {
  37667. points[i + 1].subtractToRef(points[i], curvect);
  37668. nb = Math.floor(curvect.length() / shft);
  37669. curvect.normalize();
  37670. for (var j = 0; j < nb; j++) {
  37671. curshft = shft * j;
  37672. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37673. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37674. indices.push(idx, idx + 1);
  37675. idx += 2;
  37676. }
  37677. }
  37678. // Result
  37679. var vertexData = new VertexData();
  37680. vertexData.positions = positions;
  37681. vertexData.indices = indices;
  37682. return vertexData;
  37683. };
  37684. /**
  37685. * Creates the VertexData for a Ground
  37686. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37687. * - width the width (x direction) of the ground, optional, default 1
  37688. * - height the height (z direction) of the ground, optional, default 1
  37689. * - subdivisions the number of subdivisions per side, optional, default 1
  37690. * @returns the VertexData of the Ground
  37691. */
  37692. VertexData.CreateGround = function (options) {
  37693. var indices = [];
  37694. var positions = [];
  37695. var normals = [];
  37696. var uvs = [];
  37697. var row, col;
  37698. var width = options.width || 1;
  37699. var height = options.height || 1;
  37700. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37701. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37702. for (row = 0; row <= subdivisionsY; row++) {
  37703. for (col = 0; col <= subdivisionsX; col++) {
  37704. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37705. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37706. positions.push(position.x, position.y, position.z);
  37707. normals.push(normal.x, normal.y, normal.z);
  37708. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37709. }
  37710. }
  37711. for (row = 0; row < subdivisionsY; row++) {
  37712. for (col = 0; col < subdivisionsX; col++) {
  37713. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37714. indices.push(col + 1 + row * (subdivisionsX + 1));
  37715. indices.push(col + row * (subdivisionsX + 1));
  37716. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37717. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37718. indices.push(col + row * (subdivisionsX + 1));
  37719. }
  37720. }
  37721. // Result
  37722. var vertexData = new VertexData();
  37723. vertexData.indices = indices;
  37724. vertexData.positions = positions;
  37725. vertexData.normals = normals;
  37726. vertexData.uvs = uvs;
  37727. return vertexData;
  37728. };
  37729. /**
  37730. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37731. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37732. * * xmin the ground minimum X coordinate, optional, default -1
  37733. * * zmin the ground minimum Z coordinate, optional, default -1
  37734. * * xmax the ground maximum X coordinate, optional, default 1
  37735. * * zmax the ground maximum Z coordinate, optional, default 1
  37736. * * 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}
  37737. * * 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}
  37738. * @returns the VertexData of the TiledGround
  37739. */
  37740. VertexData.CreateTiledGround = function (options) {
  37741. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37742. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37743. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37744. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37745. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37746. var precision = options.precision || { w: 1, h: 1 };
  37747. var indices = new Array();
  37748. var positions = new Array();
  37749. var normals = new Array();
  37750. var uvs = new Array();
  37751. var row, col, tileRow, tileCol;
  37752. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37753. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37754. precision.w = (precision.w < 1) ? 1 : precision.w;
  37755. precision.h = (precision.h < 1) ? 1 : precision.h;
  37756. var tileSize = {
  37757. 'w': (xmax - xmin) / subdivisions.w,
  37758. 'h': (zmax - zmin) / subdivisions.h
  37759. };
  37760. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37761. // Indices
  37762. var base = positions.length / 3;
  37763. var rowLength = precision.w + 1;
  37764. for (row = 0; row < precision.h; row++) {
  37765. for (col = 0; col < precision.w; col++) {
  37766. var square = [
  37767. base + col + row * rowLength,
  37768. base + (col + 1) + row * rowLength,
  37769. base + (col + 1) + (row + 1) * rowLength,
  37770. base + col + (row + 1) * rowLength
  37771. ];
  37772. indices.push(square[1]);
  37773. indices.push(square[2]);
  37774. indices.push(square[3]);
  37775. indices.push(square[0]);
  37776. indices.push(square[1]);
  37777. indices.push(square[3]);
  37778. }
  37779. }
  37780. // Position, normals and uvs
  37781. var position = BABYLON.Vector3.Zero();
  37782. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37783. for (row = 0; row <= precision.h; row++) {
  37784. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37785. for (col = 0; col <= precision.w; col++) {
  37786. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37787. position.y = 0;
  37788. positions.push(position.x, position.y, position.z);
  37789. normals.push(normal.x, normal.y, normal.z);
  37790. uvs.push(col / precision.w, row / precision.h);
  37791. }
  37792. }
  37793. }
  37794. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37795. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37796. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37797. }
  37798. }
  37799. // Result
  37800. var vertexData = new VertexData();
  37801. vertexData.indices = indices;
  37802. vertexData.positions = positions;
  37803. vertexData.normals = normals;
  37804. vertexData.uvs = uvs;
  37805. return vertexData;
  37806. };
  37807. /**
  37808. * Creates the VertexData of the Ground designed from a heightmap
  37809. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37810. * * width the width (x direction) of the ground
  37811. * * height the height (z direction) of the ground
  37812. * * subdivisions the number of subdivisions per side
  37813. * * minHeight the minimum altitude on the ground, optional, default 0
  37814. * * maxHeight the maximum altitude on the ground, optional default 1
  37815. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37816. * * buffer the array holding the image color data
  37817. * * bufferWidth the width of image
  37818. * * bufferHeight the height of image
  37819. * @returns the VertexData of the Ground designed from a heightmap
  37820. */
  37821. VertexData.CreateGroundFromHeightMap = function (options) {
  37822. var indices = [];
  37823. var positions = [];
  37824. var normals = [];
  37825. var uvs = [];
  37826. var row, col;
  37827. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37828. // Vertices
  37829. for (row = 0; row <= options.subdivisions; row++) {
  37830. for (col = 0; col <= options.subdivisions; col++) {
  37831. 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));
  37832. // Compute height
  37833. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37834. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37835. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37836. var r = options.buffer[pos] / 255.0;
  37837. var g = options.buffer[pos + 1] / 255.0;
  37838. var b = options.buffer[pos + 2] / 255.0;
  37839. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37840. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37841. // Add vertex
  37842. positions.push(position.x, position.y, position.z);
  37843. normals.push(0, 0, 0);
  37844. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37845. }
  37846. }
  37847. // Indices
  37848. for (row = 0; row < options.subdivisions; row++) {
  37849. for (col = 0; col < options.subdivisions; col++) {
  37850. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37851. indices.push(col + 1 + row * (options.subdivisions + 1));
  37852. indices.push(col + row * (options.subdivisions + 1));
  37853. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37854. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37855. indices.push(col + row * (options.subdivisions + 1));
  37856. }
  37857. }
  37858. // Normals
  37859. VertexData.ComputeNormals(positions, indices, normals);
  37860. // Result
  37861. var vertexData = new VertexData();
  37862. vertexData.indices = indices;
  37863. vertexData.positions = positions;
  37864. vertexData.normals = normals;
  37865. vertexData.uvs = uvs;
  37866. return vertexData;
  37867. };
  37868. /**
  37869. * Creates the VertexData for a Plane
  37870. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37871. * * size sets the width and height of the plane to the value of size, optional default 1
  37872. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37873. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37874. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37875. * * 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)
  37876. * * 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)
  37877. * @returns the VertexData of the box
  37878. */
  37879. VertexData.CreatePlane = function (options) {
  37880. var indices = [];
  37881. var positions = [];
  37882. var normals = [];
  37883. var uvs = [];
  37884. var width = options.width || options.size || 1;
  37885. var height = options.height || options.size || 1;
  37886. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37887. // Vertices
  37888. var halfWidth = width / 2.0;
  37889. var halfHeight = height / 2.0;
  37890. positions.push(-halfWidth, -halfHeight, 0);
  37891. normals.push(0, 0, -1.0);
  37892. uvs.push(0.0, 0.0);
  37893. positions.push(halfWidth, -halfHeight, 0);
  37894. normals.push(0, 0, -1.0);
  37895. uvs.push(1.0, 0.0);
  37896. positions.push(halfWidth, halfHeight, 0);
  37897. normals.push(0, 0, -1.0);
  37898. uvs.push(1.0, 1.0);
  37899. positions.push(-halfWidth, halfHeight, 0);
  37900. normals.push(0, 0, -1.0);
  37901. uvs.push(0.0, 1.0);
  37902. // Indices
  37903. indices.push(0);
  37904. indices.push(1);
  37905. indices.push(2);
  37906. indices.push(0);
  37907. indices.push(2);
  37908. indices.push(3);
  37909. // Sides
  37910. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37911. // Result
  37912. var vertexData = new VertexData();
  37913. vertexData.indices = indices;
  37914. vertexData.positions = positions;
  37915. vertexData.normals = normals;
  37916. vertexData.uvs = uvs;
  37917. return vertexData;
  37918. };
  37919. /**
  37920. * Creates the VertexData of the Disc or regular Polygon
  37921. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37922. * * radius the radius of the disc, optional default 0.5
  37923. * * tessellation the number of polygon sides, optional, default 64
  37924. * * 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
  37925. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37926. * * 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)
  37927. * * 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)
  37928. * @returns the VertexData of the box
  37929. */
  37930. VertexData.CreateDisc = function (options) {
  37931. var positions = new Array();
  37932. var indices = new Array();
  37933. var normals = new Array();
  37934. var uvs = new Array();
  37935. var radius = options.radius || 0.5;
  37936. var tessellation = options.tessellation || 64;
  37937. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37938. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37939. // positions and uvs
  37940. positions.push(0, 0, 0); // disc center first
  37941. uvs.push(0.5, 0.5);
  37942. var theta = Math.PI * 2 * arc;
  37943. var step = theta / tessellation;
  37944. for (var a = 0; a < theta; a += step) {
  37945. var x = Math.cos(a);
  37946. var y = Math.sin(a);
  37947. var u = (x + 1) / 2;
  37948. var v = (1 - y) / 2;
  37949. positions.push(radius * x, radius * y, 0);
  37950. uvs.push(u, v);
  37951. }
  37952. if (arc === 1) {
  37953. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37954. uvs.push(uvs[2], uvs[3]);
  37955. }
  37956. //indices
  37957. var vertexNb = positions.length / 3;
  37958. for (var i = 1; i < vertexNb - 1; i++) {
  37959. indices.push(i + 1, 0, i);
  37960. }
  37961. // result
  37962. VertexData.ComputeNormals(positions, indices, normals);
  37963. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37964. var vertexData = new VertexData();
  37965. vertexData.indices = indices;
  37966. vertexData.positions = positions;
  37967. vertexData.normals = normals;
  37968. vertexData.uvs = uvs;
  37969. return vertexData;
  37970. };
  37971. /**
  37972. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37973. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37974. * @param polygon a mesh built from polygonTriangulation.build()
  37975. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37976. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37977. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37978. * @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)
  37979. * @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)
  37980. * @returns the VertexData of the Polygon
  37981. */
  37982. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37983. var faceUV = fUV || new Array(3);
  37984. var faceColors = fColors;
  37985. var colors = [];
  37986. // default face colors and UV if undefined
  37987. for (var f = 0; f < 3; f++) {
  37988. if (faceUV[f] === undefined) {
  37989. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37990. }
  37991. if (faceColors && faceColors[f] === undefined) {
  37992. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37993. }
  37994. }
  37995. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37996. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37997. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37998. var indices = polygon.getIndices();
  37999. // set face colours and textures
  38000. var idx = 0;
  38001. var face = 0;
  38002. for (var index = 0; index < normals.length; index += 3) {
  38003. //Edge Face no. 1
  38004. if (Math.abs(normals[index + 1]) < 0.001) {
  38005. face = 1;
  38006. }
  38007. //Top Face no. 0
  38008. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38009. face = 0;
  38010. }
  38011. //Bottom Face no. 2
  38012. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38013. face = 2;
  38014. }
  38015. idx = index / 3;
  38016. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38017. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38018. if (faceColors) {
  38019. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38020. }
  38021. }
  38022. // sides
  38023. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38024. // Result
  38025. var vertexData = new VertexData();
  38026. vertexData.indices = indices;
  38027. vertexData.positions = positions;
  38028. vertexData.normals = normals;
  38029. vertexData.uvs = uvs;
  38030. if (faceColors) {
  38031. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38032. vertexData.colors = totalColors;
  38033. }
  38034. return vertexData;
  38035. };
  38036. /**
  38037. * Creates the VertexData of the IcoSphere
  38038. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38039. * * radius the radius of the IcoSphere, optional default 1
  38040. * * radiusX allows stretching in the x direction, optional, default radius
  38041. * * radiusY allows stretching in the y direction, optional, default radius
  38042. * * radiusZ allows stretching in the z direction, optional, default radius
  38043. * * flat when true creates a flat shaded mesh, optional, default true
  38044. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38045. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38046. * * 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)
  38047. * * 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)
  38048. * @returns the VertexData of the IcoSphere
  38049. */
  38050. VertexData.CreateIcoSphere = function (options) {
  38051. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38052. var radius = options.radius || 1;
  38053. var flat = (options.flat === undefined) ? true : options.flat;
  38054. var subdivisions = options.subdivisions || 4;
  38055. var radiusX = options.radiusX || radius;
  38056. var radiusY = options.radiusY || radius;
  38057. var radiusZ = options.radiusZ || radius;
  38058. var t = (1 + Math.sqrt(5)) / 2;
  38059. // 12 vertex x,y,z
  38060. var ico_vertices = [
  38061. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38062. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38063. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38064. ];
  38065. // index of 3 vertex makes a face of icopshere
  38066. var ico_indices = [
  38067. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38068. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38069. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38070. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38071. ];
  38072. // vertex for uv have aliased position, not for UV
  38073. var vertices_unalias_id = [
  38074. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38075. // vertex alias
  38076. 0,
  38077. 2,
  38078. 3,
  38079. 3,
  38080. 3,
  38081. 4,
  38082. 7,
  38083. 8,
  38084. 9,
  38085. 9,
  38086. 10,
  38087. 11 // 23: B + 12
  38088. ];
  38089. // uv as integer step (not pixels !)
  38090. var ico_vertexuv = [
  38091. 5, 1, 3, 1, 6, 4, 0, 0,
  38092. 5, 3, 4, 2, 2, 2, 4, 0,
  38093. 2, 0, 1, 1, 6, 0, 6, 2,
  38094. // vertex alias (for same vertex on different faces)
  38095. 0, 4,
  38096. 3, 3,
  38097. 4, 4,
  38098. 3, 1,
  38099. 4, 2,
  38100. 4, 4,
  38101. 0, 2,
  38102. 1, 1,
  38103. 2, 2,
  38104. 3, 3,
  38105. 1, 3,
  38106. 2, 4 // 23: B + 12
  38107. ];
  38108. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38109. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38110. // First island of uv mapping
  38111. // v = 4h 3+ 2
  38112. // v = 3h 9+ 4
  38113. // v = 2h 9+ 5 B
  38114. // v = 1h 9 1 0
  38115. // v = 0h 3 8 7 A
  38116. // u = 0 1 2 3 4 5 6 *a
  38117. // Second island of uv mapping
  38118. // v = 4h 0+ B+ 4+
  38119. // v = 3h A+ 2+
  38120. // v = 2h 7+ 6 3+
  38121. // v = 1h 8+ 3+
  38122. // v = 0h
  38123. // u = 0 1 2 3 4 5 6 *a
  38124. // Face layout on texture UV mapping
  38125. // ============
  38126. // \ 4 /\ 16 / ======
  38127. // \ / \ / /\ 11 /
  38128. // \/ 7 \/ / \ /
  38129. // ======= / 10 \/
  38130. // /\ 17 /\ =======
  38131. // / \ / \ \ 15 /\
  38132. // / 8 \/ 12 \ \ / \
  38133. // ============ \/ 6 \
  38134. // \ 18 /\ ============
  38135. // \ / \ \ 5 /\ 0 /
  38136. // \/ 13 \ \ / \ /
  38137. // ======= \/ 1 \/
  38138. // =============
  38139. // /\ 19 /\ 2 /\
  38140. // / \ / \ / \
  38141. // / 14 \/ 9 \/ 3 \
  38142. // ===================
  38143. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38144. var ustep = 138 / 1024;
  38145. var vstep = 239 / 1024;
  38146. var uoffset = 60 / 1024;
  38147. var voffset = 26 / 1024;
  38148. // Second island should have margin, not to touch the first island
  38149. // avoid any borderline artefact in pixel rounding
  38150. var island_u_offset = -40 / 1024;
  38151. var island_v_offset = +20 / 1024;
  38152. // face is either island 0 or 1 :
  38153. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38154. var island = [
  38155. 0, 0, 0, 0, 1,
  38156. 0, 0, 1, 1, 0,
  38157. 0, 0, 1, 1, 0,
  38158. 0, 1, 1, 1, 0 // 15 - 19
  38159. ];
  38160. var indices = new Array();
  38161. var positions = new Array();
  38162. var normals = new Array();
  38163. var uvs = new Array();
  38164. var current_indice = 0;
  38165. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38166. var face_vertex_pos = new Array(3);
  38167. var face_vertex_uv = new Array(3);
  38168. var v012;
  38169. for (v012 = 0; v012 < 3; v012++) {
  38170. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38171. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38172. }
  38173. // create all with normals
  38174. for (var face = 0; face < 20; face++) {
  38175. // 3 vertex per face
  38176. for (v012 = 0; v012 < 3; v012++) {
  38177. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38178. var v_id = ico_indices[3 * face + v012];
  38179. // vertex have 3D position (x,y,z)
  38180. 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]);
  38181. // Normalize to get normal, then scale to radius
  38182. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38183. // uv Coordinates from vertex ID
  38184. 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);
  38185. }
  38186. // Subdivide the face (interpolate pos, norm, uv)
  38187. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38188. // - norm is linear interpolation of vertex corner normal
  38189. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38190. // - uv is linear interpolation
  38191. //
  38192. // Topology is as below for sub-divide by 2
  38193. // vertex shown as v0,v1,v2
  38194. // interp index is i1 to progress in range [v0,v1[
  38195. // interp index is i2 to progress in range [v0,v2[
  38196. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38197. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38198. //
  38199. //
  38200. // i2 v2
  38201. // ^ ^
  38202. // / / \
  38203. // / / \
  38204. // / / \
  38205. // / / (0,1) \
  38206. // / #---------\
  38207. // / / \ (0,0)'/ \
  38208. // / / \ / \
  38209. // / / \ / \
  38210. // / / (0,0) \ / (1,0) \
  38211. // / #---------#---------\
  38212. // v0 v1
  38213. //
  38214. // --------------------> i1
  38215. //
  38216. // interp of (i1,i2):
  38217. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38218. // along i1 : lerp(x0,x1, i1/(S-i2))
  38219. //
  38220. // centroid of triangle is needed to get help normal computation
  38221. // (c1,c2) are used for centroid location
  38222. var interp_vertex = function (i1, i2, c1, c2) {
  38223. // vertex is interpolated from
  38224. // - face_vertex_pos[0..2]
  38225. // - face_vertex_uv[0..2]
  38226. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38227. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38228. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38229. pos_interp.normalize();
  38230. var vertex_normal;
  38231. if (flat) {
  38232. // in flat mode, recalculate normal as face centroid normal
  38233. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38234. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38235. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38236. }
  38237. else {
  38238. // in smooth mode, recalculate normal from each single vertex position
  38239. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38240. }
  38241. // Vertex normal need correction due to X,Y,Z radius scaling
  38242. vertex_normal.x /= radiusX;
  38243. vertex_normal.y /= radiusY;
  38244. vertex_normal.z /= radiusZ;
  38245. vertex_normal.normalize();
  38246. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38247. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38248. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38249. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38250. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38251. uvs.push(uv_interp.x, uv_interp.y);
  38252. // push each vertex has member of a face
  38253. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38254. indices.push(current_indice);
  38255. current_indice++;
  38256. };
  38257. for (var i2 = 0; i2 < subdivisions; i2++) {
  38258. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38259. // face : (i1,i2) for /\ :
  38260. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38261. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38262. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38263. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38264. if (i1 + i2 + 1 < subdivisions) {
  38265. // face : (i1,i2)' for \/ :
  38266. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38267. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38268. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38269. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38270. }
  38271. }
  38272. }
  38273. }
  38274. // Sides
  38275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38276. // Result
  38277. var vertexData = new VertexData();
  38278. vertexData.indices = indices;
  38279. vertexData.positions = positions;
  38280. vertexData.normals = normals;
  38281. vertexData.uvs = uvs;
  38282. return vertexData;
  38283. };
  38284. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38285. /**
  38286. * Creates the VertexData for a Polyhedron
  38287. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38288. * * type provided types are:
  38289. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38290. * * 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)
  38291. * * size the size of the IcoSphere, optional default 1
  38292. * * sizeX allows stretching in the x direction, optional, default size
  38293. * * sizeY allows stretching in the y direction, optional, default size
  38294. * * sizeZ allows stretching in the z direction, optional, default size
  38295. * * 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
  38296. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38297. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38298. * * flat when true creates a flat shaded mesh, optional, default true
  38299. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38300. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38301. * * 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)
  38302. * * 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)
  38303. * @returns the VertexData of the Polyhedron
  38304. */
  38305. VertexData.CreatePolyhedron = function (options) {
  38306. // provided polyhedron types :
  38307. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38308. // 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)
  38309. var polyhedra = [];
  38310. 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]] };
  38311. 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]] };
  38312. polyhedra[2] = {
  38313. 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]],
  38314. 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]]
  38315. };
  38316. polyhedra[3] = {
  38317. 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]],
  38318. 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]]
  38319. };
  38320. polyhedra[4] = {
  38321. 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]],
  38322. 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]]
  38323. };
  38324. 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]] };
  38325. 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]] };
  38326. 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]] };
  38327. 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]] };
  38328. 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]] };
  38329. 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]] };
  38330. 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]] };
  38331. 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]] };
  38332. 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]] };
  38333. polyhedra[14] = {
  38334. 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]],
  38335. 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]]
  38336. };
  38337. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38338. var size = options.size;
  38339. var sizeX = options.sizeX || size || 1;
  38340. var sizeY = options.sizeY || size || 1;
  38341. var sizeZ = options.sizeZ || size || 1;
  38342. var data = options.custom || polyhedra[type];
  38343. var nbfaces = data.face.length;
  38344. var faceUV = options.faceUV || new Array(nbfaces);
  38345. var faceColors = options.faceColors;
  38346. var flat = (options.flat === undefined) ? true : options.flat;
  38347. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38348. var positions = new Array();
  38349. var indices = new Array();
  38350. var normals = new Array();
  38351. var uvs = new Array();
  38352. var colors = new Array();
  38353. var index = 0;
  38354. var faceIdx = 0; // face cursor in the array "indexes"
  38355. var indexes = new Array();
  38356. var i = 0;
  38357. var f = 0;
  38358. var u, v, ang, x, y, tmp;
  38359. // default face colors and UV if undefined
  38360. if (flat) {
  38361. for (f = 0; f < nbfaces; f++) {
  38362. if (faceColors && faceColors[f] === undefined) {
  38363. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38364. }
  38365. if (faceUV && faceUV[f] === undefined) {
  38366. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38367. }
  38368. }
  38369. }
  38370. if (!flat) {
  38371. for (i = 0; i < data.vertex.length; i++) {
  38372. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38373. uvs.push(0, 0);
  38374. }
  38375. for (f = 0; f < nbfaces; f++) {
  38376. for (i = 0; i < data.face[f].length - 2; i++) {
  38377. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38378. }
  38379. }
  38380. }
  38381. else {
  38382. for (f = 0; f < nbfaces; f++) {
  38383. var fl = data.face[f].length; // number of vertices of the current face
  38384. ang = 2 * Math.PI / fl;
  38385. x = 0.5 * Math.tan(ang / 2);
  38386. y = 0.5;
  38387. // positions, uvs, colors
  38388. for (i = 0; i < fl; i++) {
  38389. // positions
  38390. 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);
  38391. indexes.push(index);
  38392. index++;
  38393. // uvs
  38394. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38395. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38396. uvs.push(u, v);
  38397. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38398. y = x * Math.sin(ang) + y * Math.cos(ang);
  38399. x = tmp;
  38400. // colors
  38401. if (faceColors) {
  38402. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38403. }
  38404. }
  38405. // indices from indexes
  38406. for (i = 0; i < fl - 2; i++) {
  38407. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38408. }
  38409. faceIdx += fl;
  38410. }
  38411. }
  38412. VertexData.ComputeNormals(positions, indices, normals);
  38413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38414. var vertexData = new VertexData();
  38415. vertexData.positions = positions;
  38416. vertexData.indices = indices;
  38417. vertexData.normals = normals;
  38418. vertexData.uvs = uvs;
  38419. if (faceColors && flat) {
  38420. vertexData.colors = colors;
  38421. }
  38422. return vertexData;
  38423. };
  38424. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38425. /**
  38426. * Creates the VertexData for a TorusKnot
  38427. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38428. * * radius the radius of the torus knot, optional, default 2
  38429. * * tube the thickness of the tube, optional, default 0.5
  38430. * * radialSegments the number of sides on each tube segments, optional, default 32
  38431. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38432. * * p the number of windings around the z axis, optional, default 2
  38433. * * q the number of windings around the x axis, optional, default 3
  38434. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38435. * * 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)
  38436. * * 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)
  38437. * @returns the VertexData of the Torus Knot
  38438. */
  38439. VertexData.CreateTorusKnot = function (options) {
  38440. var indices = new Array();
  38441. var positions = new Array();
  38442. var normals = new Array();
  38443. var uvs = new Array();
  38444. var radius = options.radius || 2;
  38445. var tube = options.tube || 0.5;
  38446. var radialSegments = options.radialSegments || 32;
  38447. var tubularSegments = options.tubularSegments || 32;
  38448. var p = options.p || 2;
  38449. var q = options.q || 3;
  38450. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38451. // Helper
  38452. var getPos = function (angle) {
  38453. var cu = Math.cos(angle);
  38454. var su = Math.sin(angle);
  38455. var quOverP = q / p * angle;
  38456. var cs = Math.cos(quOverP);
  38457. var tx = radius * (2 + cs) * 0.5 * cu;
  38458. var ty = radius * (2 + cs) * su * 0.5;
  38459. var tz = radius * Math.sin(quOverP) * 0.5;
  38460. return new BABYLON.Vector3(tx, ty, tz);
  38461. };
  38462. // Vertices
  38463. var i;
  38464. var j;
  38465. for (i = 0; i <= radialSegments; i++) {
  38466. var modI = i % radialSegments;
  38467. var u = modI / radialSegments * 2 * p * Math.PI;
  38468. var p1 = getPos(u);
  38469. var p2 = getPos(u + 0.01);
  38470. var tang = p2.subtract(p1);
  38471. var n = p2.add(p1);
  38472. var bitan = BABYLON.Vector3.Cross(tang, n);
  38473. n = BABYLON.Vector3.Cross(bitan, tang);
  38474. bitan.normalize();
  38475. n.normalize();
  38476. for (j = 0; j < tubularSegments; j++) {
  38477. var modJ = j % tubularSegments;
  38478. var v = modJ / tubularSegments * 2 * Math.PI;
  38479. var cx = -tube * Math.cos(v);
  38480. var cy = tube * Math.sin(v);
  38481. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38482. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38483. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38484. uvs.push(i / radialSegments);
  38485. uvs.push(j / tubularSegments);
  38486. }
  38487. }
  38488. for (i = 0; i < radialSegments; i++) {
  38489. for (j = 0; j < tubularSegments; j++) {
  38490. var jNext = (j + 1) % tubularSegments;
  38491. var a = i * tubularSegments + j;
  38492. var b = (i + 1) * tubularSegments + j;
  38493. var c = (i + 1) * tubularSegments + jNext;
  38494. var d = i * tubularSegments + jNext;
  38495. indices.push(d);
  38496. indices.push(b);
  38497. indices.push(a);
  38498. indices.push(d);
  38499. indices.push(c);
  38500. indices.push(b);
  38501. }
  38502. }
  38503. // Normals
  38504. VertexData.ComputeNormals(positions, indices, normals);
  38505. // Sides
  38506. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38507. // Result
  38508. var vertexData = new VertexData();
  38509. vertexData.indices = indices;
  38510. vertexData.positions = positions;
  38511. vertexData.normals = normals;
  38512. vertexData.uvs = uvs;
  38513. return vertexData;
  38514. };
  38515. // Tools
  38516. /**
  38517. * Compute normals for given positions and indices
  38518. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38519. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38520. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38521. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38522. * * facetNormals : optional array of facet normals (vector3)
  38523. * * facetPositions : optional array of facet positions (vector3)
  38524. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38525. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38526. * * bInfo : optional bounding info, required for facetPartitioning computation
  38527. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38528. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38529. * * useRightHandedSystem: optional boolean to for right handed system computation
  38530. * * depthSort : optional boolean to enable the facet depth sort computation
  38531. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38532. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38533. */
  38534. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38535. // temporary scalar variables
  38536. var index = 0; // facet index
  38537. var p1p2x = 0.0; // p1p2 vector x coordinate
  38538. var p1p2y = 0.0; // p1p2 vector y coordinate
  38539. var p1p2z = 0.0; // p1p2 vector z coordinate
  38540. var p3p2x = 0.0; // p3p2 vector x coordinate
  38541. var p3p2y = 0.0; // p3p2 vector y coordinate
  38542. var p3p2z = 0.0; // p3p2 vector z coordinate
  38543. var faceNormalx = 0.0; // facet normal x coordinate
  38544. var faceNormaly = 0.0; // facet normal y coordinate
  38545. var faceNormalz = 0.0; // facet normal z coordinate
  38546. var length = 0.0; // facet normal length before normalization
  38547. var v1x = 0; // vector1 x index in the positions array
  38548. var v1y = 0; // vector1 y index in the positions array
  38549. var v1z = 0; // vector1 z index in the positions array
  38550. var v2x = 0; // vector2 x index in the positions array
  38551. var v2y = 0; // vector2 y index in the positions array
  38552. var v2z = 0; // vector2 z index in the positions array
  38553. var v3x = 0; // vector3 x index in the positions array
  38554. var v3y = 0; // vector3 y index in the positions array
  38555. var v3z = 0; // vector3 z index in the positions array
  38556. var computeFacetNormals = false;
  38557. var computeFacetPositions = false;
  38558. var computeFacetPartitioning = false;
  38559. var computeDepthSort = false;
  38560. var faceNormalSign = 1;
  38561. var ratio = 0;
  38562. var distanceTo = null;
  38563. if (options) {
  38564. computeFacetNormals = (options.facetNormals) ? true : false;
  38565. computeFacetPositions = (options.facetPositions) ? true : false;
  38566. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38567. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38568. ratio = options.ratio || 0;
  38569. computeDepthSort = (options.depthSort) ? true : false;
  38570. distanceTo = (options.distanceTo);
  38571. if (computeDepthSort) {
  38572. if (distanceTo === undefined) {
  38573. distanceTo = BABYLON.Vector3.Zero();
  38574. }
  38575. var depthSortedFacets = options.depthSortedFacets;
  38576. }
  38577. }
  38578. // facetPartitioning reinit if needed
  38579. var xSubRatio = 0;
  38580. var ySubRatio = 0;
  38581. var zSubRatio = 0;
  38582. var subSq = 0;
  38583. if (computeFacetPartitioning && options && options.bbSize) {
  38584. var ox = 0; // X partitioning index for facet position
  38585. var oy = 0; // Y partinioning index for facet position
  38586. var oz = 0; // Z partinioning index for facet position
  38587. var b1x = 0; // X partitioning index for facet v1 vertex
  38588. var b1y = 0; // Y partitioning index for facet v1 vertex
  38589. var b1z = 0; // z partitioning index for facet v1 vertex
  38590. var b2x = 0; // X partitioning index for facet v2 vertex
  38591. var b2y = 0; // Y partitioning index for facet v2 vertex
  38592. var b2z = 0; // Z partitioning index for facet v2 vertex
  38593. var b3x = 0; // X partitioning index for facet v3 vertex
  38594. var b3y = 0; // Y partitioning index for facet v3 vertex
  38595. var b3z = 0; // Z partitioning index for facet v3 vertex
  38596. var block_idx_o = 0; // facet barycenter block index
  38597. var block_idx_v1 = 0; // v1 vertex block index
  38598. var block_idx_v2 = 0; // v2 vertex block index
  38599. var block_idx_v3 = 0; // v3 vertex block index
  38600. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38601. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38602. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38603. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38604. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38605. subSq = options.subDiv.max * options.subDiv.max;
  38606. options.facetPartitioning.length = 0;
  38607. }
  38608. // reset the normals
  38609. for (index = 0; index < positions.length; index++) {
  38610. normals[index] = 0.0;
  38611. }
  38612. // Loop : 1 indice triplet = 1 facet
  38613. var nbFaces = (indices.length / 3) | 0;
  38614. for (index = 0; index < nbFaces; index++) {
  38615. // get the indexes of the coordinates of each vertex of the facet
  38616. v1x = indices[index * 3] * 3;
  38617. v1y = v1x + 1;
  38618. v1z = v1x + 2;
  38619. v2x = indices[index * 3 + 1] * 3;
  38620. v2y = v2x + 1;
  38621. v2z = v2x + 2;
  38622. v3x = indices[index * 3 + 2] * 3;
  38623. v3y = v3x + 1;
  38624. v3z = v3x + 2;
  38625. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38626. p1p2y = positions[v1y] - positions[v2y];
  38627. p1p2z = positions[v1z] - positions[v2z];
  38628. p3p2x = positions[v3x] - positions[v2x];
  38629. p3p2y = positions[v3y] - positions[v2y];
  38630. p3p2z = positions[v3z] - positions[v2z];
  38631. // compute the face normal with the cross product
  38632. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38633. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38634. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38635. // normalize this normal and store it in the array facetData
  38636. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38637. length = (length === 0) ? 1.0 : length;
  38638. faceNormalx /= length;
  38639. faceNormaly /= length;
  38640. faceNormalz /= length;
  38641. if (computeFacetNormals && options) {
  38642. options.facetNormals[index].x = faceNormalx;
  38643. options.facetNormals[index].y = faceNormaly;
  38644. options.facetNormals[index].z = faceNormalz;
  38645. }
  38646. if (computeFacetPositions && options) {
  38647. // compute and the facet barycenter coordinates in the array facetPositions
  38648. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38649. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38650. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38651. }
  38652. if (computeFacetPartitioning && options) {
  38653. // store the facet indexes in arrays in the main facetPartitioning array :
  38654. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38655. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38656. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38657. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38658. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38659. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38660. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38661. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38662. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38663. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38664. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38665. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38666. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38667. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38668. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38669. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38670. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38671. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38672. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38673. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38674. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38675. // push each facet index in each block containing the vertex
  38676. options.facetPartitioning[block_idx_v1].push(index);
  38677. if (block_idx_v2 != block_idx_v1) {
  38678. options.facetPartitioning[block_idx_v2].push(index);
  38679. }
  38680. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38681. options.facetPartitioning[block_idx_v3].push(index);
  38682. }
  38683. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38684. options.facetPartitioning[block_idx_o].push(index);
  38685. }
  38686. }
  38687. if (computeDepthSort && options && options.facetPositions) {
  38688. var dsf = depthSortedFacets[index];
  38689. dsf.ind = index * 3;
  38690. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38691. }
  38692. // compute the normals anyway
  38693. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38694. normals[v1y] += faceNormaly;
  38695. normals[v1z] += faceNormalz;
  38696. normals[v2x] += faceNormalx;
  38697. normals[v2y] += faceNormaly;
  38698. normals[v2z] += faceNormalz;
  38699. normals[v3x] += faceNormalx;
  38700. normals[v3y] += faceNormaly;
  38701. normals[v3z] += faceNormalz;
  38702. }
  38703. // last normalization of each normal
  38704. for (index = 0; index < normals.length / 3; index++) {
  38705. faceNormalx = normals[index * 3];
  38706. faceNormaly = normals[index * 3 + 1];
  38707. faceNormalz = normals[index * 3 + 2];
  38708. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38709. length = (length === 0) ? 1.0 : length;
  38710. faceNormalx /= length;
  38711. faceNormaly /= length;
  38712. faceNormalz /= length;
  38713. normals[index * 3] = faceNormalx;
  38714. normals[index * 3 + 1] = faceNormaly;
  38715. normals[index * 3 + 2] = faceNormalz;
  38716. }
  38717. };
  38718. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38719. var li = indices.length;
  38720. var ln = normals.length;
  38721. var i;
  38722. var n;
  38723. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38724. switch (sideOrientation) {
  38725. case BABYLON.Mesh.FRONTSIDE:
  38726. // nothing changed
  38727. break;
  38728. case BABYLON.Mesh.BACKSIDE:
  38729. var tmp;
  38730. // indices
  38731. for (i = 0; i < li; i += 3) {
  38732. tmp = indices[i];
  38733. indices[i] = indices[i + 2];
  38734. indices[i + 2] = tmp;
  38735. }
  38736. // normals
  38737. for (n = 0; n < ln; n++) {
  38738. normals[n] = -normals[n];
  38739. }
  38740. break;
  38741. case BABYLON.Mesh.DOUBLESIDE:
  38742. // positions
  38743. var lp = positions.length;
  38744. var l = lp / 3;
  38745. for (var p = 0; p < lp; p++) {
  38746. positions[lp + p] = positions[p];
  38747. }
  38748. // indices
  38749. for (i = 0; i < li; i += 3) {
  38750. indices[i + li] = indices[i + 2] + l;
  38751. indices[i + 1 + li] = indices[i + 1] + l;
  38752. indices[i + 2 + li] = indices[i] + l;
  38753. }
  38754. // normals
  38755. for (n = 0; n < ln; n++) {
  38756. normals[ln + n] = -normals[n];
  38757. }
  38758. // uvs
  38759. var lu = uvs.length;
  38760. var u = 0;
  38761. for (u = 0; u < lu; u++) {
  38762. uvs[u + lu] = uvs[u];
  38763. }
  38764. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38765. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38766. u = 0;
  38767. for (i = 0; i < lu / 2; i++) {
  38768. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38769. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38770. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38771. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38772. u += 2;
  38773. }
  38774. break;
  38775. }
  38776. };
  38777. /**
  38778. * Applies VertexData created from the imported parameters to the geometry
  38779. * @param parsedVertexData the parsed data from an imported file
  38780. * @param geometry the geometry to apply the VertexData to
  38781. */
  38782. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38783. var vertexData = new VertexData();
  38784. // positions
  38785. var positions = parsedVertexData.positions;
  38786. if (positions) {
  38787. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38788. }
  38789. // normals
  38790. var normals = parsedVertexData.normals;
  38791. if (normals) {
  38792. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38793. }
  38794. // tangents
  38795. var tangents = parsedVertexData.tangents;
  38796. if (tangents) {
  38797. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38798. }
  38799. // uvs
  38800. var uvs = parsedVertexData.uvs;
  38801. if (uvs) {
  38802. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38803. }
  38804. // uv2s
  38805. var uv2s = parsedVertexData.uv2s;
  38806. if (uv2s) {
  38807. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38808. }
  38809. // uv3s
  38810. var uv3s = parsedVertexData.uv3s;
  38811. if (uv3s) {
  38812. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38813. }
  38814. // uv4s
  38815. var uv4s = parsedVertexData.uv4s;
  38816. if (uv4s) {
  38817. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38818. }
  38819. // uv5s
  38820. var uv5s = parsedVertexData.uv5s;
  38821. if (uv5s) {
  38822. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38823. }
  38824. // uv6s
  38825. var uv6s = parsedVertexData.uv6s;
  38826. if (uv6s) {
  38827. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38828. }
  38829. // colors
  38830. var colors = parsedVertexData.colors;
  38831. if (colors) {
  38832. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38833. }
  38834. // matricesIndices
  38835. var matricesIndices = parsedVertexData.matricesIndices;
  38836. if (matricesIndices) {
  38837. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38838. }
  38839. // matricesWeights
  38840. var matricesWeights = parsedVertexData.matricesWeights;
  38841. if (matricesWeights) {
  38842. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38843. }
  38844. // indices
  38845. var indices = parsedVertexData.indices;
  38846. if (indices) {
  38847. vertexData.indices = indices;
  38848. }
  38849. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38850. };
  38851. return VertexData;
  38852. }());
  38853. BABYLON.VertexData = VertexData;
  38854. })(BABYLON || (BABYLON = {}));
  38855. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38856. var BABYLON;
  38857. (function (BABYLON) {
  38858. /**
  38859. * Class used to store geometry data (vertex buffers + index buffer)
  38860. */
  38861. var Geometry = /** @class */ (function () {
  38862. /**
  38863. * Creates a new geometry
  38864. * @param id defines the unique ID
  38865. * @param scene defines the hosting scene
  38866. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38867. * @param updatable defines if geometry must be updatable (false by default)
  38868. * @param mesh defines the mesh that will be associated with the geometry
  38869. */
  38870. function Geometry(id, scene, vertexData, updatable, mesh) {
  38871. if (updatable === void 0) { updatable = false; }
  38872. if (mesh === void 0) { mesh = null; }
  38873. /**
  38874. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38875. */
  38876. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38877. this._totalVertices = 0;
  38878. this._isDisposed = false;
  38879. this._indexBufferIsUpdatable = false;
  38880. this.id = id;
  38881. this._engine = scene.getEngine();
  38882. this._meshes = [];
  38883. this._scene = scene;
  38884. //Init vertex buffer cache
  38885. this._vertexBuffers = {};
  38886. this._indices = [];
  38887. this._updatable = updatable;
  38888. // vertexData
  38889. if (vertexData) {
  38890. this.setAllVerticesData(vertexData, updatable);
  38891. }
  38892. else {
  38893. this._totalVertices = 0;
  38894. this._indices = [];
  38895. }
  38896. if (this._engine.getCaps().vertexArrayObject) {
  38897. this._vertexArrayObjects = {};
  38898. }
  38899. // applyToMesh
  38900. if (mesh) {
  38901. if (mesh.getClassName() === "LinesMesh") {
  38902. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38903. this._updateExtend();
  38904. }
  38905. this.applyToMesh(mesh);
  38906. mesh.computeWorldMatrix(true);
  38907. }
  38908. }
  38909. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38910. /**
  38911. * 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
  38912. */
  38913. get: function () {
  38914. return this._boundingBias;
  38915. },
  38916. /**
  38917. * 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
  38918. */
  38919. set: function (value) {
  38920. if (this._boundingBias && this._boundingBias.equals(value)) {
  38921. return;
  38922. }
  38923. this._boundingBias = value.clone();
  38924. this._updateBoundingInfo(true, null);
  38925. },
  38926. enumerable: true,
  38927. configurable: true
  38928. });
  38929. /**
  38930. * Static function used to attach a new empty geometry to a mesh
  38931. * @param mesh defines the mesh to attach the geometry to
  38932. * @returns the new {BABYLON.Geometry}
  38933. */
  38934. Geometry.CreateGeometryForMesh = function (mesh) {
  38935. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38936. geometry.applyToMesh(mesh);
  38937. return geometry;
  38938. };
  38939. Object.defineProperty(Geometry.prototype, "extend", {
  38940. /**
  38941. * Gets the current extend of the geometry
  38942. */
  38943. get: function () {
  38944. return this._extend;
  38945. },
  38946. enumerable: true,
  38947. configurable: true
  38948. });
  38949. /**
  38950. * Gets the hosting scene
  38951. * @returns the hosting {BABYLON.Scene}
  38952. */
  38953. Geometry.prototype.getScene = function () {
  38954. return this._scene;
  38955. };
  38956. /**
  38957. * Gets the hosting engine
  38958. * @returns the hosting {BABYLON.Engine}
  38959. */
  38960. Geometry.prototype.getEngine = function () {
  38961. return this._engine;
  38962. };
  38963. /**
  38964. * Defines if the geometry is ready to use
  38965. * @returns true if the geometry is ready to be used
  38966. */
  38967. Geometry.prototype.isReady = function () {
  38968. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38969. };
  38970. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38971. /**
  38972. * Gets a value indicating that the geometry should not be serialized
  38973. */
  38974. get: function () {
  38975. for (var index = 0; index < this._meshes.length; index++) {
  38976. if (!this._meshes[index].doNotSerialize) {
  38977. return false;
  38978. }
  38979. }
  38980. return true;
  38981. },
  38982. enumerable: true,
  38983. configurable: true
  38984. });
  38985. /** @hidden */
  38986. Geometry.prototype._rebuild = function () {
  38987. if (this._vertexArrayObjects) {
  38988. this._vertexArrayObjects = {};
  38989. }
  38990. // Index buffer
  38991. if (this._meshes.length !== 0 && this._indices) {
  38992. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38993. }
  38994. // Vertex buffers
  38995. for (var key in this._vertexBuffers) {
  38996. var vertexBuffer = this._vertexBuffers[key];
  38997. vertexBuffer._rebuild();
  38998. }
  38999. };
  39000. /**
  39001. * Affects all geometry data in one call
  39002. * @param vertexData defines the geometry data
  39003. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39004. */
  39005. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39006. vertexData.applyToGeometry(this, updatable);
  39007. this.notifyUpdate();
  39008. };
  39009. /**
  39010. * Set specific vertex data
  39011. * @param kind defines the data kind (Position, normal, etc...)
  39012. * @param data defines the vertex data to use
  39013. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39014. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39015. */
  39016. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39017. if (updatable === void 0) { updatable = false; }
  39018. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39019. this.setVerticesBuffer(buffer);
  39020. };
  39021. /**
  39022. * Removes a specific vertex data
  39023. * @param kind defines the data kind (Position, normal, etc...)
  39024. */
  39025. Geometry.prototype.removeVerticesData = function (kind) {
  39026. if (this._vertexBuffers[kind]) {
  39027. this._vertexBuffers[kind].dispose();
  39028. delete this._vertexBuffers[kind];
  39029. }
  39030. };
  39031. /**
  39032. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39033. * @param buffer defines the vertex buffer to use
  39034. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39035. */
  39036. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39037. if (totalVertices === void 0) { totalVertices = null; }
  39038. var kind = buffer.getKind();
  39039. if (this._vertexBuffers[kind]) {
  39040. this._vertexBuffers[kind].dispose();
  39041. }
  39042. this._vertexBuffers[kind] = buffer;
  39043. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39044. var data = buffer.getData();
  39045. if (totalVertices != null) {
  39046. this._totalVertices = totalVertices;
  39047. }
  39048. else {
  39049. if (data != null) {
  39050. this._totalVertices = data.length / (buffer.byteStride / 4);
  39051. }
  39052. }
  39053. this._updateExtend(data);
  39054. this._resetPointsArrayCache();
  39055. var meshes = this._meshes;
  39056. var numOfMeshes = meshes.length;
  39057. for (var index = 0; index < numOfMeshes; index++) {
  39058. var mesh = meshes[index];
  39059. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39060. mesh._createGlobalSubMesh(false);
  39061. mesh.computeWorldMatrix(true);
  39062. }
  39063. }
  39064. this.notifyUpdate(kind);
  39065. if (this._vertexArrayObjects) {
  39066. this._disposeVertexArrayObjects();
  39067. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39068. }
  39069. };
  39070. /**
  39071. * Update a specific vertex buffer
  39072. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39073. * It will do nothing if the buffer is not updatable
  39074. * @param kind defines the data kind (Position, normal, etc...)
  39075. * @param data defines the data to use
  39076. * @param offset defines the offset in the target buffer where to store the data
  39077. * @param useBytes set to true if the offset is in bytes
  39078. */
  39079. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39080. if (useBytes === void 0) { useBytes = false; }
  39081. var vertexBuffer = this.getVertexBuffer(kind);
  39082. if (!vertexBuffer) {
  39083. return;
  39084. }
  39085. vertexBuffer.updateDirectly(data, offset, useBytes);
  39086. this.notifyUpdate(kind);
  39087. };
  39088. /**
  39089. * Update a specific vertex buffer
  39090. * This function will create a new buffer if the current one is not updatable
  39091. * @param kind defines the data kind (Position, normal, etc...)
  39092. * @param data defines the data to use
  39093. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39094. */
  39095. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39096. if (updateExtends === void 0) { updateExtends = false; }
  39097. var vertexBuffer = this.getVertexBuffer(kind);
  39098. if (!vertexBuffer) {
  39099. return;
  39100. }
  39101. vertexBuffer.update(data);
  39102. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39103. this._updateBoundingInfo(updateExtends, data);
  39104. }
  39105. this.notifyUpdate(kind);
  39106. };
  39107. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39108. if (updateExtends) {
  39109. this._updateExtend(data);
  39110. }
  39111. var meshes = this._meshes;
  39112. var numOfMeshes = meshes.length;
  39113. this._resetPointsArrayCache();
  39114. for (var index = 0; index < numOfMeshes; index++) {
  39115. var mesh = meshes[index];
  39116. if (updateExtends) {
  39117. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39118. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39119. var subMesh = mesh.subMeshes[subIndex];
  39120. subMesh.refreshBoundingInfo();
  39121. }
  39122. }
  39123. }
  39124. };
  39125. /** @hidden */
  39126. Geometry.prototype._bind = function (effect, indexToBind) {
  39127. if (!effect) {
  39128. return;
  39129. }
  39130. if (indexToBind === undefined) {
  39131. indexToBind = this._indexBuffer;
  39132. }
  39133. var vbs = this.getVertexBuffers();
  39134. if (!vbs) {
  39135. return;
  39136. }
  39137. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39138. this._engine.bindBuffers(vbs, indexToBind, effect);
  39139. return;
  39140. }
  39141. // Using VAO
  39142. if (!this._vertexArrayObjects[effect.key]) {
  39143. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39144. }
  39145. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39146. };
  39147. /**
  39148. * Gets total number of vertices
  39149. * @returns the total number of vertices
  39150. */
  39151. Geometry.prototype.getTotalVertices = function () {
  39152. if (!this.isReady()) {
  39153. return 0;
  39154. }
  39155. return this._totalVertices;
  39156. };
  39157. /**
  39158. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39159. * @param kind defines the data kind (Position, normal, etc...)
  39160. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39161. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39162. * @returns a float array containing vertex data
  39163. */
  39164. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39165. var vertexBuffer = this.getVertexBuffer(kind);
  39166. if (!vertexBuffer) {
  39167. return null;
  39168. }
  39169. var data = vertexBuffer.getData();
  39170. if (!data) {
  39171. return null;
  39172. }
  39173. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39174. var count = this._totalVertices * vertexBuffer.getSize();
  39175. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39176. var copy_1 = new Array(count);
  39177. vertexBuffer.forEach(count, function (value, index) {
  39178. copy_1[index] = value;
  39179. });
  39180. return copy_1;
  39181. }
  39182. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39183. if (data instanceof Array) {
  39184. var offset = vertexBuffer.byteOffset / 4;
  39185. return BABYLON.Tools.Slice(data, offset, offset + count);
  39186. }
  39187. else if (data instanceof ArrayBuffer) {
  39188. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39189. }
  39190. else {
  39191. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39192. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39193. var result = new Float32Array(count);
  39194. var source = new Float32Array(data.buffer, offset, count);
  39195. result.set(source);
  39196. return result;
  39197. }
  39198. return new Float32Array(data.buffer, offset, count);
  39199. }
  39200. }
  39201. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39202. return BABYLON.Tools.Slice(data);
  39203. }
  39204. return data;
  39205. };
  39206. /**
  39207. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39208. * @param kind defines the data kind (Position, normal, etc...)
  39209. * @returns true if the vertex buffer with the specified kind is updatable
  39210. */
  39211. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39212. var vb = this._vertexBuffers[kind];
  39213. if (!vb) {
  39214. return false;
  39215. }
  39216. return vb.isUpdatable();
  39217. };
  39218. /**
  39219. * Gets a specific vertex buffer
  39220. * @param kind defines the data kind (Position, normal, etc...)
  39221. * @returns a {BABYLON.VertexBuffer}
  39222. */
  39223. Geometry.prototype.getVertexBuffer = function (kind) {
  39224. if (!this.isReady()) {
  39225. return null;
  39226. }
  39227. return this._vertexBuffers[kind];
  39228. };
  39229. /**
  39230. * Returns all vertex buffers
  39231. * @return an object holding all vertex buffers indexed by kind
  39232. */
  39233. Geometry.prototype.getVertexBuffers = function () {
  39234. if (!this.isReady()) {
  39235. return null;
  39236. }
  39237. return this._vertexBuffers;
  39238. };
  39239. /**
  39240. * Gets a boolean indicating if specific vertex buffer is present
  39241. * @param kind defines the data kind (Position, normal, etc...)
  39242. * @returns true if data is present
  39243. */
  39244. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39245. if (!this._vertexBuffers) {
  39246. if (this._delayInfo) {
  39247. return this._delayInfo.indexOf(kind) !== -1;
  39248. }
  39249. return false;
  39250. }
  39251. return this._vertexBuffers[kind] !== undefined;
  39252. };
  39253. /**
  39254. * Gets a list of all attached data kinds (Position, normal, etc...)
  39255. * @returns a list of string containing all kinds
  39256. */
  39257. Geometry.prototype.getVerticesDataKinds = function () {
  39258. var result = [];
  39259. var kind;
  39260. if (!this._vertexBuffers && this._delayInfo) {
  39261. for (kind in this._delayInfo) {
  39262. result.push(kind);
  39263. }
  39264. }
  39265. else {
  39266. for (kind in this._vertexBuffers) {
  39267. result.push(kind);
  39268. }
  39269. }
  39270. return result;
  39271. };
  39272. /**
  39273. * Update index buffer
  39274. * @param indices defines the indices to store in the index buffer
  39275. * @param offset defines the offset in the target buffer where to store the data
  39276. */
  39277. Geometry.prototype.updateIndices = function (indices, offset) {
  39278. if (!this._indexBuffer) {
  39279. return;
  39280. }
  39281. if (!this._indexBufferIsUpdatable) {
  39282. this.setIndices(indices, null, true);
  39283. }
  39284. else {
  39285. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39286. }
  39287. };
  39288. /**
  39289. * Creates a new index buffer
  39290. * @param indices defines the indices to store in the index buffer
  39291. * @param totalVertices defines the total number of vertices (could be null)
  39292. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39293. */
  39294. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39295. if (totalVertices === void 0) { totalVertices = null; }
  39296. if (updatable === void 0) { updatable = false; }
  39297. if (this._indexBuffer) {
  39298. this._engine._releaseBuffer(this._indexBuffer);
  39299. }
  39300. this._disposeVertexArrayObjects();
  39301. this._indices = indices;
  39302. this._indexBufferIsUpdatable = updatable;
  39303. if (this._meshes.length !== 0 && this._indices) {
  39304. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39305. }
  39306. if (totalVertices != undefined) { // including null and undefined
  39307. this._totalVertices = totalVertices;
  39308. }
  39309. var meshes = this._meshes;
  39310. var numOfMeshes = meshes.length;
  39311. for (var index = 0; index < numOfMeshes; index++) {
  39312. meshes[index]._createGlobalSubMesh(true);
  39313. }
  39314. this.notifyUpdate();
  39315. };
  39316. /**
  39317. * Return the total number of indices
  39318. * @returns the total number of indices
  39319. */
  39320. Geometry.prototype.getTotalIndices = function () {
  39321. if (!this.isReady()) {
  39322. return 0;
  39323. }
  39324. return this._indices.length;
  39325. };
  39326. /**
  39327. * Gets the index buffer array
  39328. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39329. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39330. * @returns the index buffer array
  39331. */
  39332. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39333. if (!this.isReady()) {
  39334. return null;
  39335. }
  39336. var orig = this._indices;
  39337. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39338. return orig;
  39339. }
  39340. else {
  39341. var len = orig.length;
  39342. var copy = [];
  39343. for (var i = 0; i < len; i++) {
  39344. copy.push(orig[i]);
  39345. }
  39346. return copy;
  39347. }
  39348. };
  39349. /**
  39350. * Gets the index buffer
  39351. * @return the index buffer
  39352. */
  39353. Geometry.prototype.getIndexBuffer = function () {
  39354. if (!this.isReady()) {
  39355. return null;
  39356. }
  39357. return this._indexBuffer;
  39358. };
  39359. /** @hidden */
  39360. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39361. if (effect === void 0) { effect = null; }
  39362. if (!effect || !this._vertexArrayObjects) {
  39363. return;
  39364. }
  39365. if (this._vertexArrayObjects[effect.key]) {
  39366. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39367. delete this._vertexArrayObjects[effect.key];
  39368. }
  39369. };
  39370. /**
  39371. * Release the associated resources for a specific mesh
  39372. * @param mesh defines the source mesh
  39373. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39374. */
  39375. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39376. var meshes = this._meshes;
  39377. var index = meshes.indexOf(mesh);
  39378. if (index === -1) {
  39379. return;
  39380. }
  39381. meshes.splice(index, 1);
  39382. mesh._geometry = null;
  39383. if (meshes.length === 0 && shouldDispose) {
  39384. this.dispose();
  39385. }
  39386. };
  39387. /**
  39388. * Apply current geometry to a given mesh
  39389. * @param mesh defines the mesh to apply geometry to
  39390. */
  39391. Geometry.prototype.applyToMesh = function (mesh) {
  39392. if (mesh._geometry === this) {
  39393. return;
  39394. }
  39395. var previousGeometry = mesh._geometry;
  39396. if (previousGeometry) {
  39397. previousGeometry.releaseForMesh(mesh);
  39398. }
  39399. var meshes = this._meshes;
  39400. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39401. mesh._geometry = this;
  39402. this._scene.pushGeometry(this);
  39403. meshes.push(mesh);
  39404. if (this.isReady()) {
  39405. this._applyToMesh(mesh);
  39406. }
  39407. else {
  39408. mesh._boundingInfo = this._boundingInfo;
  39409. }
  39410. };
  39411. Geometry.prototype._updateExtend = function (data) {
  39412. if (data === void 0) { data = null; }
  39413. if (!data) {
  39414. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39415. }
  39416. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39417. };
  39418. Geometry.prototype._applyToMesh = function (mesh) {
  39419. var numOfMeshes = this._meshes.length;
  39420. // vertexBuffers
  39421. for (var kind in this._vertexBuffers) {
  39422. if (numOfMeshes === 1) {
  39423. this._vertexBuffers[kind].create();
  39424. }
  39425. var buffer = this._vertexBuffers[kind].getBuffer();
  39426. if (buffer)
  39427. buffer.references = numOfMeshes;
  39428. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39429. if (!this._extend) {
  39430. this._updateExtend();
  39431. }
  39432. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39433. mesh._createGlobalSubMesh(false);
  39434. //bounding info was just created again, world matrix should be applied again.
  39435. mesh._updateBoundingInfo();
  39436. }
  39437. }
  39438. // indexBuffer
  39439. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39440. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39441. }
  39442. if (this._indexBuffer) {
  39443. this._indexBuffer.references = numOfMeshes;
  39444. }
  39445. };
  39446. Geometry.prototype.notifyUpdate = function (kind) {
  39447. if (this.onGeometryUpdated) {
  39448. this.onGeometryUpdated(this, kind);
  39449. }
  39450. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39451. var mesh = _a[_i];
  39452. mesh._markSubMeshesAsAttributesDirty();
  39453. }
  39454. };
  39455. /**
  39456. * Load the geometry if it was flagged as delay loaded
  39457. * @param scene defines the hosting scene
  39458. * @param onLoaded defines a callback called when the geometry is loaded
  39459. */
  39460. Geometry.prototype.load = function (scene, onLoaded) {
  39461. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39462. return;
  39463. }
  39464. if (this.isReady()) {
  39465. if (onLoaded) {
  39466. onLoaded();
  39467. }
  39468. return;
  39469. }
  39470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39471. this._queueLoad(scene, onLoaded);
  39472. };
  39473. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39474. var _this = this;
  39475. if (!this.delayLoadingFile) {
  39476. return;
  39477. }
  39478. scene._addPendingData(this);
  39479. scene._loadFile(this.delayLoadingFile, function (data) {
  39480. if (!_this._delayLoadingFunction) {
  39481. return;
  39482. }
  39483. _this._delayLoadingFunction(JSON.parse(data), _this);
  39484. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39485. _this._delayInfo = [];
  39486. scene._removePendingData(_this);
  39487. var meshes = _this._meshes;
  39488. var numOfMeshes = meshes.length;
  39489. for (var index = 0; index < numOfMeshes; index++) {
  39490. _this._applyToMesh(meshes[index]);
  39491. }
  39492. if (onLoaded) {
  39493. onLoaded();
  39494. }
  39495. }, undefined, true);
  39496. };
  39497. /**
  39498. * Invert the geometry to move from a right handed system to a left handed one.
  39499. */
  39500. Geometry.prototype.toLeftHanded = function () {
  39501. // Flip faces
  39502. var tIndices = this.getIndices(false);
  39503. if (tIndices != null && tIndices.length > 0) {
  39504. for (var i = 0; i < tIndices.length; i += 3) {
  39505. var tTemp = tIndices[i + 0];
  39506. tIndices[i + 0] = tIndices[i + 2];
  39507. tIndices[i + 2] = tTemp;
  39508. }
  39509. this.setIndices(tIndices);
  39510. }
  39511. // Negate position.z
  39512. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39513. if (tPositions != null && tPositions.length > 0) {
  39514. for (var i = 0; i < tPositions.length; i += 3) {
  39515. tPositions[i + 2] = -tPositions[i + 2];
  39516. }
  39517. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39518. }
  39519. // Negate normal.z
  39520. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39521. if (tNormals != null && tNormals.length > 0) {
  39522. for (var i = 0; i < tNormals.length; i += 3) {
  39523. tNormals[i + 2] = -tNormals[i + 2];
  39524. }
  39525. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39526. }
  39527. };
  39528. // Cache
  39529. /** @hidden */
  39530. Geometry.prototype._resetPointsArrayCache = function () {
  39531. this._positions = null;
  39532. };
  39533. /** @hidden */
  39534. Geometry.prototype._generatePointsArray = function () {
  39535. if (this._positions)
  39536. return true;
  39537. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39538. if (!data || data.length === 0) {
  39539. return false;
  39540. }
  39541. this._positions = [];
  39542. for (var index = 0; index < data.length; index += 3) {
  39543. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39544. }
  39545. return true;
  39546. };
  39547. /**
  39548. * Gets a value indicating if the geometry is disposed
  39549. * @returns true if the geometry was disposed
  39550. */
  39551. Geometry.prototype.isDisposed = function () {
  39552. return this._isDisposed;
  39553. };
  39554. Geometry.prototype._disposeVertexArrayObjects = function () {
  39555. if (this._vertexArrayObjects) {
  39556. for (var kind in this._vertexArrayObjects) {
  39557. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39558. }
  39559. this._vertexArrayObjects = {};
  39560. }
  39561. };
  39562. /**
  39563. * Free all associated resources
  39564. */
  39565. Geometry.prototype.dispose = function () {
  39566. var meshes = this._meshes;
  39567. var numOfMeshes = meshes.length;
  39568. var index;
  39569. for (index = 0; index < numOfMeshes; index++) {
  39570. this.releaseForMesh(meshes[index]);
  39571. }
  39572. this._meshes = [];
  39573. this._disposeVertexArrayObjects();
  39574. for (var kind in this._vertexBuffers) {
  39575. this._vertexBuffers[kind].dispose();
  39576. }
  39577. this._vertexBuffers = {};
  39578. this._totalVertices = 0;
  39579. if (this._indexBuffer) {
  39580. this._engine._releaseBuffer(this._indexBuffer);
  39581. }
  39582. this._indexBuffer = null;
  39583. this._indices = [];
  39584. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39585. this.delayLoadingFile = null;
  39586. this._delayLoadingFunction = null;
  39587. this._delayInfo = [];
  39588. this._boundingInfo = null;
  39589. this._scene.removeGeometry(this);
  39590. this._isDisposed = true;
  39591. };
  39592. /**
  39593. * Clone the current geometry into a new geometry
  39594. * @param id defines the unique ID of the new geometry
  39595. * @returns a new geometry object
  39596. */
  39597. Geometry.prototype.copy = function (id) {
  39598. var vertexData = new BABYLON.VertexData();
  39599. vertexData.indices = [];
  39600. var indices = this.getIndices();
  39601. if (indices) {
  39602. for (var index = 0; index < indices.length; index++) {
  39603. vertexData.indices.push(indices[index]);
  39604. }
  39605. }
  39606. var updatable = false;
  39607. var stopChecking = false;
  39608. var kind;
  39609. for (kind in this._vertexBuffers) {
  39610. // using slice() to make a copy of the array and not just reference it
  39611. var data = this.getVerticesData(kind);
  39612. if (data instanceof Float32Array) {
  39613. vertexData.set(new Float32Array(data), kind);
  39614. }
  39615. else {
  39616. vertexData.set(data.slice(0), kind);
  39617. }
  39618. if (!stopChecking) {
  39619. var vb = this.getVertexBuffer(kind);
  39620. if (vb) {
  39621. updatable = vb.isUpdatable();
  39622. stopChecking = !updatable;
  39623. }
  39624. }
  39625. }
  39626. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39627. geometry.delayLoadState = this.delayLoadState;
  39628. geometry.delayLoadingFile = this.delayLoadingFile;
  39629. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39630. for (kind in this._delayInfo) {
  39631. geometry._delayInfo = geometry._delayInfo || [];
  39632. geometry._delayInfo.push(kind);
  39633. }
  39634. // Bounding info
  39635. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39636. return geometry;
  39637. };
  39638. /**
  39639. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39640. * @return a JSON representation of the current geometry data (without the vertices data)
  39641. */
  39642. Geometry.prototype.serialize = function () {
  39643. var serializationObject = {};
  39644. serializationObject.id = this.id;
  39645. serializationObject.updatable = this._updatable;
  39646. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39647. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39648. }
  39649. return serializationObject;
  39650. };
  39651. Geometry.prototype.toNumberArray = function (origin) {
  39652. if (Array.isArray(origin)) {
  39653. return origin;
  39654. }
  39655. else {
  39656. return Array.prototype.slice.call(origin);
  39657. }
  39658. };
  39659. /**
  39660. * Serialize all vertices data into a JSON oject
  39661. * @returns a JSON representation of the current geometry data
  39662. */
  39663. Geometry.prototype.serializeVerticeData = function () {
  39664. var serializationObject = this.serialize();
  39665. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39666. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39667. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39668. serializationObject.positions._updatable = true;
  39669. }
  39670. }
  39671. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39672. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39673. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39674. serializationObject.normals._updatable = true;
  39675. }
  39676. }
  39677. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39678. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39679. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39680. serializationObject.tangets._updatable = true;
  39681. }
  39682. }
  39683. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39684. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39685. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39686. serializationObject.uvs._updatable = true;
  39687. }
  39688. }
  39689. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39690. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39691. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39692. serializationObject.uv2s._updatable = true;
  39693. }
  39694. }
  39695. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39696. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39697. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39698. serializationObject.uv3s._updatable = true;
  39699. }
  39700. }
  39701. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39702. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39703. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39704. serializationObject.uv4s._updatable = true;
  39705. }
  39706. }
  39707. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39708. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39709. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39710. serializationObject.uv5s._updatable = true;
  39711. }
  39712. }
  39713. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39714. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39715. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39716. serializationObject.uv6s._updatable = true;
  39717. }
  39718. }
  39719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39720. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39721. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39722. serializationObject.colors._updatable = true;
  39723. }
  39724. }
  39725. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39726. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39727. serializationObject.matricesIndices._isExpanded = true;
  39728. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39729. serializationObject.matricesIndices._updatable = true;
  39730. }
  39731. }
  39732. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39733. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39734. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39735. serializationObject.matricesWeights._updatable = true;
  39736. }
  39737. }
  39738. serializationObject.indices = this.toNumberArray(this.getIndices());
  39739. return serializationObject;
  39740. };
  39741. // Statics
  39742. /**
  39743. * Extracts a clone of a mesh geometry
  39744. * @param mesh defines the source mesh
  39745. * @param id defines the unique ID of the new geometry object
  39746. * @returns the new geometry object
  39747. */
  39748. Geometry.ExtractFromMesh = function (mesh, id) {
  39749. var geometry = mesh._geometry;
  39750. if (!geometry) {
  39751. return null;
  39752. }
  39753. return geometry.copy(id);
  39754. };
  39755. /**
  39756. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39757. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39758. * Be aware Math.random() could cause collisions, but:
  39759. * "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"
  39760. * @returns a string containing a new GUID
  39761. */
  39762. Geometry.RandomId = function () {
  39763. return BABYLON.Tools.RandomId();
  39764. };
  39765. /** @hidden */
  39766. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39767. var scene = mesh.getScene();
  39768. // Geometry
  39769. var geometryId = parsedGeometry.geometryId;
  39770. if (geometryId) {
  39771. var geometry = scene.getGeometryByID(geometryId);
  39772. if (geometry) {
  39773. geometry.applyToMesh(mesh);
  39774. }
  39775. }
  39776. else if (parsedGeometry instanceof ArrayBuffer) {
  39777. var binaryInfo = mesh._binaryInfo;
  39778. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39779. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39780. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39781. }
  39782. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39783. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39784. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39785. }
  39786. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39787. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39788. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39789. }
  39790. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39791. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39792. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39793. }
  39794. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39795. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39796. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39797. }
  39798. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39799. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39800. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39801. }
  39802. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39803. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39804. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39805. }
  39806. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39807. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39808. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39809. }
  39810. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39811. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39812. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39813. }
  39814. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39815. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39816. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39817. }
  39818. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39819. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39820. var floatIndices = [];
  39821. for (var i = 0; i < matricesIndicesData.length; i++) {
  39822. var index = matricesIndicesData[i];
  39823. floatIndices.push(index & 0x000000FF);
  39824. floatIndices.push((index & 0x0000FF00) >> 8);
  39825. floatIndices.push((index & 0x00FF0000) >> 16);
  39826. floatIndices.push(index >> 24);
  39827. }
  39828. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39829. }
  39830. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39831. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39832. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39833. }
  39834. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39835. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39836. mesh.setIndices(indicesData, null);
  39837. }
  39838. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39839. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39840. mesh.subMeshes = [];
  39841. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39842. var materialIndex = subMeshesData[(i * 5) + 0];
  39843. var verticesStart = subMeshesData[(i * 5) + 1];
  39844. var verticesCount = subMeshesData[(i * 5) + 2];
  39845. var indexStart = subMeshesData[(i * 5) + 3];
  39846. var indexCount = subMeshesData[(i * 5) + 4];
  39847. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39848. }
  39849. }
  39850. }
  39851. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39852. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39853. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39854. if (parsedGeometry.tangents) {
  39855. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39856. }
  39857. if (parsedGeometry.uvs) {
  39858. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39859. }
  39860. if (parsedGeometry.uvs2) {
  39861. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39862. }
  39863. if (parsedGeometry.uvs3) {
  39864. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39865. }
  39866. if (parsedGeometry.uvs4) {
  39867. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39868. }
  39869. if (parsedGeometry.uvs5) {
  39870. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39871. }
  39872. if (parsedGeometry.uvs6) {
  39873. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39874. }
  39875. if (parsedGeometry.colors) {
  39876. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39877. }
  39878. if (parsedGeometry.matricesIndices) {
  39879. if (!parsedGeometry.matricesIndices._isExpanded) {
  39880. var floatIndices = [];
  39881. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39882. var matricesIndex = parsedGeometry.matricesIndices[i];
  39883. floatIndices.push(matricesIndex & 0x000000FF);
  39884. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39885. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39886. floatIndices.push(matricesIndex >> 24);
  39887. }
  39888. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39889. }
  39890. else {
  39891. delete parsedGeometry.matricesIndices._isExpanded;
  39892. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39893. }
  39894. }
  39895. if (parsedGeometry.matricesIndicesExtra) {
  39896. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39897. var floatIndices = [];
  39898. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39899. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39900. floatIndices.push(matricesIndex & 0x000000FF);
  39901. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39902. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39903. floatIndices.push(matricesIndex >> 24);
  39904. }
  39905. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39906. }
  39907. else {
  39908. delete parsedGeometry.matricesIndices._isExpanded;
  39909. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39910. }
  39911. }
  39912. if (parsedGeometry.matricesWeights) {
  39913. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39914. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39915. }
  39916. if (parsedGeometry.matricesWeightsExtra) {
  39917. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39918. }
  39919. mesh.setIndices(parsedGeometry.indices, null);
  39920. }
  39921. // SubMeshes
  39922. if (parsedGeometry.subMeshes) {
  39923. mesh.subMeshes = [];
  39924. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39925. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39926. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39927. }
  39928. }
  39929. // Flat shading
  39930. if (mesh._shouldGenerateFlatShading) {
  39931. mesh.convertToFlatShadedMesh();
  39932. delete mesh._shouldGenerateFlatShading;
  39933. }
  39934. // Update
  39935. mesh.computeWorldMatrix(true);
  39936. // Octree
  39937. var sceneOctree = scene.selectionOctree;
  39938. if (sceneOctree !== undefined && sceneOctree !== null) {
  39939. sceneOctree.addMesh(mesh);
  39940. }
  39941. };
  39942. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39943. var epsilon = 1e-3;
  39944. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39945. return;
  39946. }
  39947. var noInfluenceBoneIndex = 0.0;
  39948. if (parsedGeometry.skeletonId > -1) {
  39949. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39950. if (!skeleton) {
  39951. return;
  39952. }
  39953. noInfluenceBoneIndex = skeleton.bones.length;
  39954. }
  39955. else {
  39956. return;
  39957. }
  39958. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39959. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39960. var matricesWeights = parsedGeometry.matricesWeights;
  39961. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39962. var influencers = parsedGeometry.numBoneInfluencer;
  39963. var size = matricesWeights.length;
  39964. for (var i = 0; i < size; i += 4) {
  39965. var weight = 0.0;
  39966. var firstZeroWeight = -1;
  39967. for (var j = 0; j < 4; j++) {
  39968. var w = matricesWeights[i + j];
  39969. weight += w;
  39970. if (w < epsilon && firstZeroWeight < 0) {
  39971. firstZeroWeight = j;
  39972. }
  39973. }
  39974. if (matricesWeightsExtra) {
  39975. for (var j = 0; j < 4; j++) {
  39976. var w = matricesWeightsExtra[i + j];
  39977. weight += w;
  39978. if (w < epsilon && firstZeroWeight < 0) {
  39979. firstZeroWeight = j + 4;
  39980. }
  39981. }
  39982. }
  39983. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39984. firstZeroWeight = influencers - 1;
  39985. }
  39986. if (weight > epsilon) {
  39987. var mweight = 1.0 / weight;
  39988. for (var j = 0; j < 4; j++) {
  39989. matricesWeights[i + j] *= mweight;
  39990. }
  39991. if (matricesWeightsExtra) {
  39992. for (var j = 0; j < 4; j++) {
  39993. matricesWeightsExtra[i + j] *= mweight;
  39994. }
  39995. }
  39996. }
  39997. else {
  39998. if (firstZeroWeight >= 4) {
  39999. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40000. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40001. }
  40002. else {
  40003. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40004. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40005. }
  40006. }
  40007. }
  40008. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40009. if (parsedGeometry.matricesWeightsExtra) {
  40010. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40011. }
  40012. };
  40013. /**
  40014. * Create a new geometry from persisted data (Using .babylon file format)
  40015. * @param parsedVertexData defines the persisted data
  40016. * @param scene defines the hosting scene
  40017. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40018. * @returns the new geometry object
  40019. */
  40020. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40021. if (scene.getGeometryByID(parsedVertexData.id)) {
  40022. return null; // null since geometry could be something else than a box...
  40023. }
  40024. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40025. if (BABYLON.Tags) {
  40026. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40027. }
  40028. if (parsedVertexData.delayLoadingFile) {
  40029. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40030. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40031. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40032. geometry._delayInfo = [];
  40033. if (parsedVertexData.hasUVs) {
  40034. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40035. }
  40036. if (parsedVertexData.hasUVs2) {
  40037. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40038. }
  40039. if (parsedVertexData.hasUVs3) {
  40040. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40041. }
  40042. if (parsedVertexData.hasUVs4) {
  40043. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40044. }
  40045. if (parsedVertexData.hasUVs5) {
  40046. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40047. }
  40048. if (parsedVertexData.hasUVs6) {
  40049. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40050. }
  40051. if (parsedVertexData.hasColors) {
  40052. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40053. }
  40054. if (parsedVertexData.hasMatricesIndices) {
  40055. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40056. }
  40057. if (parsedVertexData.hasMatricesWeights) {
  40058. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40059. }
  40060. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40061. }
  40062. else {
  40063. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40064. }
  40065. scene.pushGeometry(geometry, true);
  40066. return geometry;
  40067. };
  40068. return Geometry;
  40069. }());
  40070. BABYLON.Geometry = Geometry;
  40071. // Primitives
  40072. /// Abstract class
  40073. /**
  40074. * Abstract class used to provide common services for all typed geometries
  40075. * @hidden
  40076. */
  40077. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40078. __extends(_PrimitiveGeometry, _super);
  40079. /**
  40080. * Creates a new typed geometry
  40081. * @param id defines the unique ID of the geometry
  40082. * @param scene defines the hosting scene
  40083. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40084. * @param mesh defines the hosting mesh (can be null)
  40085. */
  40086. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40087. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40088. if (mesh === void 0) { mesh = null; }
  40089. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40090. _this._canBeRegenerated = _canBeRegenerated;
  40091. _this._beingRegenerated = true;
  40092. _this.regenerate();
  40093. _this._beingRegenerated = false;
  40094. return _this;
  40095. }
  40096. /**
  40097. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40098. * @returns true if the geometry can be regenerated
  40099. */
  40100. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40101. return this._canBeRegenerated;
  40102. };
  40103. /**
  40104. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40105. */
  40106. _PrimitiveGeometry.prototype.regenerate = function () {
  40107. if (!this._canBeRegenerated) {
  40108. return;
  40109. }
  40110. this._beingRegenerated = true;
  40111. this.setAllVerticesData(this._regenerateVertexData(), false);
  40112. this._beingRegenerated = false;
  40113. };
  40114. /**
  40115. * Clone the geometry
  40116. * @param id defines the unique ID of the new geometry
  40117. * @returns the new geometry
  40118. */
  40119. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40120. return _super.prototype.copy.call(this, id);
  40121. };
  40122. // overrides
  40123. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40124. if (!this._beingRegenerated) {
  40125. return;
  40126. }
  40127. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40128. };
  40129. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40130. if (!this._beingRegenerated) {
  40131. return;
  40132. }
  40133. _super.prototype.setVerticesData.call(this, kind, data, false);
  40134. };
  40135. // to override
  40136. /** @hidden */
  40137. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40138. throw new Error("Abstract method");
  40139. };
  40140. _PrimitiveGeometry.prototype.copy = function (id) {
  40141. throw new Error("Must be overriden in sub-classes.");
  40142. };
  40143. _PrimitiveGeometry.prototype.serialize = function () {
  40144. var serializationObject = _super.prototype.serialize.call(this);
  40145. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40146. return serializationObject;
  40147. };
  40148. return _PrimitiveGeometry;
  40149. }(Geometry));
  40150. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40151. /**
  40152. * Creates a ribbon geometry
  40153. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40154. */
  40155. var RibbonGeometry = /** @class */ (function (_super) {
  40156. __extends(RibbonGeometry, _super);
  40157. /**
  40158. * Creates a ribbon geometry
  40159. * @param id defines the unique ID of the geometry
  40160. * @param scene defines the hosting scene
  40161. * @param pathArray defines the array of paths to use
  40162. * @param closeArray defines if the last path and the first path must be joined
  40163. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40164. * @param offset defines the offset between points
  40165. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40166. * @param mesh defines the hosting mesh (can be null)
  40167. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40168. */
  40169. function RibbonGeometry(id, scene,
  40170. /**
  40171. * Defines the array of paths to use
  40172. */
  40173. pathArray,
  40174. /**
  40175. * Defines if the last and first points of each path in your pathArray must be joined
  40176. */
  40177. closeArray,
  40178. /**
  40179. * Defines if the last and first points of each path in your pathArray must be joined
  40180. */
  40181. closePath,
  40182. /**
  40183. * Defines the offset between points
  40184. */
  40185. offset, canBeRegenerated, mesh,
  40186. /**
  40187. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40188. */
  40189. side) {
  40190. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40191. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40192. _this.pathArray = pathArray;
  40193. _this.closeArray = closeArray;
  40194. _this.closePath = closePath;
  40195. _this.offset = offset;
  40196. _this.side = side;
  40197. return _this;
  40198. }
  40199. /** @hidden */
  40200. RibbonGeometry.prototype._regenerateVertexData = function () {
  40201. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40202. };
  40203. RibbonGeometry.prototype.copy = function (id) {
  40204. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40205. };
  40206. return RibbonGeometry;
  40207. }(_PrimitiveGeometry));
  40208. BABYLON.RibbonGeometry = RibbonGeometry;
  40209. /**
  40210. * Creates a box geometry
  40211. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40212. */
  40213. var BoxGeometry = /** @class */ (function (_super) {
  40214. __extends(BoxGeometry, _super);
  40215. /**
  40216. * Creates a box geometry
  40217. * @param id defines the unique ID of the geometry
  40218. * @param scene defines the hosting scene
  40219. * @param size defines the zise of the box (width, height and depth are the same)
  40220. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40221. * @param mesh defines the hosting mesh (can be null)
  40222. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40223. */
  40224. function BoxGeometry(id, scene,
  40225. /**
  40226. * Defines the zise of the box (width, height and depth are the same)
  40227. */
  40228. size, canBeRegenerated, mesh,
  40229. /**
  40230. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40231. */
  40232. side) {
  40233. if (mesh === void 0) { mesh = null; }
  40234. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40235. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40236. _this.size = size;
  40237. _this.side = side;
  40238. return _this;
  40239. }
  40240. /** @hidden */
  40241. BoxGeometry.prototype._regenerateVertexData = function () {
  40242. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40243. };
  40244. BoxGeometry.prototype.copy = function (id) {
  40245. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40246. };
  40247. BoxGeometry.prototype.serialize = function () {
  40248. var serializationObject = _super.prototype.serialize.call(this);
  40249. serializationObject.size = this.size;
  40250. return serializationObject;
  40251. };
  40252. BoxGeometry.Parse = function (parsedBox, scene) {
  40253. if (scene.getGeometryByID(parsedBox.id)) {
  40254. return null; // null since geometry could be something else than a box...
  40255. }
  40256. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40257. if (BABYLON.Tags) {
  40258. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40259. }
  40260. scene.pushGeometry(box, true);
  40261. return box;
  40262. };
  40263. return BoxGeometry;
  40264. }(_PrimitiveGeometry));
  40265. BABYLON.BoxGeometry = BoxGeometry;
  40266. /**
  40267. * Creates a sphere geometry
  40268. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40269. */
  40270. var SphereGeometry = /** @class */ (function (_super) {
  40271. __extends(SphereGeometry, _super);
  40272. /**
  40273. * Create a new sphere geometry
  40274. * @param id defines the unique ID of the geometry
  40275. * @param scene defines the hosting scene
  40276. * @param segments defines the number of segments to use to create the sphere
  40277. * @param diameter defines the diameter of the sphere
  40278. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40279. * @param mesh defines the hosting mesh (can be null)
  40280. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40281. */
  40282. function SphereGeometry(id, scene,
  40283. /**
  40284. * Defines the number of segments to use to create the sphere
  40285. */
  40286. segments,
  40287. /**
  40288. * Defines the diameter of the sphere
  40289. */
  40290. diameter, canBeRegenerated, mesh,
  40291. /**
  40292. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40293. */
  40294. side) {
  40295. if (mesh === void 0) { mesh = null; }
  40296. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40297. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40298. _this.segments = segments;
  40299. _this.diameter = diameter;
  40300. _this.side = side;
  40301. return _this;
  40302. }
  40303. /** @hidden */
  40304. SphereGeometry.prototype._regenerateVertexData = function () {
  40305. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40306. };
  40307. SphereGeometry.prototype.copy = function (id) {
  40308. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40309. };
  40310. SphereGeometry.prototype.serialize = function () {
  40311. var serializationObject = _super.prototype.serialize.call(this);
  40312. serializationObject.segments = this.segments;
  40313. serializationObject.diameter = this.diameter;
  40314. return serializationObject;
  40315. };
  40316. SphereGeometry.Parse = function (parsedSphere, scene) {
  40317. if (scene.getGeometryByID(parsedSphere.id)) {
  40318. return null; // null since geometry could be something else than a sphere...
  40319. }
  40320. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40321. if (BABYLON.Tags) {
  40322. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40323. }
  40324. scene.pushGeometry(sphere, true);
  40325. return sphere;
  40326. };
  40327. return SphereGeometry;
  40328. }(_PrimitiveGeometry));
  40329. BABYLON.SphereGeometry = SphereGeometry;
  40330. /**
  40331. * Creates a disc geometry
  40332. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40333. */
  40334. var DiscGeometry = /** @class */ (function (_super) {
  40335. __extends(DiscGeometry, _super);
  40336. /**
  40337. * Creates a new disc geometry
  40338. * @param id defines the unique ID of the geometry
  40339. * @param scene defines the hosting scene
  40340. * @param radius defines the radius of the disc
  40341. * @param tessellation defines the tesselation factor to apply to the disc
  40342. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40343. * @param mesh defines the hosting mesh (can be null)
  40344. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40345. */
  40346. function DiscGeometry(id, scene,
  40347. /**
  40348. * Defines the radius of the disc
  40349. */
  40350. radius,
  40351. /**
  40352. * Defines the tesselation factor to apply to the disc
  40353. */
  40354. tessellation, canBeRegenerated, mesh,
  40355. /**
  40356. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40357. */
  40358. side) {
  40359. if (mesh === void 0) { mesh = null; }
  40360. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40361. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40362. _this.radius = radius;
  40363. _this.tessellation = tessellation;
  40364. _this.side = side;
  40365. return _this;
  40366. }
  40367. /** @hidden */
  40368. DiscGeometry.prototype._regenerateVertexData = function () {
  40369. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40370. };
  40371. DiscGeometry.prototype.copy = function (id) {
  40372. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40373. };
  40374. return DiscGeometry;
  40375. }(_PrimitiveGeometry));
  40376. BABYLON.DiscGeometry = DiscGeometry;
  40377. /**
  40378. * Creates a new cylinder geometry
  40379. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40380. */
  40381. var CylinderGeometry = /** @class */ (function (_super) {
  40382. __extends(CylinderGeometry, _super);
  40383. /**
  40384. * Creates a new cylinder geometry
  40385. * @param id defines the unique ID of the geometry
  40386. * @param scene defines the hosting scene
  40387. * @param height defines the height of the cylinder
  40388. * @param diameterTop defines the diameter of the cylinder's top cap
  40389. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40390. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40391. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40392. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40393. * @param mesh defines the hosting mesh (can be null)
  40394. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40395. */
  40396. function CylinderGeometry(id, scene,
  40397. /**
  40398. * Defines the height of the cylinder
  40399. */
  40400. height,
  40401. /**
  40402. * Defines the diameter of the cylinder's top cap
  40403. */
  40404. diameterTop,
  40405. /**
  40406. * Defines the diameter of the cylinder's bottom cap
  40407. */
  40408. diameterBottom,
  40409. /**
  40410. * Defines the tessellation factor to apply to the cylinder
  40411. */
  40412. tessellation,
  40413. /**
  40414. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40415. */
  40416. subdivisions, canBeRegenerated, mesh,
  40417. /**
  40418. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40419. */
  40420. side) {
  40421. if (subdivisions === void 0) { subdivisions = 1; }
  40422. if (mesh === void 0) { mesh = null; }
  40423. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40424. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40425. _this.height = height;
  40426. _this.diameterTop = diameterTop;
  40427. _this.diameterBottom = diameterBottom;
  40428. _this.tessellation = tessellation;
  40429. _this.subdivisions = subdivisions;
  40430. _this.side = side;
  40431. return _this;
  40432. }
  40433. /** @hidden */
  40434. CylinderGeometry.prototype._regenerateVertexData = function () {
  40435. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40436. };
  40437. CylinderGeometry.prototype.copy = function (id) {
  40438. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40439. };
  40440. CylinderGeometry.prototype.serialize = function () {
  40441. var serializationObject = _super.prototype.serialize.call(this);
  40442. serializationObject.height = this.height;
  40443. serializationObject.diameterTop = this.diameterTop;
  40444. serializationObject.diameterBottom = this.diameterBottom;
  40445. serializationObject.tessellation = this.tessellation;
  40446. return serializationObject;
  40447. };
  40448. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40449. if (scene.getGeometryByID(parsedCylinder.id)) {
  40450. return null; // null since geometry could be something else than a cylinder...
  40451. }
  40452. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40453. if (BABYLON.Tags) {
  40454. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40455. }
  40456. scene.pushGeometry(cylinder, true);
  40457. return cylinder;
  40458. };
  40459. return CylinderGeometry;
  40460. }(_PrimitiveGeometry));
  40461. BABYLON.CylinderGeometry = CylinderGeometry;
  40462. /**
  40463. * Creates a new torus geometry
  40464. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40465. */
  40466. var TorusGeometry = /** @class */ (function (_super) {
  40467. __extends(TorusGeometry, _super);
  40468. /**
  40469. * Creates a new torus geometry
  40470. * @param id defines the unique ID of the geometry
  40471. * @param scene defines the hosting scene
  40472. * @param diameter defines the diameter of the torus
  40473. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40474. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40475. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40476. * @param mesh defines the hosting mesh (can be null)
  40477. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40478. */
  40479. function TorusGeometry(id, scene,
  40480. /**
  40481. * Defines the diameter of the torus
  40482. */
  40483. diameter,
  40484. /**
  40485. * Defines the thickness of the torus (ie. internal diameter)
  40486. */
  40487. thickness,
  40488. /**
  40489. * Defines the tesselation factor to apply to the torus
  40490. */
  40491. tessellation, canBeRegenerated, mesh,
  40492. /**
  40493. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40494. */
  40495. side) {
  40496. if (mesh === void 0) { mesh = null; }
  40497. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40498. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40499. _this.diameter = diameter;
  40500. _this.thickness = thickness;
  40501. _this.tessellation = tessellation;
  40502. _this.side = side;
  40503. return _this;
  40504. }
  40505. /** @hidden */
  40506. TorusGeometry.prototype._regenerateVertexData = function () {
  40507. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40508. };
  40509. TorusGeometry.prototype.copy = function (id) {
  40510. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40511. };
  40512. TorusGeometry.prototype.serialize = function () {
  40513. var serializationObject = _super.prototype.serialize.call(this);
  40514. serializationObject.diameter = this.diameter;
  40515. serializationObject.thickness = this.thickness;
  40516. serializationObject.tessellation = this.tessellation;
  40517. return serializationObject;
  40518. };
  40519. TorusGeometry.Parse = function (parsedTorus, scene) {
  40520. if (scene.getGeometryByID(parsedTorus.id)) {
  40521. return null; // null since geometry could be something else than a torus...
  40522. }
  40523. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40524. if (BABYLON.Tags) {
  40525. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40526. }
  40527. scene.pushGeometry(torus, true);
  40528. return torus;
  40529. };
  40530. return TorusGeometry;
  40531. }(_PrimitiveGeometry));
  40532. BABYLON.TorusGeometry = TorusGeometry;
  40533. /**
  40534. * Creates a new ground geometry
  40535. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40536. */
  40537. var GroundGeometry = /** @class */ (function (_super) {
  40538. __extends(GroundGeometry, _super);
  40539. /**
  40540. * Creates a new ground geometry
  40541. * @param id defines the unique ID of the geometry
  40542. * @param scene defines the hosting scene
  40543. * @param width defines the width of the ground
  40544. * @param height defines the height of the ground
  40545. * @param subdivisions defines the subdivisions to apply to the ground
  40546. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40547. * @param mesh defines the hosting mesh (can be null)
  40548. */
  40549. function GroundGeometry(id, scene,
  40550. /**
  40551. * Defines the width of the ground
  40552. */
  40553. width,
  40554. /**
  40555. * Defines the height of the ground
  40556. */
  40557. height,
  40558. /**
  40559. * Defines the subdivisions to apply to the ground
  40560. */
  40561. subdivisions, canBeRegenerated, mesh) {
  40562. if (mesh === void 0) { mesh = null; }
  40563. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40564. _this.width = width;
  40565. _this.height = height;
  40566. _this.subdivisions = subdivisions;
  40567. return _this;
  40568. }
  40569. /** @hidden */
  40570. GroundGeometry.prototype._regenerateVertexData = function () {
  40571. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40572. };
  40573. GroundGeometry.prototype.copy = function (id) {
  40574. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40575. };
  40576. GroundGeometry.prototype.serialize = function () {
  40577. var serializationObject = _super.prototype.serialize.call(this);
  40578. serializationObject.width = this.width;
  40579. serializationObject.height = this.height;
  40580. serializationObject.subdivisions = this.subdivisions;
  40581. return serializationObject;
  40582. };
  40583. GroundGeometry.Parse = function (parsedGround, scene) {
  40584. if (scene.getGeometryByID(parsedGround.id)) {
  40585. return null; // null since geometry could be something else than a ground...
  40586. }
  40587. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40588. if (BABYLON.Tags) {
  40589. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40590. }
  40591. scene.pushGeometry(ground, true);
  40592. return ground;
  40593. };
  40594. return GroundGeometry;
  40595. }(_PrimitiveGeometry));
  40596. BABYLON.GroundGeometry = GroundGeometry;
  40597. /**
  40598. * Creates a tiled ground geometry
  40599. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40600. */
  40601. var TiledGroundGeometry = /** @class */ (function (_super) {
  40602. __extends(TiledGroundGeometry, _super);
  40603. /**
  40604. * Creates a tiled ground geometry
  40605. * @param id defines the unique ID of the geometry
  40606. * @param scene defines the hosting scene
  40607. * @param xmin defines the minimum value on X axis
  40608. * @param zmin defines the minimum value on Z axis
  40609. * @param xmax defines the maximum value on X axis
  40610. * @param zmax defines the maximum value on Z axis
  40611. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40612. * @param precision defines the precision to use when computing the tiles
  40613. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40614. * @param mesh defines the hosting mesh (can be null)
  40615. */
  40616. function TiledGroundGeometry(id, scene,
  40617. /**
  40618. * Defines the minimum value on X axis
  40619. */
  40620. xmin,
  40621. /**
  40622. * Defines the minimum value on Z axis
  40623. */
  40624. zmin,
  40625. /**
  40626. * Defines the maximum value on X axis
  40627. */
  40628. xmax,
  40629. /**
  40630. * Defines the maximum value on Z axis
  40631. */
  40632. zmax,
  40633. /**
  40634. * Defines the subdivisions to apply to the ground
  40635. */
  40636. subdivisions,
  40637. /**
  40638. * Defines the precision to use when computing the tiles
  40639. */
  40640. precision, canBeRegenerated, mesh) {
  40641. if (mesh === void 0) { mesh = null; }
  40642. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40643. _this.xmin = xmin;
  40644. _this.zmin = zmin;
  40645. _this.xmax = xmax;
  40646. _this.zmax = zmax;
  40647. _this.subdivisions = subdivisions;
  40648. _this.precision = precision;
  40649. return _this;
  40650. }
  40651. /** @hidden */
  40652. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40653. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40654. };
  40655. TiledGroundGeometry.prototype.copy = function (id) {
  40656. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40657. };
  40658. return TiledGroundGeometry;
  40659. }(_PrimitiveGeometry));
  40660. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40661. /**
  40662. * Creates a plane geometry
  40663. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40664. */
  40665. var PlaneGeometry = /** @class */ (function (_super) {
  40666. __extends(PlaneGeometry, _super);
  40667. /**
  40668. * Creates a plane geometry
  40669. * @param id defines the unique ID of the geometry
  40670. * @param scene defines the hosting scene
  40671. * @param size defines the size of the plane (width === height)
  40672. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40673. * @param mesh defines the hosting mesh (can be null)
  40674. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40675. */
  40676. function PlaneGeometry(id, scene,
  40677. /**
  40678. * Defines the size of the plane (width === height)
  40679. */
  40680. size, canBeRegenerated, mesh,
  40681. /**
  40682. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40683. */
  40684. side) {
  40685. if (mesh === void 0) { mesh = null; }
  40686. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40687. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40688. _this.size = size;
  40689. _this.side = side;
  40690. return _this;
  40691. }
  40692. /** @hidden */
  40693. PlaneGeometry.prototype._regenerateVertexData = function () {
  40694. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40695. };
  40696. PlaneGeometry.prototype.copy = function (id) {
  40697. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40698. };
  40699. PlaneGeometry.prototype.serialize = function () {
  40700. var serializationObject = _super.prototype.serialize.call(this);
  40701. serializationObject.size = this.size;
  40702. return serializationObject;
  40703. };
  40704. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40705. if (scene.getGeometryByID(parsedPlane.id)) {
  40706. return null; // null since geometry could be something else than a ground...
  40707. }
  40708. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40709. if (BABYLON.Tags) {
  40710. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40711. }
  40712. scene.pushGeometry(plane, true);
  40713. return plane;
  40714. };
  40715. return PlaneGeometry;
  40716. }(_PrimitiveGeometry));
  40717. BABYLON.PlaneGeometry = PlaneGeometry;
  40718. /**
  40719. * Creates a torus knot geometry
  40720. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40721. */
  40722. var TorusKnotGeometry = /** @class */ (function (_super) {
  40723. __extends(TorusKnotGeometry, _super);
  40724. /**
  40725. * Creates a torus knot geometry
  40726. * @param id defines the unique ID of the geometry
  40727. * @param scene defines the hosting scene
  40728. * @param radius defines the radius of the torus knot
  40729. * @param tube defines the thickness of the torus knot tube
  40730. * @param radialSegments defines the number of radial segments
  40731. * @param tubularSegments defines the number of tubular segments
  40732. * @param p defines the first number of windings
  40733. * @param q defines the second number of windings
  40734. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40735. * @param mesh defines the hosting mesh (can be null)
  40736. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40737. */
  40738. function TorusKnotGeometry(id, scene,
  40739. /**
  40740. * Defines the radius of the torus knot
  40741. */
  40742. radius,
  40743. /**
  40744. * Defines the thickness of the torus knot tube
  40745. */
  40746. tube,
  40747. /**
  40748. * Defines the number of radial segments
  40749. */
  40750. radialSegments,
  40751. /**
  40752. * Defines the number of tubular segments
  40753. */
  40754. tubularSegments,
  40755. /**
  40756. * Defines the first number of windings
  40757. */
  40758. p,
  40759. /**
  40760. * Defines the second number of windings
  40761. */
  40762. q, canBeRegenerated, mesh,
  40763. /**
  40764. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40765. */
  40766. side) {
  40767. if (mesh === void 0) { mesh = null; }
  40768. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40769. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40770. _this.radius = radius;
  40771. _this.tube = tube;
  40772. _this.radialSegments = radialSegments;
  40773. _this.tubularSegments = tubularSegments;
  40774. _this.p = p;
  40775. _this.q = q;
  40776. _this.side = side;
  40777. return _this;
  40778. }
  40779. /** @hidden */
  40780. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40781. 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 });
  40782. };
  40783. TorusKnotGeometry.prototype.copy = function (id) {
  40784. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40785. };
  40786. TorusKnotGeometry.prototype.serialize = function () {
  40787. var serializationObject = _super.prototype.serialize.call(this);
  40788. serializationObject.radius = this.radius;
  40789. serializationObject.tube = this.tube;
  40790. serializationObject.radialSegments = this.radialSegments;
  40791. serializationObject.tubularSegments = this.tubularSegments;
  40792. serializationObject.p = this.p;
  40793. serializationObject.q = this.q;
  40794. return serializationObject;
  40795. };
  40796. ;
  40797. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40798. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40799. return null; // null since geometry could be something else than a ground...
  40800. }
  40801. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40802. if (BABYLON.Tags) {
  40803. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40804. }
  40805. scene.pushGeometry(torusKnot, true);
  40806. return torusKnot;
  40807. };
  40808. return TorusKnotGeometry;
  40809. }(_PrimitiveGeometry));
  40810. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40811. //}
  40812. })(BABYLON || (BABYLON = {}));
  40813. //# sourceMappingURL=babylon.geometry.js.map
  40814. var BABYLON;
  40815. (function (BABYLON) {
  40816. /**
  40817. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40818. */
  40819. var PerformanceMonitor = /** @class */ (function () {
  40820. /**
  40821. * constructor
  40822. * @param frameSampleSize The number of samples required to saturate the sliding window
  40823. */
  40824. function PerformanceMonitor(frameSampleSize) {
  40825. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40826. this._enabled = true;
  40827. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40828. }
  40829. /**
  40830. * Samples current frame
  40831. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40832. */
  40833. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40834. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40835. if (!this._enabled)
  40836. return;
  40837. if (this._lastFrameTimeMs != null) {
  40838. var dt = timeMs - this._lastFrameTimeMs;
  40839. this._rollingFrameTime.add(dt);
  40840. }
  40841. this._lastFrameTimeMs = timeMs;
  40842. };
  40843. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40844. /**
  40845. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40846. * @return Average frame time in milliseconds
  40847. */
  40848. get: function () {
  40849. return this._rollingFrameTime.average;
  40850. },
  40851. enumerable: true,
  40852. configurable: true
  40853. });
  40854. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40855. /**
  40856. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40857. * @return Frame time variance in milliseconds squared
  40858. */
  40859. get: function () {
  40860. return this._rollingFrameTime.variance;
  40861. },
  40862. enumerable: true,
  40863. configurable: true
  40864. });
  40865. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40866. /**
  40867. * Returns the frame time of the most recent frame
  40868. * @return Frame time in milliseconds
  40869. */
  40870. get: function () {
  40871. return this._rollingFrameTime.history(0);
  40872. },
  40873. enumerable: true,
  40874. configurable: true
  40875. });
  40876. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40877. /**
  40878. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40879. * @return Framerate in frames per second
  40880. */
  40881. get: function () {
  40882. return 1000.0 / this._rollingFrameTime.average;
  40883. },
  40884. enumerable: true,
  40885. configurable: true
  40886. });
  40887. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40888. /**
  40889. * Returns the average framerate in frames per second using the most recent frame time
  40890. * @return Framerate in frames per second
  40891. */
  40892. get: function () {
  40893. var history = this._rollingFrameTime.history(0);
  40894. if (history === 0) {
  40895. return 0;
  40896. }
  40897. return 1000.0 / history;
  40898. },
  40899. enumerable: true,
  40900. configurable: true
  40901. });
  40902. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40903. /**
  40904. * Returns true if enough samples have been taken to completely fill the sliding window
  40905. * @return true if saturated
  40906. */
  40907. get: function () {
  40908. return this._rollingFrameTime.isSaturated();
  40909. },
  40910. enumerable: true,
  40911. configurable: true
  40912. });
  40913. /**
  40914. * Enables contributions to the sliding window sample set
  40915. */
  40916. PerformanceMonitor.prototype.enable = function () {
  40917. this._enabled = true;
  40918. };
  40919. /**
  40920. * Disables contributions to the sliding window sample set
  40921. * Samples will not be interpolated over the disabled period
  40922. */
  40923. PerformanceMonitor.prototype.disable = function () {
  40924. this._enabled = false;
  40925. //clear last sample to avoid interpolating over the disabled period when next enabled
  40926. this._lastFrameTimeMs = null;
  40927. };
  40928. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40929. /**
  40930. * Returns true if sampling is enabled
  40931. * @return true if enabled
  40932. */
  40933. get: function () {
  40934. return this._enabled;
  40935. },
  40936. enumerable: true,
  40937. configurable: true
  40938. });
  40939. /**
  40940. * Resets performance monitor
  40941. */
  40942. PerformanceMonitor.prototype.reset = function () {
  40943. //clear last sample to avoid interpolating over the disabled period when next enabled
  40944. this._lastFrameTimeMs = null;
  40945. //wipe record
  40946. this._rollingFrameTime.reset();
  40947. };
  40948. return PerformanceMonitor;
  40949. }());
  40950. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40951. /**
  40952. * RollingAverage
  40953. *
  40954. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40955. */
  40956. var RollingAverage = /** @class */ (function () {
  40957. /**
  40958. * constructor
  40959. * @param length The number of samples required to saturate the sliding window
  40960. */
  40961. function RollingAverage(length) {
  40962. this._samples = new Array(length);
  40963. this.reset();
  40964. }
  40965. /**
  40966. * Adds a sample to the sample set
  40967. * @param v The sample value
  40968. */
  40969. RollingAverage.prototype.add = function (v) {
  40970. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40971. var delta;
  40972. //we need to check if we've already wrapped round
  40973. if (this.isSaturated()) {
  40974. //remove bottom of stack from mean
  40975. var bottomValue = this._samples[this._pos];
  40976. delta = bottomValue - this.average;
  40977. this.average -= delta / (this._sampleCount - 1);
  40978. this._m2 -= delta * (bottomValue - this.average);
  40979. }
  40980. else {
  40981. this._sampleCount++;
  40982. }
  40983. //add new value to mean
  40984. delta = v - this.average;
  40985. this.average += delta / (this._sampleCount);
  40986. this._m2 += delta * (v - this.average);
  40987. //set the new variance
  40988. this.variance = this._m2 / (this._sampleCount - 1);
  40989. this._samples[this._pos] = v;
  40990. this._pos++;
  40991. this._pos %= this._samples.length; //positive wrap around
  40992. };
  40993. /**
  40994. * Returns previously added values or null if outside of history or outside the sliding window domain
  40995. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40996. * @return Value previously recorded with add() or null if outside of range
  40997. */
  40998. RollingAverage.prototype.history = function (i) {
  40999. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41000. return 0;
  41001. }
  41002. var i0 = this._wrapPosition(this._pos - 1.0);
  41003. return this._samples[this._wrapPosition(i0 - i)];
  41004. };
  41005. /**
  41006. * Returns true if enough samples have been taken to completely fill the sliding window
  41007. * @return true if sample-set saturated
  41008. */
  41009. RollingAverage.prototype.isSaturated = function () {
  41010. return this._sampleCount >= this._samples.length;
  41011. };
  41012. /**
  41013. * Resets the rolling average (equivalent to 0 samples taken so far)
  41014. */
  41015. RollingAverage.prototype.reset = function () {
  41016. this.average = 0;
  41017. this.variance = 0;
  41018. this._sampleCount = 0;
  41019. this._pos = 0;
  41020. this._m2 = 0;
  41021. };
  41022. /**
  41023. * Wraps a value around the sample range boundaries
  41024. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41025. * @return Wrapped position in sample range
  41026. */
  41027. RollingAverage.prototype._wrapPosition = function (i) {
  41028. var max = this._samples.length;
  41029. return ((i % max) + max) % max;
  41030. };
  41031. return RollingAverage;
  41032. }());
  41033. BABYLON.RollingAverage = RollingAverage;
  41034. })(BABYLON || (BABYLON = {}));
  41035. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41036. var BABYLON;
  41037. (function (BABYLON) {
  41038. /**
  41039. * "Static Class" containing the most commonly used helper while dealing with material for
  41040. * rendering purpose.
  41041. *
  41042. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41043. *
  41044. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41045. */
  41046. var MaterialHelper = /** @class */ (function () {
  41047. function MaterialHelper() {
  41048. }
  41049. /**
  41050. * Bind the current view position to an effect.
  41051. * @param effect The effect to be bound
  41052. * @param scene The scene the eyes position is used from
  41053. */
  41054. MaterialHelper.BindEyePosition = function (effect, scene) {
  41055. if (scene._forcedViewPosition) {
  41056. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41057. return;
  41058. }
  41059. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41060. };
  41061. /**
  41062. * Helps preparing the defines values about the UVs in used in the effect.
  41063. * UVs are shared as much as we can accross chanels in the shaders.
  41064. * @param texture The texture we are preparing the UVs for
  41065. * @param defines The defines to update
  41066. * @param key The chanel key "diffuse", "specular"... used in the shader
  41067. */
  41068. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41069. defines._needUVs = true;
  41070. defines[key] = true;
  41071. if (texture.getTextureMatrix().isIdentity(true)) {
  41072. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41073. if (texture.coordinatesIndex === 0) {
  41074. defines["MAINUV1"] = true;
  41075. }
  41076. else {
  41077. defines["MAINUV2"] = true;
  41078. }
  41079. }
  41080. else {
  41081. defines[key + "DIRECTUV"] = 0;
  41082. }
  41083. };
  41084. /**
  41085. * Binds a texture matrix value to its corrsponding uniform
  41086. * @param texture The texture to bind the matrix for
  41087. * @param uniformBuffer The uniform buffer receivin the data
  41088. * @param key The chanel key "diffuse", "specular"... used in the shader
  41089. */
  41090. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41091. var matrix = texture.getTextureMatrix();
  41092. if (!matrix.isIdentity(true)) {
  41093. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41094. }
  41095. };
  41096. /**
  41097. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41098. * @param mesh defines the current mesh
  41099. * @param scene defines the current scene
  41100. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41101. * @param pointsCloud defines if point cloud rendering has to be turned on
  41102. * @param fogEnabled defines if fog has to be turned on
  41103. * @param alphaTest defines if alpha testing has to be turned on
  41104. * @param defines defines the current list of defines
  41105. */
  41106. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41107. if (defines._areMiscDirty) {
  41108. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41109. defines["POINTSIZE"] = pointsCloud;
  41110. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41111. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41112. defines["ALPHATEST"] = alphaTest;
  41113. }
  41114. };
  41115. /**
  41116. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41117. * @param scene defines the current scene
  41118. * @param engine defines the current engine
  41119. * @param defines specifies the list of active defines
  41120. * @param useInstances defines if instances have to be turned on
  41121. * @param useClipPlane defines if clip plane have to be turned on
  41122. */
  41123. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41124. if (useClipPlane === void 0) { useClipPlane = null; }
  41125. var changed = false;
  41126. var useClipPlane1 = false;
  41127. var useClipPlane2 = false;
  41128. var useClipPlane3 = false;
  41129. var useClipPlane4 = false;
  41130. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41131. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41132. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41133. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41134. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41135. defines["CLIPPLANE"] = useClipPlane1;
  41136. changed = true;
  41137. }
  41138. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41139. defines["CLIPPLANE2"] = useClipPlane2;
  41140. changed = true;
  41141. }
  41142. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41143. defines["CLIPPLANE3"] = useClipPlane3;
  41144. changed = true;
  41145. }
  41146. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41147. defines["CLIPPLANE4"] = useClipPlane4;
  41148. changed = true;
  41149. }
  41150. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41151. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41152. changed = true;
  41153. }
  41154. if (defines["INSTANCES"] !== useInstances) {
  41155. defines["INSTANCES"] = useInstances;
  41156. changed = true;
  41157. }
  41158. if (changed) {
  41159. defines.markAsUnprocessed();
  41160. }
  41161. };
  41162. /**
  41163. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41164. * @param mesh The mesh containing the geometry data we will draw
  41165. * @param defines The defines to update
  41166. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41167. * @param useBones Precise whether bones should be used or not (override mesh info)
  41168. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41169. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41170. * @returns false if defines are considered not dirty and have not been checked
  41171. */
  41172. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41173. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41174. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41175. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41176. return false;
  41177. }
  41178. defines._normals = defines._needNormals;
  41179. defines._uvs = defines._needUVs;
  41180. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41181. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41182. defines["TANGENT"] = true;
  41183. }
  41184. if (defines._needUVs) {
  41185. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41186. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41187. }
  41188. else {
  41189. defines["UV1"] = false;
  41190. defines["UV2"] = false;
  41191. }
  41192. if (useVertexColor) {
  41193. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41194. defines["VERTEXCOLOR"] = hasVertexColors;
  41195. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41196. }
  41197. if (useBones) {
  41198. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41199. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41200. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41201. }
  41202. else {
  41203. defines["NUM_BONE_INFLUENCERS"] = 0;
  41204. defines["BonesPerMesh"] = 0;
  41205. }
  41206. }
  41207. if (useMorphTargets) {
  41208. var manager = mesh.morphTargetManager;
  41209. if (manager) {
  41210. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41211. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41212. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41213. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41214. }
  41215. else {
  41216. defines["MORPHTARGETS_TANGENT"] = false;
  41217. defines["MORPHTARGETS_NORMAL"] = false;
  41218. defines["MORPHTARGETS"] = false;
  41219. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41220. }
  41221. }
  41222. return true;
  41223. };
  41224. /**
  41225. * Prepares the defines related to the light information passed in parameter
  41226. * @param scene The scene we are intending to draw
  41227. * @param mesh The mesh the effect is compiling for
  41228. * @param defines The defines to update
  41229. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41230. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41231. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41232. * @returns true if normals will be required for the rest of the effect
  41233. */
  41234. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41235. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41236. if (disableLighting === void 0) { disableLighting = false; }
  41237. if (!defines._areLightsDirty) {
  41238. return defines._needNormals;
  41239. }
  41240. var lightIndex = 0;
  41241. var needNormals = false;
  41242. var needRebuild = false;
  41243. var lightmapMode = false;
  41244. var shadowEnabled = false;
  41245. var specularEnabled = false;
  41246. if (scene.lightsEnabled && !disableLighting) {
  41247. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41248. var light = _a[_i];
  41249. needNormals = true;
  41250. if (defines["LIGHT" + lightIndex] === undefined) {
  41251. needRebuild = true;
  41252. }
  41253. defines["LIGHT" + lightIndex] = true;
  41254. defines["SPOTLIGHT" + lightIndex] = false;
  41255. defines["HEMILIGHT" + lightIndex] = false;
  41256. defines["POINTLIGHT" + lightIndex] = false;
  41257. defines["DIRLIGHT" + lightIndex] = false;
  41258. light.prepareLightSpecificDefines(defines, lightIndex);
  41259. // FallOff.
  41260. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41261. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41262. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41263. switch (light.falloffType) {
  41264. case BABYLON.Light.FALLOFF_GLTF:
  41265. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41266. break;
  41267. case BABYLON.Light.FALLOFF_PHYSICAL:
  41268. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41269. break;
  41270. case BABYLON.Light.FALLOFF_STANDARD:
  41271. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41272. break;
  41273. }
  41274. // Specular
  41275. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41276. specularEnabled = true;
  41277. }
  41278. // Shadows
  41279. defines["SHADOW" + lightIndex] = false;
  41280. defines["SHADOWPCF" + lightIndex] = false;
  41281. defines["SHADOWPCSS" + lightIndex] = false;
  41282. defines["SHADOWPOISSON" + lightIndex] = false;
  41283. defines["SHADOWESM" + lightIndex] = false;
  41284. defines["SHADOWCUBE" + lightIndex] = false;
  41285. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41286. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41287. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41288. var shadowGenerator = light.getShadowGenerator();
  41289. if (shadowGenerator) {
  41290. var shadowMap = shadowGenerator.getShadowMap();
  41291. if (shadowMap) {
  41292. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41293. shadowEnabled = true;
  41294. shadowGenerator.prepareDefines(defines, lightIndex);
  41295. }
  41296. }
  41297. }
  41298. }
  41299. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41300. lightmapMode = true;
  41301. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41302. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41303. }
  41304. else {
  41305. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41306. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41307. }
  41308. lightIndex++;
  41309. if (lightIndex === maxSimultaneousLights)
  41310. break;
  41311. }
  41312. }
  41313. defines["SPECULARTERM"] = specularEnabled;
  41314. defines["SHADOWS"] = shadowEnabled;
  41315. // Resetting all other lights if any
  41316. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41317. if (defines["LIGHT" + index] !== undefined) {
  41318. defines["LIGHT" + index] = false;
  41319. defines["HEMILIGHT" + lightIndex] = false;
  41320. defines["POINTLIGHT" + lightIndex] = false;
  41321. defines["DIRLIGHT" + lightIndex] = false;
  41322. defines["SPOTLIGHT" + lightIndex] = false;
  41323. defines["SHADOW" + lightIndex] = false;
  41324. }
  41325. }
  41326. var caps = scene.getEngine().getCaps();
  41327. if (defines["SHADOWFLOAT"] === undefined) {
  41328. needRebuild = true;
  41329. }
  41330. defines["SHADOWFLOAT"] = shadowEnabled &&
  41331. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41332. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41333. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41334. if (needRebuild) {
  41335. defines.rebuild();
  41336. }
  41337. return needNormals;
  41338. };
  41339. /**
  41340. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41341. * that won t be acctive due to defines being turned off.
  41342. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41343. * @param samplersList The samplers list
  41344. * @param defines The defines helping in the list generation
  41345. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41346. */
  41347. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41348. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41349. var uniformsList;
  41350. var uniformBuffersList = null;
  41351. if (uniformsListOrOptions.uniformsNames) {
  41352. var options = uniformsListOrOptions;
  41353. uniformsList = options.uniformsNames;
  41354. uniformBuffersList = options.uniformBuffersNames;
  41355. samplersList = options.samplers;
  41356. defines = options.defines;
  41357. maxSimultaneousLights = options.maxSimultaneousLights;
  41358. }
  41359. else {
  41360. uniformsList = uniformsListOrOptions;
  41361. if (!samplersList) {
  41362. samplersList = [];
  41363. }
  41364. }
  41365. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41366. if (!defines["LIGHT" + lightIndex]) {
  41367. break;
  41368. }
  41369. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41370. if (uniformBuffersList) {
  41371. uniformBuffersList.push("Light" + lightIndex);
  41372. }
  41373. samplersList.push("shadowSampler" + lightIndex);
  41374. samplersList.push("depthSampler" + lightIndex);
  41375. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41376. samplersList.push("projectionLightSampler" + lightIndex);
  41377. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41378. }
  41379. }
  41380. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41381. uniformsList.push("morphTargetInfluences");
  41382. }
  41383. };
  41384. /**
  41385. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41386. * @param defines The defines to update while falling back
  41387. * @param fallbacks The authorized effect fallbacks
  41388. * @param maxSimultaneousLights The maximum number of lights allowed
  41389. * @param rank the current rank of the Effect
  41390. * @returns The newly affected rank
  41391. */
  41392. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41393. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41394. if (rank === void 0) { rank = 0; }
  41395. var lightFallbackRank = 0;
  41396. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41397. if (!defines["LIGHT" + lightIndex]) {
  41398. break;
  41399. }
  41400. if (lightIndex > 0) {
  41401. lightFallbackRank = rank + lightIndex;
  41402. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41403. }
  41404. if (!defines["SHADOWS"]) {
  41405. if (defines["SHADOW" + lightIndex]) {
  41406. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41407. }
  41408. if (defines["SHADOWPCF" + lightIndex]) {
  41409. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41410. }
  41411. if (defines["SHADOWPCSS" + lightIndex]) {
  41412. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41413. }
  41414. if (defines["SHADOWPOISSON" + lightIndex]) {
  41415. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41416. }
  41417. if (defines["SHADOWESM" + lightIndex]) {
  41418. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41419. }
  41420. }
  41421. }
  41422. return lightFallbackRank++;
  41423. };
  41424. /**
  41425. * Prepares the list of attributes required for morph targets according to the effect defines.
  41426. * @param attribs The current list of supported attribs
  41427. * @param mesh The mesh to prepare the morph targets attributes for
  41428. * @param defines The current Defines of the effect
  41429. */
  41430. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41431. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41432. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41433. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41434. var manager = mesh.morphTargetManager;
  41435. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41436. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41437. for (var index = 0; index < influencers; index++) {
  41438. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41439. if (normal) {
  41440. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41441. }
  41442. if (tangent) {
  41443. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41444. }
  41445. if (attribs.length > maxAttributesCount) {
  41446. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41447. }
  41448. }
  41449. }
  41450. };
  41451. /**
  41452. * Prepares the list of attributes required for bones according to the effect defines.
  41453. * @param attribs The current list of supported attribs
  41454. * @param mesh The mesh to prepare the bones attributes for
  41455. * @param defines The current Defines of the effect
  41456. * @param fallbacks The current efffect fallback strategy
  41457. */
  41458. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41459. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41460. fallbacks.addCPUSkinningFallback(0, mesh);
  41461. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41462. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41463. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41464. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41465. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41466. }
  41467. }
  41468. };
  41469. /**
  41470. * Prepares the list of attributes required for instances according to the effect defines.
  41471. * @param attribs The current list of supported attribs
  41472. * @param defines The current Defines of the effect
  41473. */
  41474. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41475. if (defines["INSTANCES"]) {
  41476. attribs.push("world0");
  41477. attribs.push("world1");
  41478. attribs.push("world2");
  41479. attribs.push("world3");
  41480. }
  41481. };
  41482. /**
  41483. * Binds the light shadow information to the effect for the given mesh.
  41484. * @param light The light containing the generator
  41485. * @param scene The scene the lights belongs to
  41486. * @param mesh The mesh we are binding the information to render
  41487. * @param lightIndex The light index in the effect used to render the mesh
  41488. * @param effect The effect we are binding the data to
  41489. */
  41490. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41491. if (light.shadowEnabled && mesh.receiveShadows) {
  41492. var shadowGenerator = light.getShadowGenerator();
  41493. if (shadowGenerator) {
  41494. shadowGenerator.bindShadowLight(lightIndex, effect);
  41495. }
  41496. }
  41497. };
  41498. /**
  41499. * Binds the light information to the effect.
  41500. * @param light The light containing the generator
  41501. * @param effect The effect we are binding the data to
  41502. * @param lightIndex The light index in the effect used to render
  41503. */
  41504. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41505. light.transferToEffect(effect, lightIndex + "");
  41506. };
  41507. /**
  41508. * Binds the lights information from the scene to the effect for the given mesh.
  41509. * @param scene The scene the lights belongs to
  41510. * @param mesh The mesh we are binding the information to render
  41511. * @param effect The effect we are binding the data to
  41512. * @param defines The generated defines for the effect
  41513. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41514. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41515. */
  41516. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41517. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41518. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41519. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41520. for (var i = 0; i < len; i++) {
  41521. var light = mesh._lightSources[i];
  41522. var iAsString = i.toString();
  41523. var scaledIntensity = light.getScaledIntensity();
  41524. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41525. MaterialHelper.BindLightProperties(light, effect, i);
  41526. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41527. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41528. if (defines["SPECULARTERM"]) {
  41529. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41530. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41531. }
  41532. // Shadows
  41533. if (scene.shadowsEnabled) {
  41534. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41535. }
  41536. light._uniformBuffer.update();
  41537. }
  41538. };
  41539. /**
  41540. * Binds the fog information from the scene to the effect for the given mesh.
  41541. * @param scene The scene the lights belongs to
  41542. * @param mesh The mesh we are binding the information to render
  41543. * @param effect The effect we are binding the data to
  41544. */
  41545. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41546. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41547. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41548. effect.setColor3("vFogColor", scene.fogColor);
  41549. }
  41550. };
  41551. /**
  41552. * Binds the bones information from the mesh to the effect.
  41553. * @param mesh The mesh we are binding the information to render
  41554. * @param effect The effect we are binding the data to
  41555. */
  41556. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41557. if (!effect || !mesh) {
  41558. return;
  41559. }
  41560. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41561. mesh.computeBonesUsingShaders = false;
  41562. }
  41563. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41564. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41565. if (matrices) {
  41566. effect.setMatrices("mBones", matrices);
  41567. }
  41568. }
  41569. };
  41570. /**
  41571. * Binds the morph targets information from the mesh to the effect.
  41572. * @param abstractMesh The mesh we are binding the information to render
  41573. * @param effect The effect we are binding the data to
  41574. */
  41575. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41576. var manager = abstractMesh.morphTargetManager;
  41577. if (!abstractMesh || !manager) {
  41578. return;
  41579. }
  41580. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41581. };
  41582. /**
  41583. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41584. * @param defines The generated defines used in the effect
  41585. * @param effect The effect we are binding the data to
  41586. * @param scene The scene we are willing to render with logarithmic scale for
  41587. */
  41588. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41589. if (defines["LOGARITHMICDEPTH"]) {
  41590. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41591. }
  41592. };
  41593. /**
  41594. * Binds the clip plane information from the scene to the effect.
  41595. * @param scene The scene the clip plane information are extracted from
  41596. * @param effect The effect we are binding the data to
  41597. */
  41598. MaterialHelper.BindClipPlane = function (effect, scene) {
  41599. if (scene.clipPlane) {
  41600. var clipPlane = scene.clipPlane;
  41601. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41602. }
  41603. if (scene.clipPlane2) {
  41604. var clipPlane = scene.clipPlane2;
  41605. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41606. }
  41607. if (scene.clipPlane3) {
  41608. var clipPlane = scene.clipPlane3;
  41609. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41610. }
  41611. if (scene.clipPlane4) {
  41612. var clipPlane = scene.clipPlane4;
  41613. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41614. }
  41615. };
  41616. return MaterialHelper;
  41617. }());
  41618. BABYLON.MaterialHelper = MaterialHelper;
  41619. })(BABYLON || (BABYLON = {}));
  41620. //# sourceMappingURL=babylon.materialHelper.js.map
  41621. var BABYLON;
  41622. (function (BABYLON) {
  41623. var PushMaterial = /** @class */ (function (_super) {
  41624. __extends(PushMaterial, _super);
  41625. function PushMaterial(name, scene) {
  41626. var _this = _super.call(this, name, scene) || this;
  41627. _this._normalMatrix = new BABYLON.Matrix();
  41628. _this.storeEffectOnSubMeshes = true;
  41629. return _this;
  41630. }
  41631. PushMaterial.prototype.getEffect = function () {
  41632. return this._activeEffect;
  41633. };
  41634. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41635. if (!mesh) {
  41636. return false;
  41637. }
  41638. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41639. return true;
  41640. }
  41641. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41642. };
  41643. /**
  41644. * Binds the given world matrix to the active effect
  41645. *
  41646. * @param world the matrix to bind
  41647. */
  41648. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41649. this._activeEffect.setMatrix("world", world);
  41650. };
  41651. /**
  41652. * Binds the given normal matrix to the active effect
  41653. *
  41654. * @param normalMatrix the matrix to bind
  41655. */
  41656. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41657. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41658. };
  41659. PushMaterial.prototype.bind = function (world, mesh) {
  41660. if (!mesh) {
  41661. return;
  41662. }
  41663. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41664. };
  41665. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41666. if (effect === void 0) { effect = null; }
  41667. _super.prototype._afterBind.call(this, mesh);
  41668. this.getScene()._cachedEffect = effect;
  41669. };
  41670. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41671. if (visibility === void 0) { visibility = 1; }
  41672. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41673. };
  41674. return PushMaterial;
  41675. }(BABYLON.Material));
  41676. BABYLON.PushMaterial = PushMaterial;
  41677. })(BABYLON || (BABYLON = {}));
  41678. //# sourceMappingURL=babylon.pushMaterial.js.map
  41679. var BABYLON;
  41680. (function (BABYLON) {
  41681. /** @hidden */
  41682. var StandardMaterialDefines = /** @class */ (function (_super) {
  41683. __extends(StandardMaterialDefines, _super);
  41684. function StandardMaterialDefines() {
  41685. var _this = _super.call(this) || this;
  41686. _this.MAINUV1 = false;
  41687. _this.MAINUV2 = false;
  41688. _this.DIFFUSE = false;
  41689. _this.DIFFUSEDIRECTUV = 0;
  41690. _this.AMBIENT = false;
  41691. _this.AMBIENTDIRECTUV = 0;
  41692. _this.OPACITY = false;
  41693. _this.OPACITYDIRECTUV = 0;
  41694. _this.OPACITYRGB = false;
  41695. _this.REFLECTION = false;
  41696. _this.EMISSIVE = false;
  41697. _this.EMISSIVEDIRECTUV = 0;
  41698. _this.SPECULAR = false;
  41699. _this.SPECULARDIRECTUV = 0;
  41700. _this.BUMP = false;
  41701. _this.BUMPDIRECTUV = 0;
  41702. _this.PARALLAX = false;
  41703. _this.PARALLAXOCCLUSION = false;
  41704. _this.SPECULAROVERALPHA = false;
  41705. _this.CLIPPLANE = false;
  41706. _this.CLIPPLANE2 = false;
  41707. _this.CLIPPLANE3 = false;
  41708. _this.CLIPPLANE4 = false;
  41709. _this.ALPHATEST = false;
  41710. _this.DEPTHPREPASS = false;
  41711. _this.ALPHAFROMDIFFUSE = false;
  41712. _this.POINTSIZE = false;
  41713. _this.FOG = false;
  41714. _this.SPECULARTERM = false;
  41715. _this.DIFFUSEFRESNEL = false;
  41716. _this.OPACITYFRESNEL = false;
  41717. _this.REFLECTIONFRESNEL = false;
  41718. _this.REFRACTIONFRESNEL = false;
  41719. _this.EMISSIVEFRESNEL = false;
  41720. _this.FRESNEL = false;
  41721. _this.NORMAL = false;
  41722. _this.UV1 = false;
  41723. _this.UV2 = false;
  41724. _this.VERTEXCOLOR = false;
  41725. _this.VERTEXALPHA = false;
  41726. _this.NUM_BONE_INFLUENCERS = 0;
  41727. _this.BonesPerMesh = 0;
  41728. _this.INSTANCES = false;
  41729. _this.GLOSSINESS = false;
  41730. _this.ROUGHNESS = false;
  41731. _this.EMISSIVEASILLUMINATION = false;
  41732. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41733. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41734. _this.LIGHTMAP = false;
  41735. _this.LIGHTMAPDIRECTUV = 0;
  41736. _this.OBJECTSPACE_NORMALMAP = false;
  41737. _this.USELIGHTMAPASSHADOWMAP = false;
  41738. _this.REFLECTIONMAP_3D = false;
  41739. _this.REFLECTIONMAP_SPHERICAL = false;
  41740. _this.REFLECTIONMAP_PLANAR = false;
  41741. _this.REFLECTIONMAP_CUBIC = false;
  41742. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41743. _this.REFLECTIONMAP_PROJECTION = false;
  41744. _this.REFLECTIONMAP_SKYBOX = false;
  41745. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41746. _this.REFLECTIONMAP_EXPLICIT = false;
  41747. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41748. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41749. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41750. _this.INVERTCUBICMAP = false;
  41751. _this.LOGARITHMICDEPTH = false;
  41752. _this.REFRACTION = false;
  41753. _this.REFRACTIONMAP_3D = false;
  41754. _this.REFLECTIONOVERALPHA = false;
  41755. _this.TWOSIDEDLIGHTING = false;
  41756. _this.SHADOWFLOAT = false;
  41757. _this.MORPHTARGETS = false;
  41758. _this.MORPHTARGETS_NORMAL = false;
  41759. _this.MORPHTARGETS_TANGENT = false;
  41760. _this.NUM_MORPH_INFLUENCERS = 0;
  41761. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41762. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41763. _this.IMAGEPROCESSING = false;
  41764. _this.VIGNETTE = false;
  41765. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41766. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41767. _this.TONEMAPPING = false;
  41768. _this.TONEMAPPING_ACES = false;
  41769. _this.CONTRAST = false;
  41770. _this.COLORCURVES = false;
  41771. _this.COLORGRADING = false;
  41772. _this.COLORGRADING3D = false;
  41773. _this.SAMPLER3DGREENDEPTH = false;
  41774. _this.SAMPLER3DBGRMAP = false;
  41775. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41776. /**
  41777. * If the reflection texture on this material is in linear color space
  41778. * @hidden
  41779. */
  41780. _this.IS_REFLECTION_LINEAR = false;
  41781. /**
  41782. * If the refraction texture on this material is in linear color space
  41783. * @hidden
  41784. */
  41785. _this.IS_REFRACTION_LINEAR = false;
  41786. _this.EXPOSURE = false;
  41787. _this.rebuild();
  41788. return _this;
  41789. }
  41790. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41791. var modes = [
  41792. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41793. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41794. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41795. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41796. ];
  41797. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41798. var mode = modes_1[_i];
  41799. this[mode] = (mode === modeToEnable);
  41800. }
  41801. };
  41802. return StandardMaterialDefines;
  41803. }(BABYLON.MaterialDefines));
  41804. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41805. var StandardMaterial = /** @class */ (function (_super) {
  41806. __extends(StandardMaterial, _super);
  41807. function StandardMaterial(name, scene) {
  41808. var _this = _super.call(this, name, scene) || this;
  41809. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41810. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41811. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41812. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41813. _this.specularPower = 64;
  41814. _this._useAlphaFromDiffuseTexture = false;
  41815. _this._useEmissiveAsIllumination = false;
  41816. _this._linkEmissiveWithDiffuse = false;
  41817. _this._useSpecularOverAlpha = false;
  41818. _this._useReflectionOverAlpha = false;
  41819. _this._disableLighting = false;
  41820. _this._useObjectSpaceNormalMap = false;
  41821. _this._useParallax = false;
  41822. _this._useParallaxOcclusion = false;
  41823. _this.parallaxScaleBias = 0.05;
  41824. _this._roughness = 0;
  41825. _this.indexOfRefraction = 0.98;
  41826. _this.invertRefractionY = true;
  41827. /**
  41828. * Defines the alpha limits in alpha test mode
  41829. */
  41830. _this.alphaCutOff = 0.4;
  41831. _this._useLightmapAsShadowmap = false;
  41832. _this._useReflectionFresnelFromSpecular = false;
  41833. _this._useGlossinessFromSpecularMapAlpha = false;
  41834. _this._maxSimultaneousLights = 4;
  41835. /**
  41836. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41837. */
  41838. _this._invertNormalMapX = false;
  41839. /**
  41840. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41841. */
  41842. _this._invertNormalMapY = false;
  41843. /**
  41844. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41845. */
  41846. _this._twoSidedLighting = false;
  41847. _this._renderTargets = new BABYLON.SmartArray(16);
  41848. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41849. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41850. // Setup the default processing configuration to the scene.
  41851. _this._attachImageProcessingConfiguration(null);
  41852. _this.getRenderTargetTextures = function () {
  41853. _this._renderTargets.reset();
  41854. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41855. _this._renderTargets.push(_this._reflectionTexture);
  41856. }
  41857. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41858. _this._renderTargets.push(_this._refractionTexture);
  41859. }
  41860. return _this._renderTargets;
  41861. };
  41862. return _this;
  41863. }
  41864. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41865. /**
  41866. * Gets the image processing configuration used either in this material.
  41867. */
  41868. get: function () {
  41869. return this._imageProcessingConfiguration;
  41870. },
  41871. /**
  41872. * Sets the Default image processing configuration used either in the this material.
  41873. *
  41874. * If sets to null, the scene one is in use.
  41875. */
  41876. set: function (value) {
  41877. this._attachImageProcessingConfiguration(value);
  41878. // Ensure the effect will be rebuilt.
  41879. this._markAllSubMeshesAsTexturesDirty();
  41880. },
  41881. enumerable: true,
  41882. configurable: true
  41883. });
  41884. /**
  41885. * Attaches a new image processing configuration to the Standard Material.
  41886. * @param configuration
  41887. */
  41888. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41889. var _this = this;
  41890. if (configuration === this._imageProcessingConfiguration) {
  41891. return;
  41892. }
  41893. // Detaches observer.
  41894. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41895. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41896. }
  41897. // Pick the scene configuration if needed.
  41898. if (!configuration) {
  41899. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41900. }
  41901. else {
  41902. this._imageProcessingConfiguration = configuration;
  41903. }
  41904. // Attaches observer.
  41905. if (this._imageProcessingConfiguration) {
  41906. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41907. _this._markAllSubMeshesAsImageProcessingDirty();
  41908. });
  41909. }
  41910. };
  41911. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41912. /**
  41913. * Gets wether the color curves effect is enabled.
  41914. */
  41915. get: function () {
  41916. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41917. },
  41918. /**
  41919. * Sets wether the color curves effect is enabled.
  41920. */
  41921. set: function (value) {
  41922. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41923. },
  41924. enumerable: true,
  41925. configurable: true
  41926. });
  41927. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41928. /**
  41929. * Gets wether the color grading effect is enabled.
  41930. */
  41931. get: function () {
  41932. return this.imageProcessingConfiguration.colorGradingEnabled;
  41933. },
  41934. /**
  41935. * Gets wether the color grading effect is enabled.
  41936. */
  41937. set: function (value) {
  41938. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41939. },
  41940. enumerable: true,
  41941. configurable: true
  41942. });
  41943. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41944. /**
  41945. * Gets wether tonemapping is enabled or not.
  41946. */
  41947. get: function () {
  41948. return this._imageProcessingConfiguration.toneMappingEnabled;
  41949. },
  41950. /**
  41951. * Sets wether tonemapping is enabled or not
  41952. */
  41953. set: function (value) {
  41954. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41955. },
  41956. enumerable: true,
  41957. configurable: true
  41958. });
  41959. ;
  41960. ;
  41961. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41962. /**
  41963. * The camera exposure used on this material.
  41964. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41965. * This corresponds to a photographic exposure.
  41966. */
  41967. get: function () {
  41968. return this._imageProcessingConfiguration.exposure;
  41969. },
  41970. /**
  41971. * The camera exposure used on this material.
  41972. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41973. * This corresponds to a photographic exposure.
  41974. */
  41975. set: function (value) {
  41976. this._imageProcessingConfiguration.exposure = value;
  41977. },
  41978. enumerable: true,
  41979. configurable: true
  41980. });
  41981. ;
  41982. ;
  41983. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41984. /**
  41985. * Gets The camera contrast used on this material.
  41986. */
  41987. get: function () {
  41988. return this._imageProcessingConfiguration.contrast;
  41989. },
  41990. /**
  41991. * Sets The camera contrast used on this material.
  41992. */
  41993. set: function (value) {
  41994. this._imageProcessingConfiguration.contrast = value;
  41995. },
  41996. enumerable: true,
  41997. configurable: true
  41998. });
  41999. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42000. /**
  42001. * Gets the Color Grading 2D Lookup Texture.
  42002. */
  42003. get: function () {
  42004. return this._imageProcessingConfiguration.colorGradingTexture;
  42005. },
  42006. /**
  42007. * Sets the Color Grading 2D Lookup Texture.
  42008. */
  42009. set: function (value) {
  42010. this._imageProcessingConfiguration.colorGradingTexture = value;
  42011. },
  42012. enumerable: true,
  42013. configurable: true
  42014. });
  42015. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42016. /**
  42017. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42018. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42019. * 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;
  42020. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42021. */
  42022. get: function () {
  42023. return this._imageProcessingConfiguration.colorCurves;
  42024. },
  42025. /**
  42026. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42027. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42028. * 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;
  42029. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42030. */
  42031. set: function (value) {
  42032. this._imageProcessingConfiguration.colorCurves = value;
  42033. },
  42034. enumerable: true,
  42035. configurable: true
  42036. });
  42037. StandardMaterial.prototype.getClassName = function () {
  42038. return "StandardMaterial";
  42039. };
  42040. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42041. get: function () {
  42042. return this._useLogarithmicDepth;
  42043. },
  42044. set: function (value) {
  42045. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42046. this._markAllSubMeshesAsMiscDirty();
  42047. },
  42048. enumerable: true,
  42049. configurable: true
  42050. });
  42051. StandardMaterial.prototype.needAlphaBlending = function () {
  42052. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42053. };
  42054. StandardMaterial.prototype.needAlphaTesting = function () {
  42055. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42056. };
  42057. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42058. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42059. };
  42060. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42061. return this._diffuseTexture;
  42062. };
  42063. /**
  42064. * Child classes can use it to update shaders
  42065. */
  42066. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42067. if (useInstances === void 0) { useInstances = false; }
  42068. if (subMesh.effect && this.isFrozen) {
  42069. if (this._wasPreviouslyReady) {
  42070. return true;
  42071. }
  42072. }
  42073. if (!subMesh._materialDefines) {
  42074. subMesh._materialDefines = new StandardMaterialDefines();
  42075. }
  42076. var scene = this.getScene();
  42077. var defines = subMesh._materialDefines;
  42078. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42079. if (defines._renderId === scene.getRenderId()) {
  42080. return true;
  42081. }
  42082. }
  42083. var engine = scene.getEngine();
  42084. // Lights
  42085. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42086. // Textures
  42087. if (defines._areTexturesDirty) {
  42088. defines._needUVs = false;
  42089. defines.MAINUV1 = false;
  42090. defines.MAINUV2 = false;
  42091. if (scene.texturesEnabled) {
  42092. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42093. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42094. return false;
  42095. }
  42096. else {
  42097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42098. }
  42099. }
  42100. else {
  42101. defines.DIFFUSE = false;
  42102. }
  42103. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42104. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42105. return false;
  42106. }
  42107. else {
  42108. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42109. }
  42110. }
  42111. else {
  42112. defines.AMBIENT = false;
  42113. }
  42114. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42115. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42116. return false;
  42117. }
  42118. else {
  42119. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42120. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42121. }
  42122. }
  42123. else {
  42124. defines.OPACITY = false;
  42125. }
  42126. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42127. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42128. return false;
  42129. }
  42130. else {
  42131. defines._needNormals = true;
  42132. defines.REFLECTION = true;
  42133. defines.ROUGHNESS = (this._roughness > 0);
  42134. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42135. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42136. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42137. switch (this._reflectionTexture.coordinatesMode) {
  42138. case BABYLON.Texture.EXPLICIT_MODE:
  42139. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42140. break;
  42141. case BABYLON.Texture.PLANAR_MODE:
  42142. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42143. break;
  42144. case BABYLON.Texture.PROJECTION_MODE:
  42145. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42146. break;
  42147. case BABYLON.Texture.SKYBOX_MODE:
  42148. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42149. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42150. break;
  42151. case BABYLON.Texture.SPHERICAL_MODE:
  42152. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42153. break;
  42154. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42155. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42156. break;
  42157. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42158. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42159. break;
  42160. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42161. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42162. break;
  42163. case BABYLON.Texture.CUBIC_MODE:
  42164. case BABYLON.Texture.INVCUBIC_MODE:
  42165. default:
  42166. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42167. break;
  42168. }
  42169. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42170. }
  42171. }
  42172. else {
  42173. defines.REFLECTION = false;
  42174. }
  42175. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42176. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42177. return false;
  42178. }
  42179. else {
  42180. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42181. }
  42182. }
  42183. else {
  42184. defines.EMISSIVE = false;
  42185. }
  42186. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42187. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42188. return false;
  42189. }
  42190. else {
  42191. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42192. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42193. }
  42194. }
  42195. else {
  42196. defines.LIGHTMAP = false;
  42197. }
  42198. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42199. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42200. return false;
  42201. }
  42202. else {
  42203. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42204. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42205. }
  42206. }
  42207. else {
  42208. defines.SPECULAR = false;
  42209. }
  42210. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42211. // Bump texure can not be not blocking.
  42212. if (!this._bumpTexture.isReady()) {
  42213. return false;
  42214. }
  42215. else {
  42216. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42217. defines.PARALLAX = this._useParallax;
  42218. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42219. }
  42220. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42221. }
  42222. else {
  42223. defines.BUMP = false;
  42224. }
  42225. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42226. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42227. return false;
  42228. }
  42229. else {
  42230. defines._needUVs = true;
  42231. defines.REFRACTION = true;
  42232. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42233. }
  42234. }
  42235. else {
  42236. defines.REFRACTION = false;
  42237. }
  42238. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42239. }
  42240. else {
  42241. defines.DIFFUSE = false;
  42242. defines.AMBIENT = false;
  42243. defines.OPACITY = false;
  42244. defines.REFLECTION = false;
  42245. defines.EMISSIVE = false;
  42246. defines.LIGHTMAP = false;
  42247. defines.BUMP = false;
  42248. defines.REFRACTION = false;
  42249. }
  42250. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42251. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42252. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42253. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42254. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42255. }
  42256. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42257. if (!this._imageProcessingConfiguration.isReady()) {
  42258. return false;
  42259. }
  42260. this._imageProcessingConfiguration.prepareDefines(defines);
  42261. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42262. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42263. }
  42264. if (defines._areFresnelDirty) {
  42265. if (StandardMaterial.FresnelEnabled) {
  42266. // Fresnel
  42267. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42268. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42269. this._reflectionFresnelParameters) {
  42270. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42271. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42272. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42273. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42274. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42275. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42276. defines._needNormals = true;
  42277. defines.FRESNEL = true;
  42278. }
  42279. }
  42280. else {
  42281. defines.FRESNEL = false;
  42282. }
  42283. }
  42284. // Misc.
  42285. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42286. // Attribs
  42287. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42288. // Values that need to be evaluated on every frame
  42289. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42290. // Get correct effect
  42291. if (defines.isDirty) {
  42292. defines.markAsProcessed();
  42293. scene.resetCachedMaterial();
  42294. // Fallbacks
  42295. var fallbacks = new BABYLON.EffectFallbacks();
  42296. if (defines.REFLECTION) {
  42297. fallbacks.addFallback(0, "REFLECTION");
  42298. }
  42299. if (defines.SPECULAR) {
  42300. fallbacks.addFallback(0, "SPECULAR");
  42301. }
  42302. if (defines.BUMP) {
  42303. fallbacks.addFallback(0, "BUMP");
  42304. }
  42305. if (defines.PARALLAX) {
  42306. fallbacks.addFallback(1, "PARALLAX");
  42307. }
  42308. if (defines.PARALLAXOCCLUSION) {
  42309. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42310. }
  42311. if (defines.SPECULAROVERALPHA) {
  42312. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42313. }
  42314. if (defines.FOG) {
  42315. fallbacks.addFallback(1, "FOG");
  42316. }
  42317. if (defines.POINTSIZE) {
  42318. fallbacks.addFallback(0, "POINTSIZE");
  42319. }
  42320. if (defines.LOGARITHMICDEPTH) {
  42321. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42322. }
  42323. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42324. if (defines.SPECULARTERM) {
  42325. fallbacks.addFallback(0, "SPECULARTERM");
  42326. }
  42327. if (defines.DIFFUSEFRESNEL) {
  42328. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42329. }
  42330. if (defines.OPACITYFRESNEL) {
  42331. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42332. }
  42333. if (defines.REFLECTIONFRESNEL) {
  42334. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42335. }
  42336. if (defines.EMISSIVEFRESNEL) {
  42337. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42338. }
  42339. if (defines.FRESNEL) {
  42340. fallbacks.addFallback(4, "FRESNEL");
  42341. }
  42342. //Attributes
  42343. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42344. if (defines.NORMAL) {
  42345. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42346. }
  42347. if (defines.UV1) {
  42348. attribs.push(BABYLON.VertexBuffer.UVKind);
  42349. }
  42350. if (defines.UV2) {
  42351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42352. }
  42353. if (defines.VERTEXCOLOR) {
  42354. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42355. }
  42356. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42357. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42358. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42359. var shaderName = "default";
  42360. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42361. "vFogInfos", "vFogColor", "pointSize",
  42362. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42363. "mBones",
  42364. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42365. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42366. "vReflectionPosition", "vReflectionSize",
  42367. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42368. ];
  42369. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42370. var uniformBuffers = ["Material", "Scene"];
  42371. if (BABYLON.ImageProcessingConfiguration) {
  42372. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42373. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42374. }
  42375. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42376. uniformsNames: uniforms,
  42377. uniformBuffersNames: uniformBuffers,
  42378. samplers: samplers,
  42379. defines: defines,
  42380. maxSimultaneousLights: this._maxSimultaneousLights
  42381. });
  42382. if (this.customShaderNameResolve) {
  42383. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42384. }
  42385. var join = defines.toString();
  42386. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42387. attributes: attribs,
  42388. uniformsNames: uniforms,
  42389. uniformBuffersNames: uniformBuffers,
  42390. samplers: samplers,
  42391. defines: join,
  42392. fallbacks: fallbacks,
  42393. onCompiled: this.onCompiled,
  42394. onError: this.onError,
  42395. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42396. }, engine), defines);
  42397. this.buildUniformLayout();
  42398. }
  42399. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42400. return false;
  42401. }
  42402. defines._renderId = scene.getRenderId();
  42403. this._wasPreviouslyReady = true;
  42404. return true;
  42405. };
  42406. StandardMaterial.prototype.buildUniformLayout = function () {
  42407. // Order is important !
  42408. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42409. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42410. this._uniformBuffer.addUniform("opacityParts", 4);
  42411. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42412. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42413. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42414. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42415. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42416. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42417. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42418. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42419. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42420. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42421. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42422. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42423. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42424. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42425. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42426. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42427. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42428. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42429. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42430. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42431. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42432. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42433. this._uniformBuffer.addUniform("specularMatrix", 16);
  42434. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42435. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42436. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42437. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42438. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42439. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42440. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42441. this._uniformBuffer.addUniform("pointSize", 1);
  42442. this._uniformBuffer.create();
  42443. };
  42444. StandardMaterial.prototype.unbind = function () {
  42445. if (this._activeEffect) {
  42446. var needFlag = false;
  42447. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42448. this._activeEffect.setTexture("reflection2DSampler", null);
  42449. needFlag = true;
  42450. }
  42451. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42452. this._activeEffect.setTexture("refraction2DSampler", null);
  42453. needFlag = true;
  42454. }
  42455. if (needFlag) {
  42456. this._markAllSubMeshesAsTexturesDirty();
  42457. }
  42458. }
  42459. _super.prototype.unbind.call(this);
  42460. };
  42461. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42462. var scene = this.getScene();
  42463. var defines = subMesh._materialDefines;
  42464. if (!defines) {
  42465. return;
  42466. }
  42467. var effect = subMesh.effect;
  42468. if (!effect) {
  42469. return;
  42470. }
  42471. this._activeEffect = effect;
  42472. // Matrices
  42473. this.bindOnlyWorldMatrix(world);
  42474. // Normal Matrix
  42475. if (defines.OBJECTSPACE_NORMALMAP) {
  42476. world.toNormalMatrix(this._normalMatrix);
  42477. this.bindOnlyNormalMatrix(this._normalMatrix);
  42478. }
  42479. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42480. // Bones
  42481. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42482. if (mustRebind) {
  42483. this._uniformBuffer.bindToEffect(effect, "Material");
  42484. this.bindViewProjection(effect);
  42485. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42486. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42487. // Fresnel
  42488. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42489. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42490. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42491. }
  42492. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42493. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42494. }
  42495. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42496. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42497. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42498. }
  42499. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42500. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42501. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42502. }
  42503. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42504. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42505. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42506. }
  42507. }
  42508. // Textures
  42509. if (scene.texturesEnabled) {
  42510. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42511. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42512. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42513. if (this._diffuseTexture.hasAlpha) {
  42514. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42515. }
  42516. }
  42517. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42518. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42519. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42520. }
  42521. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42522. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42523. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42524. }
  42525. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42526. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42527. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42528. if (this._reflectionTexture.boundingBoxSize) {
  42529. var cubeTexture = this._reflectionTexture;
  42530. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42531. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42532. }
  42533. }
  42534. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42535. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42536. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42537. }
  42538. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42539. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42540. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42541. }
  42542. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42543. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42544. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42545. }
  42546. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42547. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42548. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42549. if (scene._mirroredCameraPosition) {
  42550. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42551. }
  42552. else {
  42553. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42554. }
  42555. }
  42556. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42557. var depth = 1.0;
  42558. if (!this._refractionTexture.isCube) {
  42559. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42560. if (this._refractionTexture.depth) {
  42561. depth = this._refractionTexture.depth;
  42562. }
  42563. }
  42564. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42565. }
  42566. }
  42567. // Point size
  42568. if (this.pointsCloud) {
  42569. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42570. }
  42571. if (defines.SPECULARTERM) {
  42572. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42573. }
  42574. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42575. // Diffuse
  42576. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42577. }
  42578. // Textures
  42579. if (scene.texturesEnabled) {
  42580. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42581. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42582. }
  42583. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42584. effect.setTexture("ambientSampler", this._ambientTexture);
  42585. }
  42586. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42587. effect.setTexture("opacitySampler", this._opacityTexture);
  42588. }
  42589. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42590. if (this._reflectionTexture.isCube) {
  42591. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42592. }
  42593. else {
  42594. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42595. }
  42596. }
  42597. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42598. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42599. }
  42600. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42601. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42602. }
  42603. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42604. effect.setTexture("specularSampler", this._specularTexture);
  42605. }
  42606. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42607. effect.setTexture("bumpSampler", this._bumpTexture);
  42608. }
  42609. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42610. var depth = 1.0;
  42611. if (this._refractionTexture.isCube) {
  42612. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42613. }
  42614. else {
  42615. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42616. }
  42617. }
  42618. }
  42619. // Clip plane
  42620. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42621. // Colors
  42622. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42623. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42624. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42625. }
  42626. if (mustRebind || !this.isFrozen) {
  42627. // Lights
  42628. if (scene.lightsEnabled && !this._disableLighting) {
  42629. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42630. }
  42631. // View
  42632. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42633. this.bindView(effect);
  42634. }
  42635. // Fog
  42636. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42637. // Morph targets
  42638. if (defines.NUM_MORPH_INFLUENCERS) {
  42639. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42640. }
  42641. // Log. depth
  42642. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42643. // image processing
  42644. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42645. this._imageProcessingConfiguration.bind(this._activeEffect);
  42646. }
  42647. }
  42648. this._uniformBuffer.update();
  42649. this._afterBind(mesh, this._activeEffect);
  42650. };
  42651. StandardMaterial.prototype.getAnimatables = function () {
  42652. var results = [];
  42653. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42654. results.push(this._diffuseTexture);
  42655. }
  42656. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42657. results.push(this._ambientTexture);
  42658. }
  42659. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42660. results.push(this._opacityTexture);
  42661. }
  42662. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42663. results.push(this._reflectionTexture);
  42664. }
  42665. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42666. results.push(this._emissiveTexture);
  42667. }
  42668. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42669. results.push(this._specularTexture);
  42670. }
  42671. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42672. results.push(this._bumpTexture);
  42673. }
  42674. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42675. results.push(this._lightmapTexture);
  42676. }
  42677. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42678. results.push(this._refractionTexture);
  42679. }
  42680. return results;
  42681. };
  42682. StandardMaterial.prototype.getActiveTextures = function () {
  42683. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42684. if (this._diffuseTexture) {
  42685. activeTextures.push(this._diffuseTexture);
  42686. }
  42687. if (this._ambientTexture) {
  42688. activeTextures.push(this._ambientTexture);
  42689. }
  42690. if (this._opacityTexture) {
  42691. activeTextures.push(this._opacityTexture);
  42692. }
  42693. if (this._reflectionTexture) {
  42694. activeTextures.push(this._reflectionTexture);
  42695. }
  42696. if (this._emissiveTexture) {
  42697. activeTextures.push(this._emissiveTexture);
  42698. }
  42699. if (this._specularTexture) {
  42700. activeTextures.push(this._specularTexture);
  42701. }
  42702. if (this._bumpTexture) {
  42703. activeTextures.push(this._bumpTexture);
  42704. }
  42705. if (this._lightmapTexture) {
  42706. activeTextures.push(this._lightmapTexture);
  42707. }
  42708. if (this._refractionTexture) {
  42709. activeTextures.push(this._refractionTexture);
  42710. }
  42711. return activeTextures;
  42712. };
  42713. StandardMaterial.prototype.hasTexture = function (texture) {
  42714. if (_super.prototype.hasTexture.call(this, texture)) {
  42715. return true;
  42716. }
  42717. if (this._diffuseTexture === texture) {
  42718. return true;
  42719. }
  42720. if (this._ambientTexture === texture) {
  42721. return true;
  42722. }
  42723. if (this._opacityTexture === texture) {
  42724. return true;
  42725. }
  42726. if (this._reflectionTexture === texture) {
  42727. return true;
  42728. }
  42729. if (this._emissiveTexture === texture) {
  42730. return true;
  42731. }
  42732. if (this._specularTexture === texture) {
  42733. return true;
  42734. }
  42735. if (this._bumpTexture === texture) {
  42736. return true;
  42737. }
  42738. if (this._lightmapTexture === texture) {
  42739. return true;
  42740. }
  42741. if (this._refractionTexture === texture) {
  42742. return true;
  42743. }
  42744. return false;
  42745. };
  42746. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42747. if (forceDisposeTextures) {
  42748. if (this._diffuseTexture) {
  42749. this._diffuseTexture.dispose();
  42750. }
  42751. if (this._ambientTexture) {
  42752. this._ambientTexture.dispose();
  42753. }
  42754. if (this._opacityTexture) {
  42755. this._opacityTexture.dispose();
  42756. }
  42757. if (this._reflectionTexture) {
  42758. this._reflectionTexture.dispose();
  42759. }
  42760. if (this._emissiveTexture) {
  42761. this._emissiveTexture.dispose();
  42762. }
  42763. if (this._specularTexture) {
  42764. this._specularTexture.dispose();
  42765. }
  42766. if (this._bumpTexture) {
  42767. this._bumpTexture.dispose();
  42768. }
  42769. if (this._lightmapTexture) {
  42770. this._lightmapTexture.dispose();
  42771. }
  42772. if (this._refractionTexture) {
  42773. this._refractionTexture.dispose();
  42774. }
  42775. }
  42776. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42777. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42778. }
  42779. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42780. };
  42781. StandardMaterial.prototype.clone = function (name) {
  42782. var _this = this;
  42783. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42784. result.name = name;
  42785. result.id = name;
  42786. return result;
  42787. };
  42788. StandardMaterial.prototype.serialize = function () {
  42789. return BABYLON.SerializationHelper.Serialize(this);
  42790. };
  42791. // Statics
  42792. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42793. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42794. };
  42795. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42796. get: function () {
  42797. return StandardMaterial._DiffuseTextureEnabled;
  42798. },
  42799. set: function (value) {
  42800. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42801. return;
  42802. }
  42803. StandardMaterial._DiffuseTextureEnabled = value;
  42804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42805. },
  42806. enumerable: true,
  42807. configurable: true
  42808. });
  42809. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42810. get: function () {
  42811. return StandardMaterial._AmbientTextureEnabled;
  42812. },
  42813. set: function (value) {
  42814. if (StandardMaterial._AmbientTextureEnabled === value) {
  42815. return;
  42816. }
  42817. StandardMaterial._AmbientTextureEnabled = value;
  42818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42824. get: function () {
  42825. return StandardMaterial._OpacityTextureEnabled;
  42826. },
  42827. set: function (value) {
  42828. if (StandardMaterial._OpacityTextureEnabled === value) {
  42829. return;
  42830. }
  42831. StandardMaterial._OpacityTextureEnabled = value;
  42832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42838. get: function () {
  42839. return StandardMaterial._ReflectionTextureEnabled;
  42840. },
  42841. set: function (value) {
  42842. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42843. return;
  42844. }
  42845. StandardMaterial._ReflectionTextureEnabled = value;
  42846. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42847. },
  42848. enumerable: true,
  42849. configurable: true
  42850. });
  42851. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42852. get: function () {
  42853. return StandardMaterial._EmissiveTextureEnabled;
  42854. },
  42855. set: function (value) {
  42856. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42857. return;
  42858. }
  42859. StandardMaterial._EmissiveTextureEnabled = value;
  42860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42861. },
  42862. enumerable: true,
  42863. configurable: true
  42864. });
  42865. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42866. get: function () {
  42867. return StandardMaterial._SpecularTextureEnabled;
  42868. },
  42869. set: function (value) {
  42870. if (StandardMaterial._SpecularTextureEnabled === value) {
  42871. return;
  42872. }
  42873. StandardMaterial._SpecularTextureEnabled = value;
  42874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42875. },
  42876. enumerable: true,
  42877. configurable: true
  42878. });
  42879. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42880. get: function () {
  42881. return StandardMaterial._BumpTextureEnabled;
  42882. },
  42883. set: function (value) {
  42884. if (StandardMaterial._BumpTextureEnabled === value) {
  42885. return;
  42886. }
  42887. StandardMaterial._BumpTextureEnabled = value;
  42888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42889. },
  42890. enumerable: true,
  42891. configurable: true
  42892. });
  42893. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42894. get: function () {
  42895. return StandardMaterial._LightmapTextureEnabled;
  42896. },
  42897. set: function (value) {
  42898. if (StandardMaterial._LightmapTextureEnabled === value) {
  42899. return;
  42900. }
  42901. StandardMaterial._LightmapTextureEnabled = value;
  42902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42903. },
  42904. enumerable: true,
  42905. configurable: true
  42906. });
  42907. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42908. get: function () {
  42909. return StandardMaterial._RefractionTextureEnabled;
  42910. },
  42911. set: function (value) {
  42912. if (StandardMaterial._RefractionTextureEnabled === value) {
  42913. return;
  42914. }
  42915. StandardMaterial._RefractionTextureEnabled = value;
  42916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42922. get: function () {
  42923. return StandardMaterial._ColorGradingTextureEnabled;
  42924. },
  42925. set: function (value) {
  42926. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42927. return;
  42928. }
  42929. StandardMaterial._ColorGradingTextureEnabled = value;
  42930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42931. },
  42932. enumerable: true,
  42933. configurable: true
  42934. });
  42935. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42936. get: function () {
  42937. return StandardMaterial._FresnelEnabled;
  42938. },
  42939. set: function (value) {
  42940. if (StandardMaterial._FresnelEnabled === value) {
  42941. return;
  42942. }
  42943. StandardMaterial._FresnelEnabled = value;
  42944. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42945. },
  42946. enumerable: true,
  42947. configurable: true
  42948. });
  42949. // Flags used to enable or disable a type of texture for all Standard Materials
  42950. StandardMaterial._DiffuseTextureEnabled = true;
  42951. StandardMaterial._AmbientTextureEnabled = true;
  42952. StandardMaterial._OpacityTextureEnabled = true;
  42953. StandardMaterial._ReflectionTextureEnabled = true;
  42954. StandardMaterial._EmissiveTextureEnabled = true;
  42955. StandardMaterial._SpecularTextureEnabled = true;
  42956. StandardMaterial._BumpTextureEnabled = true;
  42957. StandardMaterial._LightmapTextureEnabled = true;
  42958. StandardMaterial._RefractionTextureEnabled = true;
  42959. StandardMaterial._ColorGradingTextureEnabled = true;
  42960. StandardMaterial._FresnelEnabled = true;
  42961. __decorate([
  42962. BABYLON.serializeAsTexture("diffuseTexture")
  42963. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42964. __decorate([
  42965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42966. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42967. __decorate([
  42968. BABYLON.serializeAsTexture("ambientTexture")
  42969. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42970. __decorate([
  42971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42972. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42973. __decorate([
  42974. BABYLON.serializeAsTexture("opacityTexture")
  42975. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42976. __decorate([
  42977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42978. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42979. __decorate([
  42980. BABYLON.serializeAsTexture("reflectionTexture")
  42981. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42982. __decorate([
  42983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42984. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42985. __decorate([
  42986. BABYLON.serializeAsTexture("emissiveTexture")
  42987. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42988. __decorate([
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42990. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42991. __decorate([
  42992. BABYLON.serializeAsTexture("specularTexture")
  42993. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42994. __decorate([
  42995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42996. ], StandardMaterial.prototype, "specularTexture", void 0);
  42997. __decorate([
  42998. BABYLON.serializeAsTexture("bumpTexture")
  42999. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43000. __decorate([
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43002. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43003. __decorate([
  43004. BABYLON.serializeAsTexture("lightmapTexture")
  43005. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43006. __decorate([
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43008. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43009. __decorate([
  43010. BABYLON.serializeAsTexture("refractionTexture")
  43011. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43012. __decorate([
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43014. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43015. __decorate([
  43016. BABYLON.serializeAsColor3("ambient")
  43017. ], StandardMaterial.prototype, "ambientColor", void 0);
  43018. __decorate([
  43019. BABYLON.serializeAsColor3("diffuse")
  43020. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43021. __decorate([
  43022. BABYLON.serializeAsColor3("specular")
  43023. ], StandardMaterial.prototype, "specularColor", void 0);
  43024. __decorate([
  43025. BABYLON.serializeAsColor3("emissive")
  43026. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43027. __decorate([
  43028. BABYLON.serialize()
  43029. ], StandardMaterial.prototype, "specularPower", void 0);
  43030. __decorate([
  43031. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43032. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43033. __decorate([
  43034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43035. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43036. __decorate([
  43037. BABYLON.serialize("useEmissiveAsIllumination")
  43038. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43039. __decorate([
  43040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43041. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43042. __decorate([
  43043. BABYLON.serialize("linkEmissiveWithDiffuse")
  43044. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43045. __decorate([
  43046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43047. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43048. __decorate([
  43049. BABYLON.serialize("useSpecularOverAlpha")
  43050. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43051. __decorate([
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43053. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43054. __decorate([
  43055. BABYLON.serialize("useReflectionOverAlpha")
  43056. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43057. __decorate([
  43058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43059. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43060. __decorate([
  43061. BABYLON.serialize("disableLighting")
  43062. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43063. __decorate([
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43065. ], StandardMaterial.prototype, "disableLighting", void 0);
  43066. __decorate([
  43067. BABYLON.serialize("useObjectSpaceNormalMap")
  43068. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43069. __decorate([
  43070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43071. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43072. __decorate([
  43073. BABYLON.serialize("useParallax")
  43074. ], StandardMaterial.prototype, "_useParallax", void 0);
  43075. __decorate([
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], StandardMaterial.prototype, "useParallax", void 0);
  43078. __decorate([
  43079. BABYLON.serialize("useParallaxOcclusion")
  43080. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43081. __decorate([
  43082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43083. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43084. __decorate([
  43085. BABYLON.serialize()
  43086. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43087. __decorate([
  43088. BABYLON.serialize("roughness")
  43089. ], StandardMaterial.prototype, "_roughness", void 0);
  43090. __decorate([
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43092. ], StandardMaterial.prototype, "roughness", void 0);
  43093. __decorate([
  43094. BABYLON.serialize()
  43095. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43096. __decorate([
  43097. BABYLON.serialize()
  43098. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43099. __decorate([
  43100. BABYLON.serialize()
  43101. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43102. __decorate([
  43103. BABYLON.serialize("useLightmapAsShadowmap")
  43104. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43105. __decorate([
  43106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43107. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43108. __decorate([
  43109. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43110. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43111. __decorate([
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43113. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43114. __decorate([
  43115. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43116. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43117. __decorate([
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43119. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43120. __decorate([
  43121. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43122. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43123. __decorate([
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43125. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43126. __decorate([
  43127. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43128. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43129. __decorate([
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43131. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43132. __decorate([
  43133. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43134. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43135. __decorate([
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43137. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43138. __decorate([
  43139. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43140. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43143. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43144. __decorate([
  43145. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43146. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43147. __decorate([
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43150. __decorate([
  43151. BABYLON.serialize("maxSimultaneousLights")
  43152. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43153. __decorate([
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43155. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43156. __decorate([
  43157. BABYLON.serialize("invertNormalMapX")
  43158. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43159. __decorate([
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43162. __decorate([
  43163. BABYLON.serialize("invertNormalMapY")
  43164. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43168. __decorate([
  43169. BABYLON.serialize("twoSidedLighting")
  43170. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43174. __decorate([
  43175. BABYLON.serialize()
  43176. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43177. return StandardMaterial;
  43178. }(BABYLON.PushMaterial));
  43179. BABYLON.StandardMaterial = StandardMaterial;
  43180. })(BABYLON || (BABYLON = {}));
  43181. //# sourceMappingURL=babylon.standardMaterial.js.map
  43182. var BABYLON;
  43183. (function (BABYLON) {
  43184. /**
  43185. * Class representing spherical polynomial coefficients to the 3rd degree
  43186. */
  43187. var SphericalPolynomial = /** @class */ (function () {
  43188. function SphericalPolynomial() {
  43189. /**
  43190. * The x coefficients of the spherical polynomial
  43191. */
  43192. this.x = BABYLON.Vector3.Zero();
  43193. /**
  43194. * The y coefficients of the spherical polynomial
  43195. */
  43196. this.y = BABYLON.Vector3.Zero();
  43197. /**
  43198. * The z coefficients of the spherical polynomial
  43199. */
  43200. this.z = BABYLON.Vector3.Zero();
  43201. /**
  43202. * The xx coefficients of the spherical polynomial
  43203. */
  43204. this.xx = BABYLON.Vector3.Zero();
  43205. /**
  43206. * The yy coefficients of the spherical polynomial
  43207. */
  43208. this.yy = BABYLON.Vector3.Zero();
  43209. /**
  43210. * The zz coefficients of the spherical polynomial
  43211. */
  43212. this.zz = BABYLON.Vector3.Zero();
  43213. /**
  43214. * The xy coefficients of the spherical polynomial
  43215. */
  43216. this.xy = BABYLON.Vector3.Zero();
  43217. /**
  43218. * The yz coefficients of the spherical polynomial
  43219. */
  43220. this.yz = BABYLON.Vector3.Zero();
  43221. /**
  43222. * The zx coefficients of the spherical polynomial
  43223. */
  43224. this.zx = BABYLON.Vector3.Zero();
  43225. }
  43226. /**
  43227. * Adds an ambient color to the spherical polynomial
  43228. * @param color the color to add
  43229. */
  43230. SphericalPolynomial.prototype.addAmbient = function (color) {
  43231. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43232. this.xx = this.xx.add(colorVector);
  43233. this.yy = this.yy.add(colorVector);
  43234. this.zz = this.zz.add(colorVector);
  43235. };
  43236. /**
  43237. * Scales the spherical polynomial by the given amount
  43238. * @param scale the amount to scale
  43239. */
  43240. SphericalPolynomial.prototype.scale = function (scale) {
  43241. this.x = this.x.scale(scale);
  43242. this.y = this.y.scale(scale);
  43243. this.z = this.z.scale(scale);
  43244. this.xx = this.xx.scale(scale);
  43245. this.yy = this.yy.scale(scale);
  43246. this.zz = this.zz.scale(scale);
  43247. this.yz = this.yz.scale(scale);
  43248. this.zx = this.zx.scale(scale);
  43249. this.xy = this.xy.scale(scale);
  43250. };
  43251. /**
  43252. * Gets the spherical polynomial from harmonics
  43253. * @param harmonics the spherical harmonics
  43254. * @returns the spherical polynomial
  43255. */
  43256. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43257. var result = new SphericalPolynomial();
  43258. result.x = harmonics.l11.scale(1.02333);
  43259. result.y = harmonics.l1_1.scale(1.02333);
  43260. result.z = harmonics.l10.scale(1.02333);
  43261. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43262. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43263. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43264. result.yz = harmonics.l2_1.scale(0.858086);
  43265. result.zx = harmonics.l21.scale(0.858086);
  43266. result.xy = harmonics.l2_2.scale(0.858086);
  43267. result.scale(1.0 / Math.PI);
  43268. return result;
  43269. };
  43270. /**
  43271. * Constructs a spherical polynomial from an array.
  43272. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43273. * @returns the spherical polynomial
  43274. */
  43275. SphericalPolynomial.FromArray = function (data) {
  43276. var sp = new SphericalPolynomial();
  43277. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43278. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43279. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43280. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43281. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43282. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43283. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43284. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43285. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43286. return sp;
  43287. };
  43288. return SphericalPolynomial;
  43289. }());
  43290. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43291. /**
  43292. * Class representing spherical harmonics coefficients to the 3rd degree
  43293. */
  43294. var SphericalHarmonics = /** @class */ (function () {
  43295. function SphericalHarmonics() {
  43296. /**
  43297. * The l0,0 coefficients of the spherical harmonics
  43298. */
  43299. this.l00 = BABYLON.Vector3.Zero();
  43300. /**
  43301. * The l1,-1 coefficients of the spherical harmonics
  43302. */
  43303. this.l1_1 = BABYLON.Vector3.Zero();
  43304. /**
  43305. * The l1,0 coefficients of the spherical harmonics
  43306. */
  43307. this.l10 = BABYLON.Vector3.Zero();
  43308. /**
  43309. * The l1,1 coefficients of the spherical harmonics
  43310. */
  43311. this.l11 = BABYLON.Vector3.Zero();
  43312. /**
  43313. * The l2,-2 coefficients of the spherical harmonics
  43314. */
  43315. this.l2_2 = BABYLON.Vector3.Zero();
  43316. /**
  43317. * The l2,-1 coefficients of the spherical harmonics
  43318. */
  43319. this.l2_1 = BABYLON.Vector3.Zero();
  43320. /**
  43321. * The l2,0 coefficients of the spherical harmonics
  43322. */
  43323. this.l20 = BABYLON.Vector3.Zero();
  43324. /**
  43325. * The l2,1 coefficients of the spherical harmonics
  43326. */
  43327. this.l21 = BABYLON.Vector3.Zero();
  43328. /**
  43329. * The l2,2 coefficients of the spherical harmonics
  43330. */
  43331. this.lL22 = BABYLON.Vector3.Zero();
  43332. }
  43333. /**
  43334. * Adds a light to the spherical harmonics
  43335. * @param direction the direction of the light
  43336. * @param color the color of the light
  43337. * @param deltaSolidAngle the delta solid angle of the light
  43338. */
  43339. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43340. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43341. var c = colorVector.scale(deltaSolidAngle);
  43342. this.l00 = this.l00.add(c.scale(0.282095));
  43343. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43344. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43345. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43346. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43347. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43348. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43349. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43350. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43351. };
  43352. /**
  43353. * Scales the spherical harmonics by the given amount
  43354. * @param scale the amount to scale
  43355. */
  43356. SphericalHarmonics.prototype.scale = function (scale) {
  43357. this.l00 = this.l00.scale(scale);
  43358. this.l1_1 = this.l1_1.scale(scale);
  43359. this.l10 = this.l10.scale(scale);
  43360. this.l11 = this.l11.scale(scale);
  43361. this.l2_2 = this.l2_2.scale(scale);
  43362. this.l2_1 = this.l2_1.scale(scale);
  43363. this.l20 = this.l20.scale(scale);
  43364. this.l21 = this.l21.scale(scale);
  43365. this.lL22 = this.lL22.scale(scale);
  43366. };
  43367. /**
  43368. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43369. *
  43370. * ```
  43371. * E_lm = A_l * L_lm
  43372. * ```
  43373. *
  43374. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43375. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43376. * the scaling factors are given in equation 9.
  43377. */
  43378. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43379. // Constant (Band 0)
  43380. this.l00 = this.l00.scale(3.141593);
  43381. // Linear (Band 1)
  43382. this.l1_1 = this.l1_1.scale(2.094395);
  43383. this.l10 = this.l10.scale(2.094395);
  43384. this.l11 = this.l11.scale(2.094395);
  43385. // Quadratic (Band 2)
  43386. this.l2_2 = this.l2_2.scale(0.785398);
  43387. this.l2_1 = this.l2_1.scale(0.785398);
  43388. this.l20 = this.l20.scale(0.785398);
  43389. this.l21 = this.l21.scale(0.785398);
  43390. this.lL22 = this.lL22.scale(0.785398);
  43391. };
  43392. /**
  43393. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43394. *
  43395. * ```
  43396. * L = (1/pi) * E * rho
  43397. * ```
  43398. *
  43399. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43400. */
  43401. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43402. this.scale(1.0 / Math.PI);
  43403. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43404. // (The pixel shader must apply albedo after texture fetches, etc).
  43405. };
  43406. /**
  43407. * Gets the spherical harmonics from polynomial
  43408. * @param polynomial the spherical polynomial
  43409. * @returns the spherical harmonics
  43410. */
  43411. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43412. var result = new SphericalHarmonics();
  43413. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43414. result.l1_1 = polynomial.y.scale(0.977204);
  43415. result.l10 = polynomial.z.scale(0.977204);
  43416. result.l11 = polynomial.x.scale(0.977204);
  43417. result.l2_2 = polynomial.xy.scale(1.16538);
  43418. result.l2_1 = polynomial.yz.scale(1.16538);
  43419. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43420. result.l21 = polynomial.zx.scale(1.16538);
  43421. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43422. result.scale(Math.PI);
  43423. return result;
  43424. };
  43425. /**
  43426. * Constructs a spherical harmonics from an array.
  43427. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43428. * @returns the spherical harmonics
  43429. */
  43430. SphericalHarmonics.FromArray = function (data) {
  43431. var sh = new SphericalHarmonics();
  43432. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43433. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43434. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43435. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43436. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43437. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43438. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43439. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43440. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43441. return sh;
  43442. };
  43443. return SphericalHarmonics;
  43444. }());
  43445. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43446. })(BABYLON || (BABYLON = {}));
  43447. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43448. var BABYLON;
  43449. (function (BABYLON) {
  43450. var FileFaceOrientation = /** @class */ (function () {
  43451. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43452. this.name = name;
  43453. this.worldAxisForNormal = worldAxisForNormal;
  43454. this.worldAxisForFileX = worldAxisForFileX;
  43455. this.worldAxisForFileY = worldAxisForFileY;
  43456. }
  43457. return FileFaceOrientation;
  43458. }());
  43459. ;
  43460. /**
  43461. * Helper class dealing with the extraction of spherical polynomial dataArray
  43462. * from a cube map.
  43463. */
  43464. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43465. function CubeMapToSphericalPolynomialTools() {
  43466. }
  43467. /**
  43468. * Converts a texture to the according Spherical Polynomial data.
  43469. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43470. *
  43471. * @param texture The texture to extract the information from.
  43472. * @return The Spherical Polynomial data.
  43473. */
  43474. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43475. if (!texture.isCube) {
  43476. // Only supports cube Textures currently.
  43477. return null;
  43478. }
  43479. var size = texture.getSize().width;
  43480. var right = texture.readPixels(0);
  43481. var left = texture.readPixels(1);
  43482. var up;
  43483. var down;
  43484. if (texture.isRenderTarget) {
  43485. up = texture.readPixels(3);
  43486. down = texture.readPixels(2);
  43487. }
  43488. else {
  43489. up = texture.readPixels(2);
  43490. down = texture.readPixels(3);
  43491. }
  43492. var front = texture.readPixels(4);
  43493. var back = texture.readPixels(5);
  43494. var gammaSpace = texture.gammaSpace;
  43495. // Always read as RGBA.
  43496. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43497. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43498. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43499. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43500. }
  43501. var cubeInfo = {
  43502. size: size,
  43503. right: right,
  43504. left: left,
  43505. up: up,
  43506. down: down,
  43507. front: front,
  43508. back: back,
  43509. format: format,
  43510. type: type,
  43511. gammaSpace: gammaSpace,
  43512. };
  43513. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43514. };
  43515. /**
  43516. * Converts a cubemap to the according Spherical Polynomial data.
  43517. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43518. *
  43519. * @param cubeInfo The Cube map to extract the information from.
  43520. * @return The Spherical Polynomial data.
  43521. */
  43522. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43523. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43524. var totalSolidAngle = 0.0;
  43525. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43526. var du = 2.0 / cubeInfo.size;
  43527. var dv = du;
  43528. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43529. var minUV = du * 0.5 - 1.0;
  43530. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43531. var fileFace = this.FileFaces[faceIndex];
  43532. var dataArray = cubeInfo[fileFace.name];
  43533. var v = minUV;
  43534. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43535. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43536. // Because SP is still linear, so summation is fine in that basis.
  43537. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43538. for (var y = 0; y < cubeInfo.size; y++) {
  43539. var u = minUV;
  43540. for (var x = 0; x < cubeInfo.size; x++) {
  43541. // World direction (not normalised)
  43542. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43543. worldDirection.normalize();
  43544. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43545. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43546. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43547. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43548. // Handle Integer types.
  43549. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43550. r /= 255;
  43551. g /= 255;
  43552. b /= 255;
  43553. }
  43554. // Handle Gamma space textures.
  43555. if (cubeInfo.gammaSpace) {
  43556. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43557. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43558. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43559. }
  43560. var color = new BABYLON.Color3(r, g, b);
  43561. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43562. totalSolidAngle += deltaSolidAngle;
  43563. u += du;
  43564. }
  43565. v += dv;
  43566. }
  43567. }
  43568. // Solid angle for entire sphere is 4*pi
  43569. var sphereSolidAngle = 4.0 * Math.PI;
  43570. // Adjust the solid angle to allow for how many faces we processed.
  43571. var facesProcessed = 6.0;
  43572. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43573. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43574. // This is needed because the numerical integration over the cube uses a
  43575. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43576. // and also to compensate for accumulative error due to float precision in the summation.
  43577. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43578. sphericalHarmonics.scale(correctionFactor);
  43579. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43580. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43581. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43582. };
  43583. CubeMapToSphericalPolynomialTools.FileFaces = [
  43584. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43585. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43586. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43587. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43588. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43589. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43590. ];
  43591. return CubeMapToSphericalPolynomialTools;
  43592. }());
  43593. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43594. })(BABYLON || (BABYLON = {}));
  43595. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43596. var BABYLON;
  43597. (function (BABYLON) {
  43598. /**
  43599. * Manages the defines for the PBR Material.
  43600. * @hiddenChildren
  43601. */
  43602. var PBRMaterialDefines = /** @class */ (function (_super) {
  43603. __extends(PBRMaterialDefines, _super);
  43604. /**
  43605. * Initializes the PBR Material defines.
  43606. */
  43607. function PBRMaterialDefines() {
  43608. var _this = _super.call(this) || this;
  43609. _this.PBR = true;
  43610. _this.MAINUV1 = false;
  43611. _this.MAINUV2 = false;
  43612. _this.UV1 = false;
  43613. _this.UV2 = false;
  43614. _this.ALBEDO = false;
  43615. _this.ALBEDODIRECTUV = 0;
  43616. _this.VERTEXCOLOR = false;
  43617. _this.AMBIENT = false;
  43618. _this.AMBIENTDIRECTUV = 0;
  43619. _this.AMBIENTINGRAYSCALE = false;
  43620. _this.OPACITY = false;
  43621. _this.VERTEXALPHA = false;
  43622. _this.OPACITYDIRECTUV = 0;
  43623. _this.OPACITYRGB = false;
  43624. _this.ALPHATEST = false;
  43625. _this.DEPTHPREPASS = false;
  43626. _this.ALPHABLEND = false;
  43627. _this.ALPHAFROMALBEDO = false;
  43628. _this.ALPHATESTVALUE = "0.5";
  43629. _this.SPECULAROVERALPHA = false;
  43630. _this.RADIANCEOVERALPHA = false;
  43631. _this.ALPHAFRESNEL = false;
  43632. _this.LINEARALPHAFRESNEL = false;
  43633. _this.PREMULTIPLYALPHA = false;
  43634. _this.EMISSIVE = false;
  43635. _this.EMISSIVEDIRECTUV = 0;
  43636. _this.REFLECTIVITY = false;
  43637. _this.REFLECTIVITYDIRECTUV = 0;
  43638. _this.SPECULARTERM = false;
  43639. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43640. _this.MICROSURFACEAUTOMATIC = false;
  43641. _this.LODBASEDMICROSFURACE = false;
  43642. _this.MICROSURFACEMAP = false;
  43643. _this.MICROSURFACEMAPDIRECTUV = 0;
  43644. _this.METALLICWORKFLOW = false;
  43645. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43646. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43647. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43648. _this.AOSTOREINMETALMAPRED = false;
  43649. _this.ENVIRONMENTBRDF = false;
  43650. _this.NORMAL = false;
  43651. _this.TANGENT = false;
  43652. _this.BUMP = false;
  43653. _this.BUMPDIRECTUV = 0;
  43654. _this.OBJECTSPACE_NORMALMAP = false;
  43655. _this.PARALLAX = false;
  43656. _this.PARALLAXOCCLUSION = false;
  43657. _this.NORMALXYSCALE = true;
  43658. _this.LIGHTMAP = false;
  43659. _this.LIGHTMAPDIRECTUV = 0;
  43660. _this.USELIGHTMAPASSHADOWMAP = false;
  43661. _this.GAMMALIGHTMAP = false;
  43662. _this.REFLECTION = false;
  43663. _this.REFLECTIONMAP_3D = false;
  43664. _this.REFLECTIONMAP_SPHERICAL = false;
  43665. _this.REFLECTIONMAP_PLANAR = false;
  43666. _this.REFLECTIONMAP_CUBIC = false;
  43667. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43668. _this.REFLECTIONMAP_PROJECTION = false;
  43669. _this.REFLECTIONMAP_SKYBOX = false;
  43670. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43671. _this.REFLECTIONMAP_EXPLICIT = false;
  43672. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43673. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43674. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43675. _this.INVERTCUBICMAP = false;
  43676. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43677. _this.USESPHERICALINVERTEX = false;
  43678. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43679. _this.LODINREFLECTIONALPHA = false;
  43680. _this.GAMMAREFLECTION = false;
  43681. _this.RGBDREFLECTION = false;
  43682. _this.RADIANCEOCCLUSION = false;
  43683. _this.HORIZONOCCLUSION = false;
  43684. _this.REFRACTION = false;
  43685. _this.REFRACTIONMAP_3D = false;
  43686. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43687. _this.LODINREFRACTIONALPHA = false;
  43688. _this.GAMMAREFRACTION = false;
  43689. _this.RGBDREFRACTION = false;
  43690. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43691. _this.INSTANCES = false;
  43692. _this.NUM_BONE_INFLUENCERS = 0;
  43693. _this.BonesPerMesh = 0;
  43694. _this.NONUNIFORMSCALING = false;
  43695. _this.MORPHTARGETS = false;
  43696. _this.MORPHTARGETS_NORMAL = false;
  43697. _this.MORPHTARGETS_TANGENT = false;
  43698. _this.NUM_MORPH_INFLUENCERS = 0;
  43699. _this.IMAGEPROCESSING = false;
  43700. _this.VIGNETTE = false;
  43701. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43702. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43703. _this.TONEMAPPING = false;
  43704. _this.TONEMAPPING_ACES = false;
  43705. _this.CONTRAST = false;
  43706. _this.COLORCURVES = false;
  43707. _this.COLORGRADING = false;
  43708. _this.COLORGRADING3D = false;
  43709. _this.SAMPLER3DGREENDEPTH = false;
  43710. _this.SAMPLER3DBGRMAP = false;
  43711. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43712. _this.EXPOSURE = false;
  43713. _this.USEPHYSICALLIGHTFALLOFF = false;
  43714. _this.USEGLTFLIGHTFALLOFF = false;
  43715. _this.TWOSIDEDLIGHTING = false;
  43716. _this.SHADOWFLOAT = false;
  43717. _this.CLIPPLANE = false;
  43718. _this.CLIPPLANE2 = false;
  43719. _this.CLIPPLANE3 = false;
  43720. _this.CLIPPLANE4 = false;
  43721. _this.POINTSIZE = false;
  43722. _this.FOG = false;
  43723. _this.LOGARITHMICDEPTH = false;
  43724. _this.FORCENORMALFORWARD = false;
  43725. _this.SPECULARAA = false;
  43726. _this.UNLIT = false;
  43727. _this.rebuild();
  43728. return _this;
  43729. }
  43730. /**
  43731. * Resets the PBR Material defines.
  43732. */
  43733. PBRMaterialDefines.prototype.reset = function () {
  43734. _super.prototype.reset.call(this);
  43735. this.ALPHATESTVALUE = "0.5";
  43736. this.PBR = true;
  43737. };
  43738. return PBRMaterialDefines;
  43739. }(BABYLON.MaterialDefines));
  43740. /**
  43741. * The Physically based material base class of BJS.
  43742. *
  43743. * This offers the main features of a standard PBR material.
  43744. * For more information, please refer to the documentation :
  43745. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43746. */
  43747. var PBRBaseMaterial = /** @class */ (function (_super) {
  43748. __extends(PBRBaseMaterial, _super);
  43749. /**
  43750. * Instantiates a new PBRMaterial instance.
  43751. *
  43752. * @param name The material name
  43753. * @param scene The scene the material will be use in.
  43754. */
  43755. function PBRBaseMaterial(name, scene) {
  43756. var _this = _super.call(this, name, scene) || this;
  43757. /**
  43758. * Intensity of the direct lights e.g. the four lights available in your scene.
  43759. * This impacts both the direct diffuse and specular highlights.
  43760. */
  43761. _this._directIntensity = 1.0;
  43762. /**
  43763. * Intensity of the emissive part of the material.
  43764. * This helps controlling the emissive effect without modifying the emissive color.
  43765. */
  43766. _this._emissiveIntensity = 1.0;
  43767. /**
  43768. * Intensity of the environment e.g. how much the environment will light the object
  43769. * either through harmonics for rough material or through the refelction for shiny ones.
  43770. */
  43771. _this._environmentIntensity = 1.0;
  43772. /**
  43773. * This is a special control allowing the reduction of the specular highlights coming from the
  43774. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43775. */
  43776. _this._specularIntensity = 1.0;
  43777. /**
  43778. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43779. */
  43780. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43781. /**
  43782. * Debug Control allowing disabling the bump map on this material.
  43783. */
  43784. _this._disableBumpMap = false;
  43785. /**
  43786. * AKA Occlusion Texture Intensity in other nomenclature.
  43787. */
  43788. _this._ambientTextureStrength = 1.0;
  43789. /**
  43790. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43791. * 1 means it completely occludes it
  43792. * 0 mean it has no impact
  43793. */
  43794. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43795. /**
  43796. * The color of a material in ambient lighting.
  43797. */
  43798. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43799. /**
  43800. * AKA Diffuse Color in other nomenclature.
  43801. */
  43802. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43803. /**
  43804. * AKA Specular Color in other nomenclature.
  43805. */
  43806. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43807. /**
  43808. * The color applied when light is reflected from a material.
  43809. */
  43810. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43811. /**
  43812. * The color applied when light is emitted from a material.
  43813. */
  43814. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43815. /**
  43816. * AKA Glossiness in other nomenclature.
  43817. */
  43818. _this._microSurface = 0.9;
  43819. /**
  43820. * source material index of refraction (IOR)' / 'destination material IOR.
  43821. */
  43822. _this._indexOfRefraction = 0.66;
  43823. /**
  43824. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43825. */
  43826. _this._invertRefractionY = false;
  43827. /**
  43828. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43829. * Materials half opaque for instance using refraction could benefit from this control.
  43830. */
  43831. _this._linkRefractionWithTransparency = false;
  43832. /**
  43833. * Specifies that the material will use the light map as a show map.
  43834. */
  43835. _this._useLightmapAsShadowmap = false;
  43836. /**
  43837. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43838. * makes the reflect vector face the model (under horizon).
  43839. */
  43840. _this._useHorizonOcclusion = true;
  43841. /**
  43842. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43843. * too much the area relying on ambient texture to define their ambient occlusion.
  43844. */
  43845. _this._useRadianceOcclusion = true;
  43846. /**
  43847. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43848. */
  43849. _this._useAlphaFromAlbedoTexture = false;
  43850. /**
  43851. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43852. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43853. */
  43854. _this._useSpecularOverAlpha = true;
  43855. /**
  43856. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43857. */
  43858. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43859. /**
  43860. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43861. */
  43862. _this._useRoughnessFromMetallicTextureAlpha = true;
  43863. /**
  43864. * Specifies if the metallic texture contains the roughness information in its green channel.
  43865. */
  43866. _this._useRoughnessFromMetallicTextureGreen = false;
  43867. /**
  43868. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43869. */
  43870. _this._useMetallnessFromMetallicTextureBlue = false;
  43871. /**
  43872. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43873. */
  43874. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43875. /**
  43876. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43877. */
  43878. _this._useAmbientInGrayScale = false;
  43879. /**
  43880. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43881. * The material will try to infer what glossiness each pixel should be.
  43882. */
  43883. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43884. /**
  43885. * Defines the falloff type used in this material.
  43886. * It by default is Physical.
  43887. */
  43888. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43889. /**
  43890. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43891. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43892. */
  43893. _this._useRadianceOverAlpha = true;
  43894. /**
  43895. * Allows using an object space normal map (instead of tangent space).
  43896. */
  43897. _this._useObjectSpaceNormalMap = false;
  43898. /**
  43899. * Allows using the bump map in parallax mode.
  43900. */
  43901. _this._useParallax = false;
  43902. /**
  43903. * Allows using the bump map in parallax occlusion mode.
  43904. */
  43905. _this._useParallaxOcclusion = false;
  43906. /**
  43907. * Controls the scale bias of the parallax mode.
  43908. */
  43909. _this._parallaxScaleBias = 0.05;
  43910. /**
  43911. * If sets to true, disables all the lights affecting the material.
  43912. */
  43913. _this._disableLighting = false;
  43914. /**
  43915. * Number of Simultaneous lights allowed on the material.
  43916. */
  43917. _this._maxSimultaneousLights = 4;
  43918. /**
  43919. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43920. */
  43921. _this._invertNormalMapX = false;
  43922. /**
  43923. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43924. */
  43925. _this._invertNormalMapY = false;
  43926. /**
  43927. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43928. */
  43929. _this._twoSidedLighting = false;
  43930. /**
  43931. * Defines the alpha limits in alpha test mode.
  43932. */
  43933. _this._alphaCutOff = 0.4;
  43934. /**
  43935. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43936. */
  43937. _this._forceAlphaTest = false;
  43938. /**
  43939. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43940. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43941. */
  43942. _this._useAlphaFresnel = false;
  43943. /**
  43944. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43945. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43946. */
  43947. _this._useLinearAlphaFresnel = false;
  43948. /**
  43949. * The transparency mode of the material.
  43950. */
  43951. _this._transparencyMode = null;
  43952. /**
  43953. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43954. * from cos thetav and roughness:
  43955. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43956. */
  43957. _this._environmentBRDFTexture = null;
  43958. /**
  43959. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43960. */
  43961. _this._forceIrradianceInFragment = false;
  43962. /**
  43963. * Force normal to face away from face.
  43964. */
  43965. _this._forceNormalForward = false;
  43966. /**
  43967. * Enables specular anti aliasing in the PBR shader.
  43968. * It will both interacts on the Geometry for analytical and IBL lighting.
  43969. * It also prefilter the roughness map based on the bump values.
  43970. */
  43971. _this._enableSpecularAntiAliasing = false;
  43972. /**
  43973. * Stores the available render targets.
  43974. */
  43975. _this._renderTargets = new BABYLON.SmartArray(16);
  43976. /**
  43977. * Sets the global ambient color for the material used in lighting calculations.
  43978. */
  43979. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43980. /**
  43981. * If set to true, no lighting calculations will be applied.
  43982. */
  43983. _this._unlit = false;
  43984. // Setup the default processing configuration to the scene.
  43985. _this._attachImageProcessingConfiguration(null);
  43986. _this.getRenderTargetTextures = function () {
  43987. _this._renderTargets.reset();
  43988. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43989. _this._renderTargets.push(_this._reflectionTexture);
  43990. }
  43991. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43992. _this._renderTargets.push(_this._refractionTexture);
  43993. }
  43994. return _this._renderTargets;
  43995. };
  43996. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43997. return _this;
  43998. }
  43999. /**
  44000. * Attaches a new image processing configuration to the PBR Material.
  44001. * @param configuration
  44002. */
  44003. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44004. var _this = this;
  44005. if (configuration === this._imageProcessingConfiguration) {
  44006. return;
  44007. }
  44008. // Detaches observer.
  44009. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44010. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44011. }
  44012. // Pick the scene configuration if needed.
  44013. if (!configuration) {
  44014. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44015. }
  44016. else {
  44017. this._imageProcessingConfiguration = configuration;
  44018. }
  44019. // Attaches observer.
  44020. if (this._imageProcessingConfiguration) {
  44021. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44022. _this._markAllSubMeshesAsImageProcessingDirty();
  44023. });
  44024. }
  44025. };
  44026. /**
  44027. * Gets the name of the material class.
  44028. */
  44029. PBRBaseMaterial.prototype.getClassName = function () {
  44030. return "PBRBaseMaterial";
  44031. };
  44032. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44033. /**
  44034. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44035. */
  44036. get: function () {
  44037. return this._useLogarithmicDepth;
  44038. },
  44039. /**
  44040. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44041. */
  44042. set: function (value) {
  44043. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44044. },
  44045. enumerable: true,
  44046. configurable: true
  44047. });
  44048. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44049. /**
  44050. * Gets the current transparency mode.
  44051. */
  44052. get: function () {
  44053. return this._transparencyMode;
  44054. },
  44055. /**
  44056. * Sets the transparency mode of the material.
  44057. *
  44058. * | Value | Type | Description |
  44059. * | ----- | ----------------------------------- | ----------- |
  44060. * | 0 | OPAQUE | |
  44061. * | 1 | ALPHATEST | |
  44062. * | 2 | ALPHABLEND | |
  44063. * | 3 | ALPHATESTANDBLEND | |
  44064. *
  44065. */
  44066. set: function (value) {
  44067. if (this._transparencyMode === value) {
  44068. return;
  44069. }
  44070. this._transparencyMode = value;
  44071. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44072. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44073. },
  44074. enumerable: true,
  44075. configurable: true
  44076. });
  44077. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44078. /**
  44079. * Returns true if alpha blending should be disabled.
  44080. */
  44081. get: function () {
  44082. return (this._linkRefractionWithTransparency ||
  44083. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44084. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44085. },
  44086. enumerable: true,
  44087. configurable: true
  44088. });
  44089. /**
  44090. * Specifies whether or not this material should be rendered in alpha blend mode.
  44091. */
  44092. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44093. if (this._disableAlphaBlending) {
  44094. return false;
  44095. }
  44096. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44097. };
  44098. /**
  44099. * Specifies if the mesh will require alpha blending.
  44100. * @param mesh - BJS mesh.
  44101. */
  44102. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44103. if (this._disableAlphaBlending) {
  44104. return false;
  44105. }
  44106. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44107. };
  44108. /**
  44109. * Specifies whether or not this material should be rendered in alpha test mode.
  44110. */
  44111. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44112. if (this._forceAlphaTest) {
  44113. return true;
  44114. }
  44115. if (this._linkRefractionWithTransparency) {
  44116. return false;
  44117. }
  44118. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44119. };
  44120. /**
  44121. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44122. */
  44123. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44124. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44125. };
  44126. /**
  44127. * Gets the texture used for the alpha test.
  44128. */
  44129. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44130. return this._albedoTexture;
  44131. };
  44132. /**
  44133. * Specifies that the submesh is ready to be used.
  44134. * @param mesh - BJS mesh.
  44135. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44136. * @param useInstances - Specifies that instances should be used.
  44137. * @returns - boolean indicating that the submesh is ready or not.
  44138. */
  44139. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44140. if (subMesh.effect && this.isFrozen) {
  44141. if (this._wasPreviouslyReady) {
  44142. return true;
  44143. }
  44144. }
  44145. if (!subMesh._materialDefines) {
  44146. subMesh._materialDefines = new PBRMaterialDefines();
  44147. }
  44148. var defines = subMesh._materialDefines;
  44149. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44150. if (defines._renderId === this.getScene().getRenderId()) {
  44151. return true;
  44152. }
  44153. }
  44154. var scene = this.getScene();
  44155. var engine = scene.getEngine();
  44156. if (defines._areTexturesDirty) {
  44157. if (scene.texturesEnabled) {
  44158. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44159. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44160. return false;
  44161. }
  44162. }
  44163. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44164. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44165. return false;
  44166. }
  44167. }
  44168. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44169. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44170. return false;
  44171. }
  44172. }
  44173. var reflectionTexture = this._getReflectionTexture();
  44174. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44175. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44176. return false;
  44177. }
  44178. }
  44179. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44180. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44181. return false;
  44182. }
  44183. }
  44184. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44185. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44186. return false;
  44187. }
  44188. }
  44189. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44190. if (this._metallicTexture) {
  44191. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44192. return false;
  44193. }
  44194. }
  44195. else if (this._reflectivityTexture) {
  44196. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44197. return false;
  44198. }
  44199. }
  44200. if (this._microSurfaceTexture) {
  44201. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44202. return false;
  44203. }
  44204. }
  44205. }
  44206. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44207. // Bump texture cannot be not blocking.
  44208. if (!this._bumpTexture.isReady()) {
  44209. return false;
  44210. }
  44211. }
  44212. var refractionTexture = this._getRefractionTexture();
  44213. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44214. if (!refractionTexture.isReadyOrNotBlocking()) {
  44215. return false;
  44216. }
  44217. }
  44218. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44219. // This is blocking.
  44220. if (!this._environmentBRDFTexture.isReady()) {
  44221. return false;
  44222. }
  44223. }
  44224. }
  44225. }
  44226. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44227. if (!this._imageProcessingConfiguration.isReady()) {
  44228. return false;
  44229. }
  44230. }
  44231. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44232. mesh.createNormals(true);
  44233. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44234. }
  44235. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44236. if (effect) {
  44237. scene.resetCachedMaterial();
  44238. subMesh.setEffect(effect, defines);
  44239. this.buildUniformLayout();
  44240. }
  44241. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44242. return false;
  44243. }
  44244. defines._renderId = scene.getRenderId();
  44245. this._wasPreviouslyReady = true;
  44246. return true;
  44247. };
  44248. /**
  44249. * Specifies if the material uses metallic roughness workflow.
  44250. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44251. */
  44252. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44253. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44254. return true;
  44255. }
  44256. return false;
  44257. };
  44258. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44259. if (onCompiled === void 0) { onCompiled = null; }
  44260. if (onError === void 0) { onError = null; }
  44261. if (useInstances === void 0) { useInstances = null; }
  44262. if (useClipPlane === void 0) { useClipPlane = null; }
  44263. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44264. if (!defines.isDirty) {
  44265. return null;
  44266. }
  44267. defines.markAsProcessed();
  44268. var scene = this.getScene();
  44269. var engine = scene.getEngine();
  44270. // Fallbacks
  44271. var fallbacks = new BABYLON.EffectFallbacks();
  44272. var fallbackRank = 0;
  44273. if (defines.USESPHERICALINVERTEX) {
  44274. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44275. }
  44276. if (defines.FOG) {
  44277. fallbacks.addFallback(fallbackRank, "FOG");
  44278. }
  44279. if (defines.SPECULARAA) {
  44280. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44281. }
  44282. if (defines.POINTSIZE) {
  44283. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44284. }
  44285. if (defines.LOGARITHMICDEPTH) {
  44286. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44287. }
  44288. if (defines.PARALLAX) {
  44289. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44290. }
  44291. if (defines.PARALLAXOCCLUSION) {
  44292. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44293. }
  44294. if (defines.ENVIRONMENTBRDF) {
  44295. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44296. }
  44297. if (defines.TANGENT) {
  44298. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44299. }
  44300. if (defines.BUMP) {
  44301. fallbacks.addFallback(fallbackRank++, "BUMP");
  44302. }
  44303. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44304. if (defines.SPECULARTERM) {
  44305. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44306. }
  44307. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44308. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44309. }
  44310. if (defines.LIGHTMAP) {
  44311. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44312. }
  44313. if (defines.NORMAL) {
  44314. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44315. }
  44316. if (defines.AMBIENT) {
  44317. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44318. }
  44319. if (defines.EMISSIVE) {
  44320. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44321. }
  44322. if (defines.VERTEXCOLOR) {
  44323. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44324. }
  44325. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44326. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44327. }
  44328. if (defines.MORPHTARGETS) {
  44329. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44330. }
  44331. //Attributes
  44332. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44333. if (defines.NORMAL) {
  44334. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44335. }
  44336. if (defines.TANGENT) {
  44337. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44338. }
  44339. if (defines.UV1) {
  44340. attribs.push(BABYLON.VertexBuffer.UVKind);
  44341. }
  44342. if (defines.UV2) {
  44343. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44344. }
  44345. if (defines.VERTEXCOLOR) {
  44346. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44347. }
  44348. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44349. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44350. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44351. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44352. "vFogInfos", "vFogColor", "pointSize",
  44353. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44354. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44355. "mBones",
  44356. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44357. "vLightingIntensity",
  44358. "logarithmicDepthConstant",
  44359. "vSphericalX", "vSphericalY", "vSphericalZ",
  44360. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44361. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44362. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44363. "vTangentSpaceParams"
  44364. ];
  44365. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44366. "bumpSampler", "lightmapSampler", "opacitySampler",
  44367. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44368. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44369. "microSurfaceSampler", "environmentBrdfSampler"];
  44370. var uniformBuffers = ["Material", "Scene"];
  44371. if (BABYLON.ImageProcessingConfiguration) {
  44372. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44373. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44374. }
  44375. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44376. uniformsNames: uniforms,
  44377. uniformBuffersNames: uniformBuffers,
  44378. samplers: samplers,
  44379. defines: defines,
  44380. maxSimultaneousLights: this._maxSimultaneousLights
  44381. });
  44382. var join = defines.toString();
  44383. return engine.createEffect("pbr", {
  44384. attributes: attribs,
  44385. uniformsNames: uniforms,
  44386. uniformBuffersNames: uniformBuffers,
  44387. samplers: samplers,
  44388. defines: join,
  44389. fallbacks: fallbacks,
  44390. onCompiled: onCompiled,
  44391. onError: onError,
  44392. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44393. }, engine);
  44394. };
  44395. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44396. if (useInstances === void 0) { useInstances = null; }
  44397. if (useClipPlane === void 0) { useClipPlane = null; }
  44398. var scene = this.getScene();
  44399. var engine = scene.getEngine();
  44400. // Lights
  44401. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44402. defines._needNormals = true;
  44403. // Textures
  44404. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44405. if (defines._areTexturesDirty) {
  44406. defines._needUVs = false;
  44407. if (scene.texturesEnabled) {
  44408. if (scene.getEngine().getCaps().textureLOD) {
  44409. defines.LODBASEDMICROSFURACE = true;
  44410. }
  44411. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44412. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44413. }
  44414. else {
  44415. defines.ALBEDO = false;
  44416. }
  44417. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44419. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44420. }
  44421. else {
  44422. defines.AMBIENT = false;
  44423. }
  44424. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44425. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44426. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44427. }
  44428. else {
  44429. defines.OPACITY = false;
  44430. }
  44431. var reflectionTexture = this._getReflectionTexture();
  44432. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44433. defines.REFLECTION = true;
  44434. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44435. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44436. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44437. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44438. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44439. defines.INVERTCUBICMAP = true;
  44440. }
  44441. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44442. switch (reflectionTexture.coordinatesMode) {
  44443. case BABYLON.Texture.EXPLICIT_MODE:
  44444. defines.REFLECTIONMAP_EXPLICIT = true;
  44445. break;
  44446. case BABYLON.Texture.PLANAR_MODE:
  44447. defines.REFLECTIONMAP_PLANAR = true;
  44448. break;
  44449. case BABYLON.Texture.PROJECTION_MODE:
  44450. defines.REFLECTIONMAP_PROJECTION = true;
  44451. break;
  44452. case BABYLON.Texture.SKYBOX_MODE:
  44453. defines.REFLECTIONMAP_SKYBOX = true;
  44454. break;
  44455. case BABYLON.Texture.SPHERICAL_MODE:
  44456. defines.REFLECTIONMAP_SPHERICAL = true;
  44457. break;
  44458. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44459. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44460. break;
  44461. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44462. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44463. break;
  44464. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44465. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44466. break;
  44467. case BABYLON.Texture.CUBIC_MODE:
  44468. case BABYLON.Texture.INVCUBIC_MODE:
  44469. default:
  44470. defines.REFLECTIONMAP_CUBIC = true;
  44471. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44472. break;
  44473. }
  44474. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44475. if (reflectionTexture.sphericalPolynomial) {
  44476. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44477. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44478. defines.USESPHERICALINVERTEX = false;
  44479. }
  44480. else {
  44481. defines.USESPHERICALINVERTEX = true;
  44482. }
  44483. }
  44484. }
  44485. else {
  44486. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44487. }
  44488. }
  44489. else {
  44490. defines.REFLECTION = false;
  44491. defines.REFLECTIONMAP_3D = false;
  44492. defines.REFLECTIONMAP_SPHERICAL = false;
  44493. defines.REFLECTIONMAP_PLANAR = false;
  44494. defines.REFLECTIONMAP_CUBIC = false;
  44495. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44496. defines.REFLECTIONMAP_PROJECTION = false;
  44497. defines.REFLECTIONMAP_SKYBOX = false;
  44498. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44499. defines.REFLECTIONMAP_EXPLICIT = false;
  44500. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44501. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44502. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44503. defines.INVERTCUBICMAP = false;
  44504. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44505. defines.USESPHERICALINVERTEX = false;
  44506. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44507. defines.LODINREFLECTIONALPHA = false;
  44508. defines.GAMMAREFLECTION = false;
  44509. defines.RGBDREFLECTION = false;
  44510. }
  44511. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44513. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44514. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44515. }
  44516. else {
  44517. defines.LIGHTMAP = false;
  44518. }
  44519. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44520. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44521. }
  44522. else {
  44523. defines.EMISSIVE = false;
  44524. }
  44525. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44526. if (this._metallicTexture) {
  44527. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44528. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44529. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44530. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44531. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44532. }
  44533. else if (this._reflectivityTexture) {
  44534. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44535. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44536. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44537. }
  44538. else {
  44539. defines.REFLECTIVITY = false;
  44540. }
  44541. if (this._microSurfaceTexture) {
  44542. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44543. }
  44544. else {
  44545. defines.MICROSURFACEMAP = false;
  44546. }
  44547. }
  44548. else {
  44549. defines.REFLECTIVITY = false;
  44550. defines.MICROSURFACEMAP = false;
  44551. }
  44552. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44553. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44554. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44555. defines.PARALLAX = true;
  44556. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44557. }
  44558. else {
  44559. defines.PARALLAX = false;
  44560. }
  44561. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44562. }
  44563. else {
  44564. defines.BUMP = false;
  44565. }
  44566. var refractionTexture = this._getRefractionTexture();
  44567. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44568. defines.REFRACTION = true;
  44569. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44570. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44571. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44572. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44573. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44574. if (this._linkRefractionWithTransparency) {
  44575. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44576. }
  44577. }
  44578. else {
  44579. defines.REFRACTION = false;
  44580. }
  44581. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44582. defines.ENVIRONMENTBRDF = true;
  44583. }
  44584. else {
  44585. defines.ENVIRONMENTBRDF = false;
  44586. }
  44587. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44588. defines.ALPHAFROMALBEDO = true;
  44589. }
  44590. else {
  44591. defines.ALPHAFROMALBEDO = false;
  44592. }
  44593. }
  44594. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44595. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44596. defines.USEPHYSICALLIGHTFALLOFF = false;
  44597. defines.USEGLTFLIGHTFALLOFF = false;
  44598. }
  44599. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44600. defines.USEPHYSICALLIGHTFALLOFF = false;
  44601. defines.USEGLTFLIGHTFALLOFF = true;
  44602. }
  44603. else {
  44604. defines.USEPHYSICALLIGHTFALLOFF = true;
  44605. defines.USEGLTFLIGHTFALLOFF = false;
  44606. }
  44607. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44608. if (!this.backFaceCulling && this._twoSidedLighting) {
  44609. defines.TWOSIDEDLIGHTING = true;
  44610. }
  44611. else {
  44612. defines.TWOSIDEDLIGHTING = false;
  44613. }
  44614. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44615. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44616. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44617. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44618. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44619. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44620. }
  44621. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44622. this._imageProcessingConfiguration.prepareDefines(defines);
  44623. }
  44624. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44625. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44626. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44627. // Misc.
  44628. if (defines._areMiscDirty) {
  44629. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44630. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44631. }
  44632. // Values that need to be evaluated on every frame
  44633. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44634. // Attribs
  44635. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44636. };
  44637. /**
  44638. * Force shader compilation
  44639. */
  44640. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44641. var _this = this;
  44642. var localOptions = __assign({ clipPlane: false }, options);
  44643. var defines = new PBRMaterialDefines();
  44644. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44645. if (effect.isReady()) {
  44646. if (onCompiled) {
  44647. onCompiled(this);
  44648. }
  44649. }
  44650. else {
  44651. effect.onCompileObservable.add(function () {
  44652. if (onCompiled) {
  44653. onCompiled(_this);
  44654. }
  44655. });
  44656. }
  44657. };
  44658. /**
  44659. * Initializes the uniform buffer layout for the shader.
  44660. */
  44661. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44662. // Order is important !
  44663. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44664. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44665. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44666. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44667. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44668. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44669. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44670. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44671. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44672. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44673. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44674. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44675. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44676. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44677. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44678. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44679. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44680. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44681. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44682. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44683. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44684. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44685. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44686. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44687. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44688. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44689. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44690. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44691. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44692. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44693. this._uniformBuffer.addUniform("pointSize", 1);
  44694. this._uniformBuffer.create();
  44695. };
  44696. /**
  44697. * Unbinds the textures.
  44698. */
  44699. PBRBaseMaterial.prototype.unbind = function () {
  44700. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44701. this._uniformBuffer.setTexture("reflectionSampler", null);
  44702. }
  44703. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44704. this._uniformBuffer.setTexture("refractionSampler", null);
  44705. }
  44706. _super.prototype.unbind.call(this);
  44707. };
  44708. /**
  44709. * Binds the submesh data.
  44710. * @param world - The world matrix.
  44711. * @param mesh - The BJS mesh.
  44712. * @param subMesh - A submesh of the BJS mesh.
  44713. */
  44714. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44715. var scene = this.getScene();
  44716. var defines = subMesh._materialDefines;
  44717. if (!defines) {
  44718. return;
  44719. }
  44720. var effect = subMesh.effect;
  44721. if (!effect) {
  44722. return;
  44723. }
  44724. this._activeEffect = effect;
  44725. // Matrices
  44726. this.bindOnlyWorldMatrix(world);
  44727. // Normal Matrix
  44728. if (defines.OBJECTSPACE_NORMALMAP) {
  44729. world.toNormalMatrix(this._normalMatrix);
  44730. this.bindOnlyNormalMatrix(this._normalMatrix);
  44731. }
  44732. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44733. // Bones
  44734. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44735. var reflectionTexture = null;
  44736. if (mustRebind) {
  44737. this._uniformBuffer.bindToEffect(effect, "Material");
  44738. this.bindViewProjection(effect);
  44739. reflectionTexture = this._getReflectionTexture();
  44740. var refractionTexture = this._getRefractionTexture();
  44741. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44742. // Texture uniforms
  44743. if (scene.texturesEnabled) {
  44744. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44745. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44746. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44747. }
  44748. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44749. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44750. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44751. }
  44752. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44753. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44754. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44755. }
  44756. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44757. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44758. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44759. if (reflectionTexture.boundingBoxSize) {
  44760. var cubeTexture = reflectionTexture;
  44761. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44762. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44763. }
  44764. var polynomials = reflectionTexture.sphericalPolynomial;
  44765. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44766. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44767. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44768. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44769. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44770. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44771. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44772. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44773. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44774. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44775. }
  44776. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44777. }
  44778. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44779. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44780. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44781. }
  44782. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44783. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44784. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44785. }
  44786. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44787. if (this._metallicTexture) {
  44788. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44789. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44790. }
  44791. else if (this._reflectivityTexture) {
  44792. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44793. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44794. }
  44795. if (this._microSurfaceTexture) {
  44796. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44797. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44798. }
  44799. }
  44800. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44801. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44802. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44803. if (scene._mirroredCameraPosition) {
  44804. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44805. }
  44806. else {
  44807. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44808. }
  44809. }
  44810. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44811. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44812. var depth = 1.0;
  44813. if (!refractionTexture.isCube) {
  44814. if (refractionTexture.depth) {
  44815. depth = refractionTexture.depth;
  44816. }
  44817. }
  44818. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44819. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44820. }
  44821. }
  44822. // Point size
  44823. if (this.pointsCloud) {
  44824. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44825. }
  44826. // Colors
  44827. if (defines.METALLICWORKFLOW) {
  44828. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44829. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44830. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44831. }
  44832. else {
  44833. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44834. }
  44835. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44836. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44837. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44838. // Misc
  44839. this._lightingInfos.x = this._directIntensity;
  44840. this._lightingInfos.y = this._emissiveIntensity;
  44841. this._lightingInfos.z = this._environmentIntensity;
  44842. this._lightingInfos.w = this._specularIntensity;
  44843. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44844. }
  44845. // Textures
  44846. if (scene.texturesEnabled) {
  44847. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44848. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44849. }
  44850. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44851. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44852. }
  44853. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44854. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44855. }
  44856. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44857. if (defines.LODBASEDMICROSFURACE) {
  44858. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44859. }
  44860. else {
  44861. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44862. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44863. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44864. }
  44865. }
  44866. if (defines.ENVIRONMENTBRDF) {
  44867. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44868. }
  44869. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44870. if (defines.LODBASEDMICROSFURACE) {
  44871. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44872. }
  44873. else {
  44874. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44875. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44876. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44877. }
  44878. }
  44879. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44880. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44881. }
  44882. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44883. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44884. }
  44885. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44886. if (this._metallicTexture) {
  44887. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44888. }
  44889. else if (this._reflectivityTexture) {
  44890. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44891. }
  44892. if (this._microSurfaceTexture) {
  44893. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44894. }
  44895. }
  44896. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44897. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44898. }
  44899. }
  44900. // Clip plane
  44901. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44902. // Colors
  44903. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44904. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44905. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44906. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44907. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44908. }
  44909. if (mustRebind || !this.isFrozen) {
  44910. // Lights
  44911. if (scene.lightsEnabled && !this._disableLighting) {
  44912. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44913. }
  44914. // View
  44915. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44916. this.bindView(effect);
  44917. }
  44918. // Fog
  44919. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44920. // Morph targets
  44921. if (defines.NUM_MORPH_INFLUENCERS) {
  44922. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44923. }
  44924. // image processing
  44925. this._imageProcessingConfiguration.bind(this._activeEffect);
  44926. // Log. depth
  44927. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44928. }
  44929. this._uniformBuffer.update();
  44930. this._afterBind(mesh, this._activeEffect);
  44931. };
  44932. /**
  44933. * Returns the animatable textures.
  44934. * @returns - Array of animatable textures.
  44935. */
  44936. PBRBaseMaterial.prototype.getAnimatables = function () {
  44937. var results = [];
  44938. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44939. results.push(this._albedoTexture);
  44940. }
  44941. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44942. results.push(this._ambientTexture);
  44943. }
  44944. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44945. results.push(this._opacityTexture);
  44946. }
  44947. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44948. results.push(this._reflectionTexture);
  44949. }
  44950. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44951. results.push(this._emissiveTexture);
  44952. }
  44953. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44954. results.push(this._metallicTexture);
  44955. }
  44956. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44957. results.push(this._reflectivityTexture);
  44958. }
  44959. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44960. results.push(this._bumpTexture);
  44961. }
  44962. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44963. results.push(this._lightmapTexture);
  44964. }
  44965. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44966. results.push(this._refractionTexture);
  44967. }
  44968. return results;
  44969. };
  44970. /**
  44971. * Returns the texture used for reflections.
  44972. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44973. */
  44974. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44975. if (this._reflectionTexture) {
  44976. return this._reflectionTexture;
  44977. }
  44978. return this.getScene().environmentTexture;
  44979. };
  44980. /**
  44981. * Returns the texture used for refraction or null if none is used.
  44982. * @returns - Refection texture if present. If no refraction texture and refraction
  44983. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44984. */
  44985. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44986. if (this._refractionTexture) {
  44987. return this._refractionTexture;
  44988. }
  44989. if (this._linkRefractionWithTransparency) {
  44990. return this.getScene().environmentTexture;
  44991. }
  44992. return null;
  44993. };
  44994. /**
  44995. * Disposes the resources of the material.
  44996. * @param forceDisposeEffect - Forces the disposal of effects.
  44997. * @param forceDisposeTextures - Forces the disposal of all textures.
  44998. */
  44999. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45000. if (forceDisposeTextures) {
  45001. if (this._albedoTexture) {
  45002. this._albedoTexture.dispose();
  45003. }
  45004. if (this._ambientTexture) {
  45005. this._ambientTexture.dispose();
  45006. }
  45007. if (this._opacityTexture) {
  45008. this._opacityTexture.dispose();
  45009. }
  45010. if (this._reflectionTexture) {
  45011. this._reflectionTexture.dispose();
  45012. }
  45013. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45014. this._environmentBRDFTexture.dispose();
  45015. }
  45016. if (this._emissiveTexture) {
  45017. this._emissiveTexture.dispose();
  45018. }
  45019. if (this._metallicTexture) {
  45020. this._metallicTexture.dispose();
  45021. }
  45022. if (this._reflectivityTexture) {
  45023. this._reflectivityTexture.dispose();
  45024. }
  45025. if (this._bumpTexture) {
  45026. this._bumpTexture.dispose();
  45027. }
  45028. if (this._lightmapTexture) {
  45029. this._lightmapTexture.dispose();
  45030. }
  45031. if (this._refractionTexture) {
  45032. this._refractionTexture.dispose();
  45033. }
  45034. }
  45035. this._renderTargets.dispose();
  45036. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45037. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45038. }
  45039. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45040. };
  45041. /**
  45042. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45043. */
  45044. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45045. /**
  45046. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45047. * to enhance interoperability with other engines.
  45048. */
  45049. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45050. /**
  45051. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45052. * to enhance interoperability with other materials.
  45053. */
  45054. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45055. /**
  45056. * Stores the reflectivity values based on metallic roughness workflow.
  45057. */
  45058. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45059. __decorate([
  45060. BABYLON.serializeAsImageProcessingConfiguration()
  45061. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45062. __decorate([
  45063. BABYLON.serialize()
  45064. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45065. __decorate([
  45066. BABYLON.serialize()
  45067. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45068. return PBRBaseMaterial;
  45069. }(BABYLON.PushMaterial));
  45070. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45071. })(BABYLON || (BABYLON = {}));
  45072. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45073. var BABYLON;
  45074. (function (BABYLON) {
  45075. /**
  45076. * The Physically based simple base material of BJS.
  45077. *
  45078. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45079. * It is used as the base class for both the specGloss and metalRough conventions.
  45080. */
  45081. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45082. __extends(PBRBaseSimpleMaterial, _super);
  45083. /**
  45084. * Instantiates a new PBRMaterial instance.
  45085. *
  45086. * @param name The material name
  45087. * @param scene The scene the material will be use in.
  45088. */
  45089. function PBRBaseSimpleMaterial(name, scene) {
  45090. var _this = _super.call(this, name, scene) || this;
  45091. /**
  45092. * Number of Simultaneous lights allowed on the material.
  45093. */
  45094. _this.maxSimultaneousLights = 4;
  45095. /**
  45096. * If sets to true, disables all the lights affecting the material.
  45097. */
  45098. _this.disableLighting = false;
  45099. /**
  45100. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45101. */
  45102. _this.invertNormalMapX = false;
  45103. /**
  45104. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45105. */
  45106. _this.invertNormalMapY = false;
  45107. /**
  45108. * Emissivie color used to self-illuminate the model.
  45109. */
  45110. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45111. /**
  45112. * Occlusion Channel Strenght.
  45113. */
  45114. _this.occlusionStrength = 1.0;
  45115. _this.useLightmapAsShadowmap = false;
  45116. _this._useAlphaFromAlbedoTexture = true;
  45117. _this._useAmbientInGrayScale = true;
  45118. return _this;
  45119. }
  45120. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45121. /**
  45122. * Gets the current double sided mode.
  45123. */
  45124. get: function () {
  45125. return this._twoSidedLighting;
  45126. },
  45127. /**
  45128. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45129. */
  45130. set: function (value) {
  45131. if (this._twoSidedLighting === value) {
  45132. return;
  45133. }
  45134. this._twoSidedLighting = value;
  45135. this.backFaceCulling = !value;
  45136. this._markAllSubMeshesAsTexturesDirty();
  45137. },
  45138. enumerable: true,
  45139. configurable: true
  45140. });
  45141. /**
  45142. * Return the active textures of the material.
  45143. */
  45144. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45145. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45146. if (this.environmentTexture) {
  45147. activeTextures.push(this.environmentTexture);
  45148. }
  45149. if (this.normalTexture) {
  45150. activeTextures.push(this.normalTexture);
  45151. }
  45152. if (this.emissiveTexture) {
  45153. activeTextures.push(this.emissiveTexture);
  45154. }
  45155. if (this.occlusionTexture) {
  45156. activeTextures.push(this.occlusionTexture);
  45157. }
  45158. if (this.lightmapTexture) {
  45159. activeTextures.push(this.lightmapTexture);
  45160. }
  45161. return activeTextures;
  45162. };
  45163. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45164. if (_super.prototype.hasTexture.call(this, texture)) {
  45165. return true;
  45166. }
  45167. if (this.lightmapTexture === texture) {
  45168. return true;
  45169. }
  45170. return false;
  45171. };
  45172. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45173. return "PBRBaseSimpleMaterial";
  45174. };
  45175. __decorate([
  45176. BABYLON.serialize(),
  45177. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45178. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45179. __decorate([
  45180. BABYLON.serialize(),
  45181. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45182. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45183. __decorate([
  45184. BABYLON.serializeAsTexture(),
  45185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45186. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45187. __decorate([
  45188. BABYLON.serialize(),
  45189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45190. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45191. __decorate([
  45192. BABYLON.serialize(),
  45193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45194. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45195. __decorate([
  45196. BABYLON.serializeAsTexture(),
  45197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45198. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45199. __decorate([
  45200. BABYLON.serializeAsColor3("emissive"),
  45201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45202. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45203. __decorate([
  45204. BABYLON.serializeAsTexture(),
  45205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45206. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45207. __decorate([
  45208. BABYLON.serialize(),
  45209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45210. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45211. __decorate([
  45212. BABYLON.serializeAsTexture(),
  45213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45214. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45215. __decorate([
  45216. BABYLON.serialize(),
  45217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45218. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45219. __decorate([
  45220. BABYLON.serialize()
  45221. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45222. __decorate([
  45223. BABYLON.serializeAsTexture(),
  45224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45225. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45226. __decorate([
  45227. BABYLON.serialize(),
  45228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45229. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45230. return PBRBaseSimpleMaterial;
  45231. }(BABYLON.PBRBaseMaterial));
  45232. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45233. })(BABYLON || (BABYLON = {}));
  45234. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45235. var BABYLON;
  45236. (function (BABYLON) {
  45237. /**
  45238. * The Physically based material of BJS.
  45239. *
  45240. * This offers the main features of a standard PBR material.
  45241. * For more information, please refer to the documentation :
  45242. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45243. */
  45244. var PBRMaterial = /** @class */ (function (_super) {
  45245. __extends(PBRMaterial, _super);
  45246. /**
  45247. * Instantiates a new PBRMaterial instance.
  45248. *
  45249. * @param name The material name
  45250. * @param scene The scene the material will be use in.
  45251. */
  45252. function PBRMaterial(name, scene) {
  45253. var _this = _super.call(this, name, scene) || this;
  45254. /**
  45255. * Intensity of the direct lights e.g. the four lights available in your scene.
  45256. * This impacts both the direct diffuse and specular highlights.
  45257. */
  45258. _this.directIntensity = 1.0;
  45259. /**
  45260. * Intensity of the emissive part of the material.
  45261. * This helps controlling the emissive effect without modifying the emissive color.
  45262. */
  45263. _this.emissiveIntensity = 1.0;
  45264. /**
  45265. * Intensity of the environment e.g. how much the environment will light the object
  45266. * either through harmonics for rough material or through the refelction for shiny ones.
  45267. */
  45268. _this.environmentIntensity = 1.0;
  45269. /**
  45270. * This is a special control allowing the reduction of the specular highlights coming from the
  45271. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45272. */
  45273. _this.specularIntensity = 1.0;
  45274. /**
  45275. * Debug Control allowing disabling the bump map on this material.
  45276. */
  45277. _this.disableBumpMap = false;
  45278. /**
  45279. * AKA Occlusion Texture Intensity in other nomenclature.
  45280. */
  45281. _this.ambientTextureStrength = 1.0;
  45282. /**
  45283. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45284. * 1 means it completely occludes it
  45285. * 0 mean it has no impact
  45286. */
  45287. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45288. /**
  45289. * The color of a material in ambient lighting.
  45290. */
  45291. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45292. /**
  45293. * AKA Diffuse Color in other nomenclature.
  45294. */
  45295. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45296. /**
  45297. * AKA Specular Color in other nomenclature.
  45298. */
  45299. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45300. /**
  45301. * The color reflected from the material.
  45302. */
  45303. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45304. /**
  45305. * The color emitted from the material.
  45306. */
  45307. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45308. /**
  45309. * AKA Glossiness in other nomenclature.
  45310. */
  45311. _this.microSurface = 1.0;
  45312. /**
  45313. * source material index of refraction (IOR)' / 'destination material IOR.
  45314. */
  45315. _this.indexOfRefraction = 0.66;
  45316. /**
  45317. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45318. */
  45319. _this.invertRefractionY = false;
  45320. /**
  45321. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45322. * Materials half opaque for instance using refraction could benefit from this control.
  45323. */
  45324. _this.linkRefractionWithTransparency = false;
  45325. _this.useLightmapAsShadowmap = false;
  45326. /**
  45327. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45328. */
  45329. _this.useAlphaFromAlbedoTexture = false;
  45330. /**
  45331. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45332. */
  45333. _this.forceAlphaTest = false;
  45334. /**
  45335. * Defines the alpha limits in alpha test mode.
  45336. */
  45337. _this.alphaCutOff = 0.4;
  45338. /**
  45339. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45340. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45341. */
  45342. _this.useSpecularOverAlpha = true;
  45343. /**
  45344. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45345. */
  45346. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45347. /**
  45348. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45349. */
  45350. _this.useRoughnessFromMetallicTextureAlpha = true;
  45351. /**
  45352. * Specifies if the metallic texture contains the roughness information in its green channel.
  45353. */
  45354. _this.useRoughnessFromMetallicTextureGreen = false;
  45355. /**
  45356. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45357. */
  45358. _this.useMetallnessFromMetallicTextureBlue = false;
  45359. /**
  45360. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45361. */
  45362. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45363. /**
  45364. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45365. */
  45366. _this.useAmbientInGrayScale = false;
  45367. /**
  45368. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45369. * The material will try to infer what glossiness each pixel should be.
  45370. */
  45371. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45372. /**
  45373. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45374. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45375. */
  45376. _this.useRadianceOverAlpha = true;
  45377. /**
  45378. * Allows using an object space normal map (instead of tangent space).
  45379. */
  45380. _this.useObjectSpaceNormalMap = false;
  45381. /**
  45382. * Allows using the bump map in parallax mode.
  45383. */
  45384. _this.useParallax = false;
  45385. /**
  45386. * Allows using the bump map in parallax occlusion mode.
  45387. */
  45388. _this.useParallaxOcclusion = false;
  45389. /**
  45390. * Controls the scale bias of the parallax mode.
  45391. */
  45392. _this.parallaxScaleBias = 0.05;
  45393. /**
  45394. * If sets to true, disables all the lights affecting the material.
  45395. */
  45396. _this.disableLighting = false;
  45397. /**
  45398. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45399. */
  45400. _this.forceIrradianceInFragment = false;
  45401. /**
  45402. * Number of Simultaneous lights allowed on the material.
  45403. */
  45404. _this.maxSimultaneousLights = 4;
  45405. /**
  45406. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45407. */
  45408. _this.invertNormalMapX = false;
  45409. /**
  45410. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45411. */
  45412. _this.invertNormalMapY = false;
  45413. /**
  45414. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45415. */
  45416. _this.twoSidedLighting = false;
  45417. /**
  45418. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45419. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45420. */
  45421. _this.useAlphaFresnel = false;
  45422. /**
  45423. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45424. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45425. */
  45426. _this.useLinearAlphaFresnel = false;
  45427. /**
  45428. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45429. * And/Or occlude the blended part.
  45430. */
  45431. _this.environmentBRDFTexture = null;
  45432. /**
  45433. * Force normal to face away from face.
  45434. */
  45435. _this.forceNormalForward = false;
  45436. /**
  45437. * Enables specular anti aliasing in the PBR shader.
  45438. * It will both interacts on the Geometry for analytical and IBL lighting.
  45439. * It also prefilter the roughness map based on the bump values.
  45440. */
  45441. _this.enableSpecularAntiAliasing = false;
  45442. /**
  45443. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45444. * makes the reflect vector face the model (under horizon).
  45445. */
  45446. _this.useHorizonOcclusion = true;
  45447. /**
  45448. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45449. * too much the area relying on ambient texture to define their ambient occlusion.
  45450. */
  45451. _this.useRadianceOcclusion = true;
  45452. /**
  45453. * If set to true, no lighting calculations will be applied.
  45454. */
  45455. _this.unlit = false;
  45456. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45457. return _this;
  45458. }
  45459. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45460. /**
  45461. * BJS is using an harcoded light falloff based on a manually sets up range.
  45462. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45463. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45464. */
  45465. get: function () {
  45466. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45467. },
  45468. /**
  45469. * BJS is using an harcoded light falloff based on a manually sets up range.
  45470. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45471. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45472. */
  45473. set: function (value) {
  45474. if (value !== this.usePhysicalLightFalloff) {
  45475. // Ensure the effect will be rebuilt.
  45476. this._markAllSubMeshesAsTexturesDirty();
  45477. if (value) {
  45478. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45479. }
  45480. else {
  45481. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45482. }
  45483. }
  45484. },
  45485. enumerable: true,
  45486. configurable: true
  45487. });
  45488. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45489. /**
  45490. * In order to support the falloff compatibility with gltf, a special mode has been added
  45491. * to reproduce the gltf light falloff.
  45492. */
  45493. get: function () {
  45494. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45495. },
  45496. /**
  45497. * In order to support the falloff compatibility with gltf, a special mode has been added
  45498. * to reproduce the gltf light falloff.
  45499. */
  45500. set: function (value) {
  45501. if (value !== this.useGLTFLightFalloff) {
  45502. // Ensure the effect will be rebuilt.
  45503. this._markAllSubMeshesAsTexturesDirty();
  45504. if (value) {
  45505. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45506. }
  45507. else {
  45508. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45509. }
  45510. }
  45511. },
  45512. enumerable: true,
  45513. configurable: true
  45514. });
  45515. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45516. /**
  45517. * Gets the image processing configuration used either in this material.
  45518. */
  45519. get: function () {
  45520. return this._imageProcessingConfiguration;
  45521. },
  45522. /**
  45523. * Sets the Default image processing configuration used either in the this material.
  45524. *
  45525. * If sets to null, the scene one is in use.
  45526. */
  45527. set: function (value) {
  45528. this._attachImageProcessingConfiguration(value);
  45529. // Ensure the effect will be rebuilt.
  45530. this._markAllSubMeshesAsTexturesDirty();
  45531. },
  45532. enumerable: true,
  45533. configurable: true
  45534. });
  45535. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45536. /**
  45537. * Gets wether the color curves effect is enabled.
  45538. */
  45539. get: function () {
  45540. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45541. },
  45542. /**
  45543. * Sets wether the color curves effect is enabled.
  45544. */
  45545. set: function (value) {
  45546. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45547. },
  45548. enumerable: true,
  45549. configurable: true
  45550. });
  45551. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45552. /**
  45553. * Gets wether the color grading effect is enabled.
  45554. */
  45555. get: function () {
  45556. return this.imageProcessingConfiguration.colorGradingEnabled;
  45557. },
  45558. /**
  45559. * Gets wether the color grading effect is enabled.
  45560. */
  45561. set: function (value) {
  45562. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45563. },
  45564. enumerable: true,
  45565. configurable: true
  45566. });
  45567. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45568. /**
  45569. * Gets wether tonemapping is enabled or not.
  45570. */
  45571. get: function () {
  45572. return this._imageProcessingConfiguration.toneMappingEnabled;
  45573. },
  45574. /**
  45575. * Sets wether tonemapping is enabled or not
  45576. */
  45577. set: function (value) {
  45578. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45579. },
  45580. enumerable: true,
  45581. configurable: true
  45582. });
  45583. ;
  45584. ;
  45585. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45586. /**
  45587. * The camera exposure used on this material.
  45588. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45589. * This corresponds to a photographic exposure.
  45590. */
  45591. get: function () {
  45592. return this._imageProcessingConfiguration.exposure;
  45593. },
  45594. /**
  45595. * The camera exposure used on this material.
  45596. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45597. * This corresponds to a photographic exposure.
  45598. */
  45599. set: function (value) {
  45600. this._imageProcessingConfiguration.exposure = value;
  45601. },
  45602. enumerable: true,
  45603. configurable: true
  45604. });
  45605. ;
  45606. ;
  45607. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45608. /**
  45609. * Gets The camera contrast used on this material.
  45610. */
  45611. get: function () {
  45612. return this._imageProcessingConfiguration.contrast;
  45613. },
  45614. /**
  45615. * Sets The camera contrast used on this material.
  45616. */
  45617. set: function (value) {
  45618. this._imageProcessingConfiguration.contrast = value;
  45619. },
  45620. enumerable: true,
  45621. configurable: true
  45622. });
  45623. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45624. /**
  45625. * Gets the Color Grading 2D Lookup Texture.
  45626. */
  45627. get: function () {
  45628. return this._imageProcessingConfiguration.colorGradingTexture;
  45629. },
  45630. /**
  45631. * Sets the Color Grading 2D Lookup Texture.
  45632. */
  45633. set: function (value) {
  45634. this._imageProcessingConfiguration.colorGradingTexture = value;
  45635. },
  45636. enumerable: true,
  45637. configurable: true
  45638. });
  45639. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45640. /**
  45641. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45642. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45643. * 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;
  45644. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45645. */
  45646. get: function () {
  45647. return this._imageProcessingConfiguration.colorCurves;
  45648. },
  45649. /**
  45650. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45651. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45652. * 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;
  45653. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45654. */
  45655. set: function (value) {
  45656. this._imageProcessingConfiguration.colorCurves = value;
  45657. },
  45658. enumerable: true,
  45659. configurable: true
  45660. });
  45661. /**
  45662. * Returns the name of this material class.
  45663. */
  45664. PBRMaterial.prototype.getClassName = function () {
  45665. return "PBRMaterial";
  45666. };
  45667. /**
  45668. * Returns an array of the actively used textures.
  45669. * @returns - Array of BaseTextures
  45670. */
  45671. PBRMaterial.prototype.getActiveTextures = function () {
  45672. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45673. if (this._albedoTexture) {
  45674. activeTextures.push(this._albedoTexture);
  45675. }
  45676. if (this._ambientTexture) {
  45677. activeTextures.push(this._ambientTexture);
  45678. }
  45679. if (this._opacityTexture) {
  45680. activeTextures.push(this._opacityTexture);
  45681. }
  45682. if (this._reflectionTexture) {
  45683. activeTextures.push(this._reflectionTexture);
  45684. }
  45685. if (this._emissiveTexture) {
  45686. activeTextures.push(this._emissiveTexture);
  45687. }
  45688. if (this._reflectivityTexture) {
  45689. activeTextures.push(this._reflectivityTexture);
  45690. }
  45691. if (this._metallicTexture) {
  45692. activeTextures.push(this._metallicTexture);
  45693. }
  45694. if (this._microSurfaceTexture) {
  45695. activeTextures.push(this._microSurfaceTexture);
  45696. }
  45697. if (this._bumpTexture) {
  45698. activeTextures.push(this._bumpTexture);
  45699. }
  45700. if (this._lightmapTexture) {
  45701. activeTextures.push(this._lightmapTexture);
  45702. }
  45703. if (this._refractionTexture) {
  45704. activeTextures.push(this._refractionTexture);
  45705. }
  45706. return activeTextures;
  45707. };
  45708. /**
  45709. * Checks to see if a texture is used in the material.
  45710. * @param texture - Base texture to use.
  45711. * @returns - Boolean specifying if a texture is used in the material.
  45712. */
  45713. PBRMaterial.prototype.hasTexture = function (texture) {
  45714. if (_super.prototype.hasTexture.call(this, texture)) {
  45715. return true;
  45716. }
  45717. if (this._albedoTexture === texture) {
  45718. return true;
  45719. }
  45720. if (this._ambientTexture === texture) {
  45721. return true;
  45722. }
  45723. if (this._opacityTexture === texture) {
  45724. return true;
  45725. }
  45726. if (this._reflectionTexture === texture) {
  45727. return true;
  45728. }
  45729. if (this._reflectivityTexture === texture) {
  45730. return true;
  45731. }
  45732. if (this._metallicTexture === texture) {
  45733. return true;
  45734. }
  45735. if (this._microSurfaceTexture === texture) {
  45736. return true;
  45737. }
  45738. if (this._bumpTexture === texture) {
  45739. return true;
  45740. }
  45741. if (this._lightmapTexture === texture) {
  45742. return true;
  45743. }
  45744. if (this._refractionTexture === texture) {
  45745. return true;
  45746. }
  45747. return false;
  45748. };
  45749. /**
  45750. * Makes a duplicate of the current material.
  45751. * @param name - name to use for the new material.
  45752. */
  45753. PBRMaterial.prototype.clone = function (name) {
  45754. var _this = this;
  45755. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45756. clone.id = name;
  45757. clone.name = name;
  45758. return clone;
  45759. };
  45760. /**
  45761. * Serializes this PBR Material.
  45762. * @returns - An object with the serialized material.
  45763. */
  45764. PBRMaterial.prototype.serialize = function () {
  45765. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45766. serializationObject.customType = "BABYLON.PBRMaterial";
  45767. return serializationObject;
  45768. };
  45769. // Statics
  45770. /**
  45771. * Parses a PBR Material from a serialized object.
  45772. * @param source - Serialized object.
  45773. * @param scene - BJS scene instance.
  45774. * @param rootUrl - url for the scene object
  45775. * @returns - PBRMaterial
  45776. */
  45777. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45778. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45779. };
  45780. /**
  45781. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45782. */
  45783. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45784. /**
  45785. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45786. */
  45787. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45788. /**
  45789. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45790. */
  45791. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45792. /**
  45793. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45794. * They are also discarded below the alpha cutoff threshold to improve performances.
  45795. */
  45796. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45797. /**
  45798. * Defines the default value of how much AO map is occluding the analytical lights
  45799. * (point spot...).
  45800. */
  45801. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45802. __decorate([
  45803. BABYLON.serialize(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45805. ], PBRMaterial.prototype, "directIntensity", void 0);
  45806. __decorate([
  45807. BABYLON.serialize(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45809. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45810. __decorate([
  45811. BABYLON.serialize(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45814. __decorate([
  45815. BABYLON.serialize(),
  45816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45817. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45818. __decorate([
  45819. BABYLON.serialize(),
  45820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45821. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45822. __decorate([
  45823. BABYLON.serializeAsTexture(),
  45824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45825. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45826. __decorate([
  45827. BABYLON.serializeAsTexture(),
  45828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45829. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45830. __decorate([
  45831. BABYLON.serialize(),
  45832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45833. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45834. __decorate([
  45835. BABYLON.serialize(),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45837. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45838. __decorate([
  45839. BABYLON.serializeAsTexture(),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45841. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45842. __decorate([
  45843. BABYLON.serializeAsTexture(),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45846. __decorate([
  45847. BABYLON.serializeAsTexture(),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45850. __decorate([
  45851. BABYLON.serializeAsTexture(),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45853. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45854. __decorate([
  45855. BABYLON.serializeAsTexture(),
  45856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45857. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45858. __decorate([
  45859. BABYLON.serialize(),
  45860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45861. ], PBRMaterial.prototype, "metallic", void 0);
  45862. __decorate([
  45863. BABYLON.serialize(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45865. ], PBRMaterial.prototype, "roughness", void 0);
  45866. __decorate([
  45867. BABYLON.serializeAsTexture(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45870. __decorate([
  45871. BABYLON.serializeAsTexture(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45873. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45874. __decorate([
  45875. BABYLON.serializeAsTexture(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45877. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45878. __decorate([
  45879. BABYLON.serializeAsTexture(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45882. __decorate([
  45883. BABYLON.serializeAsColor3("ambient"),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRMaterial.prototype, "ambientColor", void 0);
  45886. __decorate([
  45887. BABYLON.serializeAsColor3("albedo"),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRMaterial.prototype, "albedoColor", void 0);
  45890. __decorate([
  45891. BABYLON.serializeAsColor3("reflectivity"),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45894. __decorate([
  45895. BABYLON.serializeAsColor3("reflection"),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45898. __decorate([
  45899. BABYLON.serializeAsColor3("emissive"),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45901. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45902. __decorate([
  45903. BABYLON.serialize(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45905. ], PBRMaterial.prototype, "microSurface", void 0);
  45906. __decorate([
  45907. BABYLON.serialize(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45909. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45910. __decorate([
  45911. BABYLON.serialize(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45913. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45914. __decorate([
  45915. BABYLON.serialize(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45917. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45918. __decorate([
  45919. BABYLON.serialize(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45921. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45922. __decorate([
  45923. BABYLON.serialize(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45925. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45926. __decorate([
  45927. BABYLON.serialize(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45929. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45930. __decorate([
  45931. BABYLON.serialize(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45933. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45934. __decorate([
  45935. BABYLON.serialize(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45938. __decorate([
  45939. BABYLON.serialize(),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45941. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45942. __decorate([
  45943. BABYLON.serialize(),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45945. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45946. __decorate([
  45947. BABYLON.serialize(),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45949. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45950. __decorate([
  45951. BABYLON.serialize(),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45953. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45954. __decorate([
  45955. BABYLON.serialize(),
  45956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45957. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45958. __decorate([
  45959. BABYLON.serialize(),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45961. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45962. __decorate([
  45963. BABYLON.serialize(),
  45964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45965. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45966. __decorate([
  45967. BABYLON.serialize()
  45968. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45969. __decorate([
  45970. BABYLON.serialize()
  45971. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45972. __decorate([
  45973. BABYLON.serialize(),
  45974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45975. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45976. __decorate([
  45977. BABYLON.serialize(),
  45978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45979. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45980. __decorate([
  45981. BABYLON.serialize(),
  45982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45983. ], PBRMaterial.prototype, "useParallax", void 0);
  45984. __decorate([
  45985. BABYLON.serialize(),
  45986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45987. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45988. __decorate([
  45989. BABYLON.serialize(),
  45990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45991. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45992. __decorate([
  45993. BABYLON.serialize(),
  45994. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45995. ], PBRMaterial.prototype, "disableLighting", void 0);
  45996. __decorate([
  45997. BABYLON.serialize(),
  45998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45999. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46000. __decorate([
  46001. BABYLON.serialize(),
  46002. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46003. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46004. __decorate([
  46005. BABYLON.serialize(),
  46006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46007. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46008. __decorate([
  46009. BABYLON.serialize(),
  46010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46011. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46012. __decorate([
  46013. BABYLON.serialize(),
  46014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46015. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46016. __decorate([
  46017. BABYLON.serialize(),
  46018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46019. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46020. __decorate([
  46021. BABYLON.serialize(),
  46022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46023. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46024. __decorate([
  46025. BABYLON.serializeAsTexture(),
  46026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46027. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46028. __decorate([
  46029. BABYLON.serialize(),
  46030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46031. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46032. __decorate([
  46033. BABYLON.serialize(),
  46034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46035. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46036. __decorate([
  46037. BABYLON.serialize(),
  46038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46039. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46040. __decorate([
  46041. BABYLON.serialize(),
  46042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46043. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46044. __decorate([
  46045. BABYLON.serialize(),
  46046. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46047. ], PBRMaterial.prototype, "unlit", void 0);
  46048. return PBRMaterial;
  46049. }(BABYLON.PBRBaseMaterial));
  46050. BABYLON.PBRMaterial = PBRMaterial;
  46051. })(BABYLON || (BABYLON = {}));
  46052. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46053. var BABYLON;
  46054. (function (BABYLON) {
  46055. /**
  46056. * The PBR material of BJS following the metal roughness convention.
  46057. *
  46058. * This fits to the PBR convention in the GLTF definition:
  46059. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46060. */
  46061. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46062. __extends(PBRMetallicRoughnessMaterial, _super);
  46063. /**
  46064. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46065. *
  46066. * @param name The material name
  46067. * @param scene The scene the material will be use in.
  46068. */
  46069. function PBRMetallicRoughnessMaterial(name, scene) {
  46070. var _this = _super.call(this, name, scene) || this;
  46071. _this._useRoughnessFromMetallicTextureAlpha = false;
  46072. _this._useRoughnessFromMetallicTextureGreen = true;
  46073. _this._useMetallnessFromMetallicTextureBlue = true;
  46074. _this.metallic = 1.0;
  46075. _this.roughness = 1.0;
  46076. return _this;
  46077. }
  46078. /**
  46079. * Return the currrent class name of the material.
  46080. */
  46081. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46082. return "PBRMetallicRoughnessMaterial";
  46083. };
  46084. /**
  46085. * Return the active textures of the material.
  46086. */
  46087. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46088. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46089. if (this.baseTexture) {
  46090. activeTextures.push(this.baseTexture);
  46091. }
  46092. if (this.metallicRoughnessTexture) {
  46093. activeTextures.push(this.metallicRoughnessTexture);
  46094. }
  46095. return activeTextures;
  46096. };
  46097. /**
  46098. * Checks to see if a texture is used in the material.
  46099. * @param texture - Base texture to use.
  46100. * @returns - Boolean specifying if a texture is used in the material.
  46101. */
  46102. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46103. if (_super.prototype.hasTexture.call(this, texture)) {
  46104. return true;
  46105. }
  46106. if (this.baseTexture === texture) {
  46107. return true;
  46108. }
  46109. if (this.metallicRoughnessTexture === texture) {
  46110. return true;
  46111. }
  46112. return false;
  46113. };
  46114. /**
  46115. * Makes a duplicate of the current material.
  46116. * @param name - name to use for the new material.
  46117. */
  46118. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46119. var _this = this;
  46120. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46121. clone.id = name;
  46122. clone.name = name;
  46123. return clone;
  46124. };
  46125. /**
  46126. * Serialize the material to a parsable JSON object.
  46127. */
  46128. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46129. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46130. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46131. return serializationObject;
  46132. };
  46133. /**
  46134. * Parses a JSON object correponding to the serialize function.
  46135. */
  46136. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46137. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46138. };
  46139. __decorate([
  46140. BABYLON.serializeAsColor3(),
  46141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46142. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46143. __decorate([
  46144. BABYLON.serializeAsTexture(),
  46145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46146. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46147. __decorate([
  46148. BABYLON.serialize(),
  46149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46150. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46151. __decorate([
  46152. BABYLON.serialize(),
  46153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46154. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46155. __decorate([
  46156. BABYLON.serializeAsTexture(),
  46157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46158. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46159. return PBRMetallicRoughnessMaterial;
  46160. }(BABYLON.PBRBaseSimpleMaterial));
  46161. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46162. })(BABYLON || (BABYLON = {}));
  46163. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46164. var BABYLON;
  46165. (function (BABYLON) {
  46166. /**
  46167. * The PBR material of BJS following the specular glossiness convention.
  46168. *
  46169. * This fits to the PBR convention in the GLTF definition:
  46170. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46171. */
  46172. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46173. __extends(PBRSpecularGlossinessMaterial, _super);
  46174. /**
  46175. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46176. *
  46177. * @param name The material name
  46178. * @param scene The scene the material will be use in.
  46179. */
  46180. function PBRSpecularGlossinessMaterial(name, scene) {
  46181. var _this = _super.call(this, name, scene) || this;
  46182. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46183. return _this;
  46184. }
  46185. /**
  46186. * Return the currrent class name of the material.
  46187. */
  46188. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46189. return "PBRSpecularGlossinessMaterial";
  46190. };
  46191. /**
  46192. * Return the active textures of the material.
  46193. */
  46194. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46195. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46196. if (this.diffuseTexture) {
  46197. activeTextures.push(this.diffuseTexture);
  46198. }
  46199. if (this.specularGlossinessTexture) {
  46200. activeTextures.push(this.specularGlossinessTexture);
  46201. }
  46202. return activeTextures;
  46203. };
  46204. /**
  46205. * Checks to see if a texture is used in the material.
  46206. * @param texture - Base texture to use.
  46207. * @returns - Boolean specifying if a texture is used in the material.
  46208. */
  46209. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46210. if (_super.prototype.hasTexture.call(this, texture)) {
  46211. return true;
  46212. }
  46213. if (this.diffuseTexture === texture) {
  46214. return true;
  46215. }
  46216. if (this.specularGlossinessTexture === texture) {
  46217. return true;
  46218. }
  46219. return false;
  46220. };
  46221. /**
  46222. * Makes a duplicate of the current material.
  46223. * @param name - name to use for the new material.
  46224. */
  46225. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46226. var _this = this;
  46227. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46228. clone.id = name;
  46229. clone.name = name;
  46230. return clone;
  46231. };
  46232. /**
  46233. * Serialize the material to a parsable JSON object.
  46234. */
  46235. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46236. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46237. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46238. return serializationObject;
  46239. };
  46240. /**
  46241. * Parses a JSON object correponding to the serialize function.
  46242. */
  46243. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46244. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46245. };
  46246. __decorate([
  46247. BABYLON.serializeAsColor3("diffuse"),
  46248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46249. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46250. __decorate([
  46251. BABYLON.serializeAsTexture(),
  46252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46253. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46254. __decorate([
  46255. BABYLON.serializeAsColor3("specular"),
  46256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46257. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46258. __decorate([
  46259. BABYLON.serialize(),
  46260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46261. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46262. __decorate([
  46263. BABYLON.serializeAsTexture(),
  46264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46265. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46266. return PBRSpecularGlossinessMaterial;
  46267. }(BABYLON.PBRBaseSimpleMaterial));
  46268. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46269. })(BABYLON || (BABYLON = {}));
  46270. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46271. var BABYLON;
  46272. (function (BABYLON) {
  46273. BABYLON.CameraInputTypes = {};
  46274. var CameraInputsManager = /** @class */ (function () {
  46275. function CameraInputsManager(camera) {
  46276. this.attached = {};
  46277. this.camera = camera;
  46278. this.checkInputs = function () { };
  46279. }
  46280. /**
  46281. * Add an input method to a camera
  46282. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46283. * @param input camera input method
  46284. */
  46285. CameraInputsManager.prototype.add = function (input) {
  46286. var type = input.getSimpleName();
  46287. if (this.attached[type]) {
  46288. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46289. return;
  46290. }
  46291. this.attached[type] = input;
  46292. input.camera = this.camera;
  46293. //for checkInputs, we are dynamically creating a function
  46294. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46295. if (input.checkInputs) {
  46296. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46297. }
  46298. if (this.attachedElement) {
  46299. input.attachControl(this.attachedElement);
  46300. }
  46301. };
  46302. /**
  46303. * Remove a specific input method from a camera
  46304. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46305. * @param inputToRemove camera input method
  46306. */
  46307. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46308. for (var cam in this.attached) {
  46309. var input = this.attached[cam];
  46310. if (input === inputToRemove) {
  46311. input.detachControl(this.attachedElement);
  46312. input.camera = null;
  46313. delete this.attached[cam];
  46314. this.rebuildInputCheck();
  46315. }
  46316. }
  46317. };
  46318. CameraInputsManager.prototype.removeByType = function (inputType) {
  46319. for (var cam in this.attached) {
  46320. var input = this.attached[cam];
  46321. if (input.getClassName() === inputType) {
  46322. input.detachControl(this.attachedElement);
  46323. input.camera = null;
  46324. delete this.attached[cam];
  46325. this.rebuildInputCheck();
  46326. }
  46327. }
  46328. };
  46329. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46330. var current = this.checkInputs;
  46331. return function () {
  46332. current();
  46333. fn();
  46334. };
  46335. };
  46336. CameraInputsManager.prototype.attachInput = function (input) {
  46337. if (this.attachedElement) {
  46338. input.attachControl(this.attachedElement, this.noPreventDefault);
  46339. }
  46340. };
  46341. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46342. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46343. if (this.attachedElement) {
  46344. return;
  46345. }
  46346. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46347. this.attachedElement = element;
  46348. this.noPreventDefault = noPreventDefault;
  46349. for (var cam in this.attached) {
  46350. this.attached[cam].attachControl(element, noPreventDefault);
  46351. }
  46352. };
  46353. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46354. if (disconnect === void 0) { disconnect = false; }
  46355. if (this.attachedElement !== element) {
  46356. return;
  46357. }
  46358. for (var cam in this.attached) {
  46359. this.attached[cam].detachControl(element);
  46360. if (disconnect) {
  46361. this.attached[cam].camera = null;
  46362. }
  46363. }
  46364. this.attachedElement = null;
  46365. };
  46366. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46367. this.checkInputs = function () { };
  46368. for (var cam in this.attached) {
  46369. var input = this.attached[cam];
  46370. if (input.checkInputs) {
  46371. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46372. }
  46373. }
  46374. };
  46375. /**
  46376. * Remove all attached input methods from a camera
  46377. */
  46378. CameraInputsManager.prototype.clear = function () {
  46379. if (this.attachedElement) {
  46380. this.detachElement(this.attachedElement, true);
  46381. }
  46382. this.attached = {};
  46383. this.attachedElement = null;
  46384. this.checkInputs = function () { };
  46385. };
  46386. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46387. var inputs = {};
  46388. for (var cam in this.attached) {
  46389. var input = this.attached[cam];
  46390. var res = BABYLON.SerializationHelper.Serialize(input);
  46391. inputs[input.getClassName()] = res;
  46392. }
  46393. serializedCamera.inputsmgr = inputs;
  46394. };
  46395. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46396. var parsedInputs = parsedCamera.inputsmgr;
  46397. if (parsedInputs) {
  46398. this.clear();
  46399. for (var n in parsedInputs) {
  46400. var construct = BABYLON.CameraInputTypes[n];
  46401. if (construct) {
  46402. var parsedinput = parsedInputs[n];
  46403. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46404. this.add(input);
  46405. }
  46406. }
  46407. }
  46408. else {
  46409. //2016-03-08 this part is for managing backward compatibility
  46410. for (var n in this.attached) {
  46411. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46412. if (construct) {
  46413. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46414. this.remove(this.attached[n]);
  46415. this.add(input);
  46416. }
  46417. }
  46418. }
  46419. };
  46420. return CameraInputsManager;
  46421. }());
  46422. BABYLON.CameraInputsManager = CameraInputsManager;
  46423. })(BABYLON || (BABYLON = {}));
  46424. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46425. var BABYLON;
  46426. (function (BABYLON) {
  46427. var TargetCamera = /** @class */ (function (_super) {
  46428. __extends(TargetCamera, _super);
  46429. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46430. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46431. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46432. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46433. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46434. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46435. _this.speed = 2.0;
  46436. _this.noRotationConstraint = false;
  46437. _this.lockedTarget = null;
  46438. /** @hidden */
  46439. _this._currentTarget = BABYLON.Vector3.Zero();
  46440. /** @hidden */
  46441. _this._viewMatrix = BABYLON.Matrix.Zero();
  46442. /** @hidden */
  46443. _this._camMatrix = BABYLON.Matrix.Zero();
  46444. /** @hidden */
  46445. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46446. /** @hidden */
  46447. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46448. /** @hidden */
  46449. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46450. /** @hidden */
  46451. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46452. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46453. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46454. _this._defaultUp = BABYLON.Vector3.Up();
  46455. _this._cachedRotationZ = 0;
  46456. return _this;
  46457. }
  46458. TargetCamera.prototype.getFrontPosition = function (distance) {
  46459. this.getWorldMatrix();
  46460. var direction = this.getTarget().subtract(this.position);
  46461. direction.normalize();
  46462. direction.scaleInPlace(distance);
  46463. return this.globalPosition.add(direction);
  46464. };
  46465. /** @hidden */
  46466. TargetCamera.prototype._getLockedTargetPosition = function () {
  46467. if (!this.lockedTarget) {
  46468. return null;
  46469. }
  46470. if (this.lockedTarget.absolutePosition) {
  46471. this.lockedTarget.computeWorldMatrix();
  46472. }
  46473. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46474. };
  46475. TargetCamera.prototype.storeState = function () {
  46476. this._storedPosition = this.position.clone();
  46477. this._storedRotation = this.rotation.clone();
  46478. if (this.rotationQuaternion) {
  46479. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46480. }
  46481. return _super.prototype.storeState.call(this);
  46482. };
  46483. /**
  46484. * Restored camera state. You must call storeState() first
  46485. * @returns whether it was successful or not
  46486. * @hidden
  46487. */
  46488. TargetCamera.prototype._restoreStateValues = function () {
  46489. if (!_super.prototype._restoreStateValues.call(this)) {
  46490. return false;
  46491. }
  46492. this.position = this._storedPosition.clone();
  46493. this.rotation = this._storedRotation.clone();
  46494. if (this.rotationQuaternion) {
  46495. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46496. }
  46497. this.cameraDirection.copyFromFloats(0, 0, 0);
  46498. this.cameraRotation.copyFromFloats(0, 0);
  46499. return true;
  46500. };
  46501. // Cache
  46502. /** @hidden */
  46503. TargetCamera.prototype._initCache = function () {
  46504. _super.prototype._initCache.call(this);
  46505. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46506. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46507. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46508. };
  46509. /** @hidden */
  46510. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46511. if (!ignoreParentClass) {
  46512. _super.prototype._updateCache.call(this);
  46513. }
  46514. var lockedTargetPosition = this._getLockedTargetPosition();
  46515. if (!lockedTargetPosition) {
  46516. this._cache.lockedTarget = null;
  46517. }
  46518. else {
  46519. if (!this._cache.lockedTarget) {
  46520. this._cache.lockedTarget = lockedTargetPosition.clone();
  46521. }
  46522. else {
  46523. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46524. }
  46525. }
  46526. this._cache.rotation.copyFrom(this.rotation);
  46527. if (this.rotationQuaternion)
  46528. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46529. };
  46530. // Synchronized
  46531. /** @hidden */
  46532. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46533. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46534. return false;
  46535. }
  46536. var lockedTargetPosition = this._getLockedTargetPosition();
  46537. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46538. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46539. };
  46540. // Methods
  46541. /** @hidden */
  46542. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46543. var engine = this.getEngine();
  46544. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46545. };
  46546. // Target
  46547. /** @hidden */
  46548. TargetCamera.prototype.setTarget = function (target) {
  46549. this.upVector.normalize();
  46550. if (this.position.z === target.z) {
  46551. this.position.z += BABYLON.Epsilon;
  46552. }
  46553. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46554. this._camMatrix.invert();
  46555. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46556. var vDir = target.subtract(this.position);
  46557. if (vDir.x >= 0.0) {
  46558. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46559. }
  46560. else {
  46561. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46562. }
  46563. this.rotation.z = 0;
  46564. if (isNaN(this.rotation.x)) {
  46565. this.rotation.x = 0;
  46566. }
  46567. if (isNaN(this.rotation.y)) {
  46568. this.rotation.y = 0;
  46569. }
  46570. if (isNaN(this.rotation.z)) {
  46571. this.rotation.z = 0;
  46572. }
  46573. if (this.rotationQuaternion) {
  46574. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46575. }
  46576. };
  46577. /**
  46578. * Return the current target position of the camera. This value is expressed in local space.
  46579. */
  46580. TargetCamera.prototype.getTarget = function () {
  46581. return this._currentTarget;
  46582. };
  46583. /** @hidden */
  46584. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46585. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46586. };
  46587. /** @hidden */
  46588. TargetCamera.prototype._updatePosition = function () {
  46589. if (this.parent) {
  46590. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46591. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46592. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46593. return;
  46594. }
  46595. this.position.addInPlace(this.cameraDirection);
  46596. };
  46597. /** @hidden */
  46598. TargetCamera.prototype._checkInputs = function () {
  46599. var needToMove = this._decideIfNeedsToMove();
  46600. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46601. // Move
  46602. if (needToMove) {
  46603. this._updatePosition();
  46604. }
  46605. // Rotate
  46606. if (needToRotate) {
  46607. this.rotation.x += this.cameraRotation.x;
  46608. this.rotation.y += this.cameraRotation.y;
  46609. //rotate, if quaternion is set and rotation was used
  46610. if (this.rotationQuaternion) {
  46611. var len = this.rotation.lengthSquared();
  46612. if (len) {
  46613. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46614. }
  46615. }
  46616. if (!this.noRotationConstraint) {
  46617. var limit = (Math.PI / 2) * 0.95;
  46618. if (this.rotation.x > limit)
  46619. this.rotation.x = limit;
  46620. if (this.rotation.x < -limit)
  46621. this.rotation.x = -limit;
  46622. }
  46623. }
  46624. // Inertia
  46625. if (needToMove) {
  46626. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46627. this.cameraDirection.x = 0;
  46628. }
  46629. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46630. this.cameraDirection.y = 0;
  46631. }
  46632. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46633. this.cameraDirection.z = 0;
  46634. }
  46635. this.cameraDirection.scaleInPlace(this.inertia);
  46636. }
  46637. if (needToRotate) {
  46638. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46639. this.cameraRotation.x = 0;
  46640. }
  46641. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46642. this.cameraRotation.y = 0;
  46643. }
  46644. this.cameraRotation.scaleInPlace(this.inertia);
  46645. }
  46646. _super.prototype._checkInputs.call(this);
  46647. };
  46648. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46649. if (this.rotationQuaternion) {
  46650. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46651. }
  46652. else {
  46653. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46654. }
  46655. };
  46656. /**
  46657. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46658. * @returns the current camera
  46659. */
  46660. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46661. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46662. return this;
  46663. };
  46664. /** @hidden */
  46665. TargetCamera.prototype._getViewMatrix = function () {
  46666. if (this.lockedTarget) {
  46667. this.setTarget(this._getLockedTargetPosition());
  46668. }
  46669. // Compute
  46670. this._updateCameraRotationMatrix();
  46671. // Apply the changed rotation to the upVector.
  46672. if (this._cachedRotationZ != this.rotation.z) {
  46673. this._rotateUpVectorWithCameraRotationMatrix();
  46674. this._cachedRotationZ = this.rotation.z;
  46675. }
  46676. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46677. // Computing target and final matrix
  46678. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46679. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46680. return this._viewMatrix;
  46681. };
  46682. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46683. if (this.parent) {
  46684. var parentWorldMatrix = this.parent.getWorldMatrix();
  46685. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46686. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46687. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46688. this._markSyncedWithParent();
  46689. }
  46690. else {
  46691. this._globalPosition.copyFrom(position);
  46692. this._globalCurrentTarget.copyFrom(target);
  46693. this._globalCurrentUpVector.copyFrom(up);
  46694. }
  46695. if (this.getScene().useRightHandedSystem) {
  46696. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46697. }
  46698. else {
  46699. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46700. }
  46701. };
  46702. /**
  46703. * @override
  46704. * Override Camera.createRigCamera
  46705. */
  46706. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46707. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46708. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46709. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46710. if (!this.rotationQuaternion) {
  46711. this.rotationQuaternion = new BABYLON.Quaternion();
  46712. }
  46713. rigCamera._cameraRigParams = {};
  46714. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46715. }
  46716. return rigCamera;
  46717. }
  46718. return null;
  46719. };
  46720. /**
  46721. * @hidden
  46722. * @override
  46723. * Override Camera._updateRigCameras
  46724. */
  46725. TargetCamera.prototype._updateRigCameras = function () {
  46726. var camLeft = this._rigCameras[0];
  46727. var camRight = this._rigCameras[1];
  46728. switch (this.cameraRigMode) {
  46729. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46730. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46731. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46732. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46733. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46734. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46735. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46736. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46737. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46738. camLeft.setTarget(this.getTarget());
  46739. camRight.setTarget(this.getTarget());
  46740. break;
  46741. case BABYLON.Camera.RIG_MODE_VR:
  46742. if (camLeft.rotationQuaternion) {
  46743. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46744. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46745. }
  46746. else {
  46747. camLeft.rotation.copyFrom(this.rotation);
  46748. camRight.rotation.copyFrom(this.rotation);
  46749. }
  46750. camLeft.position.copyFrom(this.position);
  46751. camRight.position.copyFrom(this.position);
  46752. break;
  46753. }
  46754. _super.prototype._updateRigCameras.call(this);
  46755. };
  46756. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46757. if (!this._rigCamTransformMatrix) {
  46758. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46759. }
  46760. var target = this.getTarget();
  46761. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46762. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46763. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46764. };
  46765. TargetCamera.prototype.getClassName = function () {
  46766. return "TargetCamera";
  46767. };
  46768. __decorate([
  46769. BABYLON.serializeAsVector3()
  46770. ], TargetCamera.prototype, "rotation", void 0);
  46771. __decorate([
  46772. BABYLON.serialize()
  46773. ], TargetCamera.prototype, "speed", void 0);
  46774. __decorate([
  46775. BABYLON.serializeAsMeshReference("lockedTargetId")
  46776. ], TargetCamera.prototype, "lockedTarget", void 0);
  46777. return TargetCamera;
  46778. }(BABYLON.Camera));
  46779. BABYLON.TargetCamera = TargetCamera;
  46780. })(BABYLON || (BABYLON = {}));
  46781. //# sourceMappingURL=babylon.targetCamera.js.map
  46782. var BABYLON;
  46783. (function (BABYLON) {
  46784. var FreeCameraMouseInput = /** @class */ (function () {
  46785. function FreeCameraMouseInput(touchEnabled) {
  46786. if (touchEnabled === void 0) { touchEnabled = true; }
  46787. this.touchEnabled = touchEnabled;
  46788. this.buttons = [0, 1, 2];
  46789. this.angularSensibility = 2000.0;
  46790. this.previousPosition = null;
  46791. }
  46792. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46793. var _this = this;
  46794. var engine = this.camera.getEngine();
  46795. if (!this._pointerInput) {
  46796. this._pointerInput = function (p, s) {
  46797. var evt = p.event;
  46798. if (engine.isInVRExclusivePointerMode) {
  46799. return;
  46800. }
  46801. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46802. return;
  46803. }
  46804. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46805. return;
  46806. }
  46807. var srcElement = (evt.srcElement || evt.target);
  46808. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46809. try {
  46810. srcElement.setPointerCapture(evt.pointerId);
  46811. }
  46812. catch (e) {
  46813. //Nothing to do with the error. Execution will continue.
  46814. }
  46815. _this.previousPosition = {
  46816. x: evt.clientX,
  46817. y: evt.clientY
  46818. };
  46819. if (!noPreventDefault) {
  46820. evt.preventDefault();
  46821. element.focus();
  46822. }
  46823. }
  46824. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46825. try {
  46826. srcElement.releasePointerCapture(evt.pointerId);
  46827. }
  46828. catch (e) {
  46829. //Nothing to do with the error.
  46830. }
  46831. _this.previousPosition = null;
  46832. if (!noPreventDefault) {
  46833. evt.preventDefault();
  46834. }
  46835. }
  46836. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46837. if (!_this.previousPosition || engine.isPointerLock) {
  46838. return;
  46839. }
  46840. var offsetX = evt.clientX - _this.previousPosition.x;
  46841. if (_this.camera.getScene().useRightHandedSystem)
  46842. offsetX *= -1;
  46843. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46844. offsetX *= -1;
  46845. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46846. var offsetY = evt.clientY - _this.previousPosition.y;
  46847. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46848. _this.previousPosition = {
  46849. x: evt.clientX,
  46850. y: evt.clientY
  46851. };
  46852. if (!noPreventDefault) {
  46853. evt.preventDefault();
  46854. }
  46855. }
  46856. };
  46857. }
  46858. this._onMouseMove = function (evt) {
  46859. if (!engine.isPointerLock) {
  46860. return;
  46861. }
  46862. if (engine.isInVRExclusivePointerMode) {
  46863. return;
  46864. }
  46865. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46866. if (_this.camera.getScene().useRightHandedSystem)
  46867. offsetX *= -1;
  46868. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46869. offsetX *= -1;
  46870. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46871. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46872. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46873. _this.previousPosition = null;
  46874. if (!noPreventDefault) {
  46875. evt.preventDefault();
  46876. }
  46877. };
  46878. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46879. element.addEventListener("mousemove", this._onMouseMove, false);
  46880. };
  46881. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46882. if (this._observer && element) {
  46883. this.camera.getScene().onPointerObservable.remove(this._observer);
  46884. if (this._onMouseMove) {
  46885. element.removeEventListener("mousemove", this._onMouseMove);
  46886. }
  46887. this._observer = null;
  46888. this._onMouseMove = null;
  46889. this.previousPosition = null;
  46890. }
  46891. };
  46892. FreeCameraMouseInput.prototype.getClassName = function () {
  46893. return "FreeCameraMouseInput";
  46894. };
  46895. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46896. return "mouse";
  46897. };
  46898. __decorate([
  46899. BABYLON.serialize()
  46900. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46901. __decorate([
  46902. BABYLON.serialize()
  46903. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46904. return FreeCameraMouseInput;
  46905. }());
  46906. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46907. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46908. })(BABYLON || (BABYLON = {}));
  46909. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46910. var BABYLON;
  46911. (function (BABYLON) {
  46912. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46913. function FreeCameraKeyboardMoveInput() {
  46914. this._keys = new Array();
  46915. this.keysUp = [38];
  46916. this.keysDown = [40];
  46917. this.keysLeft = [37];
  46918. this.keysRight = [39];
  46919. }
  46920. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46921. var _this = this;
  46922. if (this._onCanvasBlurObserver) {
  46923. return;
  46924. }
  46925. this._scene = this.camera.getScene();
  46926. this._engine = this._scene.getEngine();
  46927. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46928. _this._keys = [];
  46929. });
  46930. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46931. var evt = info.event;
  46932. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46933. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46934. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46935. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46936. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46937. var index = _this._keys.indexOf(evt.keyCode);
  46938. if (index === -1) {
  46939. _this._keys.push(evt.keyCode);
  46940. }
  46941. if (!noPreventDefault) {
  46942. evt.preventDefault();
  46943. }
  46944. }
  46945. }
  46946. else {
  46947. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46948. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46949. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46950. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46951. var index = _this._keys.indexOf(evt.keyCode);
  46952. if (index >= 0) {
  46953. _this._keys.splice(index, 1);
  46954. }
  46955. if (!noPreventDefault) {
  46956. evt.preventDefault();
  46957. }
  46958. }
  46959. }
  46960. });
  46961. };
  46962. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46963. if (this._scene) {
  46964. if (this._onKeyboardObserver) {
  46965. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46966. }
  46967. if (this._onCanvasBlurObserver) {
  46968. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46969. }
  46970. this._onKeyboardObserver = null;
  46971. this._onCanvasBlurObserver = null;
  46972. }
  46973. this._keys = [];
  46974. };
  46975. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46976. if (this._onKeyboardObserver) {
  46977. var camera = this.camera;
  46978. // Keyboard
  46979. for (var index = 0; index < this._keys.length; index++) {
  46980. var keyCode = this._keys[index];
  46981. var speed = camera._computeLocalCameraSpeed();
  46982. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46983. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46984. }
  46985. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46986. camera._localDirection.copyFromFloats(0, 0, speed);
  46987. }
  46988. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46989. camera._localDirection.copyFromFloats(speed, 0, 0);
  46990. }
  46991. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46992. camera._localDirection.copyFromFloats(0, 0, -speed);
  46993. }
  46994. if (camera.getScene().useRightHandedSystem) {
  46995. camera._localDirection.z *= -1;
  46996. }
  46997. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46998. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46999. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47000. }
  47001. }
  47002. };
  47003. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47004. return "FreeCameraKeyboardMoveInput";
  47005. };
  47006. /** @hidden */
  47007. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47008. this._keys = [];
  47009. };
  47010. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47011. return "keyboard";
  47012. };
  47013. __decorate([
  47014. BABYLON.serialize()
  47015. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47016. __decorate([
  47017. BABYLON.serialize()
  47018. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47019. __decorate([
  47020. BABYLON.serialize()
  47021. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47022. __decorate([
  47023. BABYLON.serialize()
  47024. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47025. return FreeCameraKeyboardMoveInput;
  47026. }());
  47027. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47028. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47029. })(BABYLON || (BABYLON = {}));
  47030. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47031. var BABYLON;
  47032. (function (BABYLON) {
  47033. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47034. __extends(FreeCameraInputsManager, _super);
  47035. function FreeCameraInputsManager(camera) {
  47036. return _super.call(this, camera) || this;
  47037. }
  47038. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47039. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47040. return this;
  47041. };
  47042. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47043. if (touchEnabled === void 0) { touchEnabled = true; }
  47044. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47045. return this;
  47046. };
  47047. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47048. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47049. return this;
  47050. };
  47051. FreeCameraInputsManager.prototype.addTouch = function () {
  47052. this.add(new BABYLON.FreeCameraTouchInput());
  47053. return this;
  47054. };
  47055. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47056. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47057. return this;
  47058. };
  47059. return FreeCameraInputsManager;
  47060. }(BABYLON.CameraInputsManager));
  47061. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47062. })(BABYLON || (BABYLON = {}));
  47063. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47064. var BABYLON;
  47065. (function (BABYLON) {
  47066. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47067. // Forcing to use the Universal camera
  47068. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47069. });
  47070. var FreeCamera = /** @class */ (function (_super) {
  47071. __extends(FreeCamera, _super);
  47072. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47073. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47074. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47075. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47076. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47077. _this.checkCollisions = false;
  47078. _this.applyGravity = false;
  47079. _this._needMoveForGravity = false;
  47080. _this._oldPosition = BABYLON.Vector3.Zero();
  47081. _this._diffPosition = BABYLON.Vector3.Zero();
  47082. _this._newPosition = BABYLON.Vector3.Zero();
  47083. // Collisions
  47084. _this._collisionMask = -1;
  47085. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47086. if (collidedMesh === void 0) { collidedMesh = null; }
  47087. //TODO move this to the collision coordinator!
  47088. if (_this.getScene().workerCollisions)
  47089. newPosition.multiplyInPlace(_this._collider._radius);
  47090. var updatePosition = function (newPos) {
  47091. _this._newPosition.copyFrom(newPos);
  47092. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47093. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47094. _this.position.addInPlace(_this._diffPosition);
  47095. if (_this.onCollide && collidedMesh) {
  47096. _this.onCollide(collidedMesh);
  47097. }
  47098. }
  47099. };
  47100. updatePosition(newPosition);
  47101. };
  47102. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47103. _this.inputs.addKeyboard().addMouse();
  47104. return _this;
  47105. }
  47106. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47107. //-- begin properties for backward compatibility for inputs
  47108. /**
  47109. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47110. * Higher values reduce sensitivity.
  47111. */
  47112. get: function () {
  47113. var mouse = this.inputs.attached["mouse"];
  47114. if (mouse)
  47115. return mouse.angularSensibility;
  47116. return 0;
  47117. },
  47118. /**
  47119. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47120. * Higher values reduce sensitivity.
  47121. */
  47122. set: function (value) {
  47123. var mouse = this.inputs.attached["mouse"];
  47124. if (mouse)
  47125. mouse.angularSensibility = value;
  47126. },
  47127. enumerable: true,
  47128. configurable: true
  47129. });
  47130. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47131. get: function () {
  47132. var keyboard = this.inputs.attached["keyboard"];
  47133. if (keyboard)
  47134. return keyboard.keysUp;
  47135. return [];
  47136. },
  47137. set: function (value) {
  47138. var keyboard = this.inputs.attached["keyboard"];
  47139. if (keyboard)
  47140. keyboard.keysUp = value;
  47141. },
  47142. enumerable: true,
  47143. configurable: true
  47144. });
  47145. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47146. get: function () {
  47147. var keyboard = this.inputs.attached["keyboard"];
  47148. if (keyboard)
  47149. return keyboard.keysDown;
  47150. return [];
  47151. },
  47152. set: function (value) {
  47153. var keyboard = this.inputs.attached["keyboard"];
  47154. if (keyboard)
  47155. keyboard.keysDown = value;
  47156. },
  47157. enumerable: true,
  47158. configurable: true
  47159. });
  47160. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47161. get: function () {
  47162. var keyboard = this.inputs.attached["keyboard"];
  47163. if (keyboard)
  47164. return keyboard.keysLeft;
  47165. return [];
  47166. },
  47167. set: function (value) {
  47168. var keyboard = this.inputs.attached["keyboard"];
  47169. if (keyboard)
  47170. keyboard.keysLeft = value;
  47171. },
  47172. enumerable: true,
  47173. configurable: true
  47174. });
  47175. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47176. get: function () {
  47177. var keyboard = this.inputs.attached["keyboard"];
  47178. if (keyboard)
  47179. return keyboard.keysRight;
  47180. return [];
  47181. },
  47182. set: function (value) {
  47183. var keyboard = this.inputs.attached["keyboard"];
  47184. if (keyboard)
  47185. keyboard.keysRight = value;
  47186. },
  47187. enumerable: true,
  47188. configurable: true
  47189. });
  47190. // Controls
  47191. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47192. this.inputs.attachElement(element, noPreventDefault);
  47193. };
  47194. FreeCamera.prototype.detachControl = function (element) {
  47195. this.inputs.detachElement(element);
  47196. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47197. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47198. };
  47199. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47200. get: function () {
  47201. return this._collisionMask;
  47202. },
  47203. set: function (mask) {
  47204. this._collisionMask = !isNaN(mask) ? mask : -1;
  47205. },
  47206. enumerable: true,
  47207. configurable: true
  47208. });
  47209. /** @hidden */
  47210. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47211. var globalPosition;
  47212. if (this.parent) {
  47213. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47214. }
  47215. else {
  47216. globalPosition = this.position;
  47217. }
  47218. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47219. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47220. if (!this._collider) {
  47221. this._collider = new BABYLON.Collider();
  47222. }
  47223. this._collider._radius = this.ellipsoid;
  47224. this._collider.collisionMask = this._collisionMask;
  47225. //no need for clone, as long as gravity is not on.
  47226. var actualDisplacement = displacement;
  47227. //add gravity to the direction to prevent the dual-collision checking
  47228. if (this.applyGravity) {
  47229. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47230. actualDisplacement = displacement.add(this.getScene().gravity);
  47231. }
  47232. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47233. };
  47234. /** @hidden */
  47235. FreeCamera.prototype._checkInputs = function () {
  47236. if (!this._localDirection) {
  47237. this._localDirection = BABYLON.Vector3.Zero();
  47238. this._transformedDirection = BABYLON.Vector3.Zero();
  47239. }
  47240. this.inputs.checkInputs();
  47241. _super.prototype._checkInputs.call(this);
  47242. };
  47243. /** @hidden */
  47244. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47245. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47246. };
  47247. /** @hidden */
  47248. FreeCamera.prototype._updatePosition = function () {
  47249. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47250. this._collideWithWorld(this.cameraDirection);
  47251. }
  47252. else {
  47253. _super.prototype._updatePosition.call(this);
  47254. }
  47255. };
  47256. FreeCamera.prototype.dispose = function () {
  47257. this.inputs.clear();
  47258. _super.prototype.dispose.call(this);
  47259. };
  47260. FreeCamera.prototype.getClassName = function () {
  47261. return "FreeCamera";
  47262. };
  47263. __decorate([
  47264. BABYLON.serializeAsVector3()
  47265. ], FreeCamera.prototype, "ellipsoid", void 0);
  47266. __decorate([
  47267. BABYLON.serializeAsVector3()
  47268. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47269. __decorate([
  47270. BABYLON.serialize()
  47271. ], FreeCamera.prototype, "checkCollisions", void 0);
  47272. __decorate([
  47273. BABYLON.serialize()
  47274. ], FreeCamera.prototype, "applyGravity", void 0);
  47275. return FreeCamera;
  47276. }(BABYLON.TargetCamera));
  47277. BABYLON.FreeCamera = FreeCamera;
  47278. })(BABYLON || (BABYLON = {}));
  47279. //# sourceMappingURL=babylon.freeCamera.js.map
  47280. var BABYLON;
  47281. (function (BABYLON) {
  47282. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47283. function ArcRotateCameraKeyboardMoveInput() {
  47284. this._keys = new Array();
  47285. this.keysUp = [38];
  47286. this.keysDown = [40];
  47287. this.keysLeft = [37];
  47288. this.keysRight = [39];
  47289. this.keysReset = [220];
  47290. this.panningSensibility = 50.0;
  47291. this.zoomingSensibility = 25.0;
  47292. this.useAltToZoom = true;
  47293. }
  47294. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47295. var _this = this;
  47296. if (this._onCanvasBlurObserver) {
  47297. return;
  47298. }
  47299. this._scene = this.camera.getScene();
  47300. this._engine = this._scene.getEngine();
  47301. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47302. _this._keys = [];
  47303. });
  47304. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47305. var evt = info.event;
  47306. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47307. _this._ctrlPressed = evt.ctrlKey;
  47308. _this._altPressed = evt.altKey;
  47309. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47310. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47311. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47312. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47313. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47314. var index = _this._keys.indexOf(evt.keyCode);
  47315. if (index === -1) {
  47316. _this._keys.push(evt.keyCode);
  47317. }
  47318. if (evt.preventDefault) {
  47319. if (!noPreventDefault) {
  47320. evt.preventDefault();
  47321. }
  47322. }
  47323. }
  47324. }
  47325. else {
  47326. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47327. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47328. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47329. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47330. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47331. var index = _this._keys.indexOf(evt.keyCode);
  47332. if (index >= 0) {
  47333. _this._keys.splice(index, 1);
  47334. }
  47335. if (evt.preventDefault) {
  47336. if (!noPreventDefault) {
  47337. evt.preventDefault();
  47338. }
  47339. }
  47340. }
  47341. }
  47342. });
  47343. };
  47344. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47345. if (this._scene) {
  47346. if (this._onKeyboardObserver) {
  47347. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47348. }
  47349. if (this._onCanvasBlurObserver) {
  47350. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47351. }
  47352. this._onKeyboardObserver = null;
  47353. this._onCanvasBlurObserver = null;
  47354. }
  47355. this._keys = [];
  47356. };
  47357. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47358. if (this._onKeyboardObserver) {
  47359. var camera = this.camera;
  47360. for (var index = 0; index < this._keys.length; index++) {
  47361. var keyCode = this._keys[index];
  47362. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47363. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47364. camera.inertialPanningX -= 1 / this.panningSensibility;
  47365. }
  47366. else {
  47367. camera.inertialAlphaOffset -= 0.01;
  47368. }
  47369. }
  47370. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47371. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47372. camera.inertialPanningY += 1 / this.panningSensibility;
  47373. }
  47374. else if (this._altPressed && this.useAltToZoom) {
  47375. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47376. }
  47377. else {
  47378. camera.inertialBetaOffset -= 0.01;
  47379. }
  47380. }
  47381. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47382. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47383. camera.inertialPanningX += 1 / this.panningSensibility;
  47384. }
  47385. else {
  47386. camera.inertialAlphaOffset += 0.01;
  47387. }
  47388. }
  47389. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47390. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47391. camera.inertialPanningY -= 1 / this.panningSensibility;
  47392. }
  47393. else if (this._altPressed && this.useAltToZoom) {
  47394. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47395. }
  47396. else {
  47397. camera.inertialBetaOffset += 0.01;
  47398. }
  47399. }
  47400. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47401. camera.restoreState();
  47402. }
  47403. }
  47404. }
  47405. };
  47406. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47407. return "ArcRotateCameraKeyboardMoveInput";
  47408. };
  47409. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47410. return "keyboard";
  47411. };
  47412. __decorate([
  47413. BABYLON.serialize()
  47414. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47415. __decorate([
  47416. BABYLON.serialize()
  47417. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47418. __decorate([
  47419. BABYLON.serialize()
  47420. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47421. __decorate([
  47422. BABYLON.serialize()
  47423. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47424. __decorate([
  47425. BABYLON.serialize()
  47426. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47427. __decorate([
  47428. BABYLON.serialize()
  47429. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47430. __decorate([
  47431. BABYLON.serialize()
  47432. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47433. __decorate([
  47434. BABYLON.serialize()
  47435. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47436. return ArcRotateCameraKeyboardMoveInput;
  47437. }());
  47438. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47439. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47440. })(BABYLON || (BABYLON = {}));
  47441. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47442. var BABYLON;
  47443. (function (BABYLON) {
  47444. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47445. function ArcRotateCameraMouseWheelInput() {
  47446. this.wheelPrecision = 3.0;
  47447. /**
  47448. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47449. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47450. */
  47451. this.wheelDeltaPercentage = 0;
  47452. }
  47453. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47454. var _this = this;
  47455. this._wheel = function (p, s) {
  47456. //sanity check - this should be a PointerWheel event.
  47457. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47458. return;
  47459. var event = p.event;
  47460. var delta = 0;
  47461. if (event.wheelDelta) {
  47462. if (_this.wheelDeltaPercentage) {
  47463. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47464. if (event.wheelDelta > 0) {
  47465. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47466. }
  47467. else {
  47468. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47469. }
  47470. }
  47471. else {
  47472. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47473. }
  47474. }
  47475. else if (event.detail) {
  47476. delta = -event.detail / _this.wheelPrecision;
  47477. }
  47478. if (delta)
  47479. _this.camera.inertialRadiusOffset += delta;
  47480. if (event.preventDefault) {
  47481. if (!noPreventDefault) {
  47482. event.preventDefault();
  47483. }
  47484. }
  47485. };
  47486. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47487. };
  47488. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47489. if (this._observer && element) {
  47490. this.camera.getScene().onPointerObservable.remove(this._observer);
  47491. this._observer = null;
  47492. this._wheel = null;
  47493. }
  47494. };
  47495. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47496. return "ArcRotateCameraMouseWheelInput";
  47497. };
  47498. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47499. return "mousewheel";
  47500. };
  47501. __decorate([
  47502. BABYLON.serialize()
  47503. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47504. __decorate([
  47505. BABYLON.serialize()
  47506. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47507. return ArcRotateCameraMouseWheelInput;
  47508. }());
  47509. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47510. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47511. })(BABYLON || (BABYLON = {}));
  47512. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47513. var BABYLON;
  47514. (function (BABYLON) {
  47515. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47516. function ArcRotateCameraPointersInput() {
  47517. this.buttons = [0, 1, 2];
  47518. this.angularSensibilityX = 1000.0;
  47519. this.angularSensibilityY = 1000.0;
  47520. this.pinchPrecision = 12.0;
  47521. /**
  47522. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47523. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47524. */
  47525. this.pinchDeltaPercentage = 0;
  47526. this.panningSensibility = 1000.0;
  47527. this.multiTouchPanning = true;
  47528. this.multiTouchPanAndZoom = true;
  47529. this._isPanClick = false;
  47530. this.pinchInwards = true;
  47531. }
  47532. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47533. var _this = this;
  47534. var engine = this.camera.getEngine();
  47535. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47536. var pointA = null;
  47537. var pointB = null;
  47538. var previousPinchSquaredDistance = 0;
  47539. var initialDistance = 0;
  47540. var twoFingerActivityCount = 0;
  47541. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47542. this._pointerInput = function (p, s) {
  47543. var evt = p.event;
  47544. var isTouch = p.event.pointerType === "touch";
  47545. if (engine.isInVRExclusivePointerMode) {
  47546. return;
  47547. }
  47548. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47549. return;
  47550. }
  47551. var srcElement = (evt.srcElement || evt.target);
  47552. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47553. try {
  47554. srcElement.setPointerCapture(evt.pointerId);
  47555. }
  47556. catch (e) {
  47557. //Nothing to do with the error. Execution will continue.
  47558. }
  47559. // Manage panning with pan button click
  47560. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47561. // manage pointers
  47562. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47563. if (pointA === null) {
  47564. pointA = cacheSoloPointer;
  47565. }
  47566. else if (pointB === null) {
  47567. pointB = cacheSoloPointer;
  47568. }
  47569. if (!noPreventDefault) {
  47570. evt.preventDefault();
  47571. element.focus();
  47572. }
  47573. }
  47574. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47575. _this.camera.restoreState();
  47576. }
  47577. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47578. try {
  47579. srcElement.releasePointerCapture(evt.pointerId);
  47580. }
  47581. catch (e) {
  47582. //Nothing to do with the error.
  47583. }
  47584. cacheSoloPointer = null;
  47585. previousPinchSquaredDistance = 0;
  47586. previousMultiTouchPanPosition.isPaning = false;
  47587. previousMultiTouchPanPosition.isPinching = false;
  47588. twoFingerActivityCount = 0;
  47589. initialDistance = 0;
  47590. if (!isTouch) {
  47591. pointB = null; // Mouse and pen are mono pointer
  47592. }
  47593. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47594. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47595. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47596. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47597. if (engine._badOS) {
  47598. pointA = pointB = null;
  47599. }
  47600. else {
  47601. //only remove the impacted pointer in case of multitouch allowing on most
  47602. //platforms switching from rotate to zoom and pan seamlessly.
  47603. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47604. pointA = pointB;
  47605. pointB = null;
  47606. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47607. }
  47608. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47609. pointB = null;
  47610. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47611. }
  47612. else {
  47613. pointA = pointB = null;
  47614. }
  47615. }
  47616. if (!noPreventDefault) {
  47617. evt.preventDefault();
  47618. }
  47619. }
  47620. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47621. if (!noPreventDefault) {
  47622. evt.preventDefault();
  47623. }
  47624. // One button down
  47625. if (pointA && pointB === null && cacheSoloPointer) {
  47626. if (_this.panningSensibility !== 0 &&
  47627. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47628. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47629. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47630. }
  47631. else {
  47632. var offsetX = evt.clientX - cacheSoloPointer.x;
  47633. var offsetY = evt.clientY - cacheSoloPointer.y;
  47634. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47635. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47636. }
  47637. cacheSoloPointer.x = evt.clientX;
  47638. cacheSoloPointer.y = evt.clientY;
  47639. }
  47640. // Two buttons down: pinch/pan
  47641. else if (pointA && pointB) {
  47642. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47643. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47644. ed.x = evt.clientX;
  47645. ed.y = evt.clientY;
  47646. var direction = _this.pinchInwards ? 1 : -1;
  47647. var distX = pointA.x - pointB.x;
  47648. var distY = pointA.y - pointB.y;
  47649. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47650. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47651. if (previousPinchSquaredDistance === 0) {
  47652. initialDistance = pinchDistance;
  47653. previousPinchSquaredDistance = pinchSquaredDistance;
  47654. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47655. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47656. return;
  47657. }
  47658. if (_this.multiTouchPanAndZoom) {
  47659. if (_this.pinchDeltaPercentage) {
  47660. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47661. }
  47662. else {
  47663. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47664. (_this.pinchPrecision *
  47665. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47666. direction);
  47667. }
  47668. if (_this.panningSensibility !== 0) {
  47669. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47670. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47671. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47672. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47673. previousMultiTouchPanPosition.x = pointersCenterX;
  47674. previousMultiTouchPanPosition.y = pointersCenterY;
  47675. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47676. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47677. }
  47678. }
  47679. else {
  47680. twoFingerActivityCount++;
  47681. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47682. if (_this.pinchDeltaPercentage) {
  47683. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47684. }
  47685. else {
  47686. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47687. (_this.pinchPrecision *
  47688. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47689. direction);
  47690. }
  47691. previousMultiTouchPanPosition.isPaning = false;
  47692. previousMultiTouchPanPosition.isPinching = true;
  47693. }
  47694. else {
  47695. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47696. if (!previousMultiTouchPanPosition.isPaning) {
  47697. previousMultiTouchPanPosition.isPaning = true;
  47698. previousMultiTouchPanPosition.isPinching = false;
  47699. previousMultiTouchPanPosition.x = ed.x;
  47700. previousMultiTouchPanPosition.y = ed.y;
  47701. return;
  47702. }
  47703. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47704. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47705. }
  47706. }
  47707. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47708. previousMultiTouchPanPosition.x = ed.x;
  47709. previousMultiTouchPanPosition.y = ed.y;
  47710. }
  47711. }
  47712. previousPinchSquaredDistance = pinchSquaredDistance;
  47713. }
  47714. }
  47715. };
  47716. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47717. this._onContextMenu = function (evt) {
  47718. evt.preventDefault();
  47719. };
  47720. if (!this.camera._useCtrlForPanning) {
  47721. element.addEventListener("contextmenu", this._onContextMenu, false);
  47722. }
  47723. this._onLostFocus = function () {
  47724. //this._keys = [];
  47725. pointA = pointB = null;
  47726. previousPinchSquaredDistance = 0;
  47727. previousMultiTouchPanPosition.isPaning = false;
  47728. previousMultiTouchPanPosition.isPinching = false;
  47729. twoFingerActivityCount = 0;
  47730. cacheSoloPointer = null;
  47731. initialDistance = 0;
  47732. };
  47733. this._onMouseMove = function (evt) {
  47734. if (!engine.isPointerLock) {
  47735. return;
  47736. }
  47737. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47738. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47739. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47740. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47741. if (!noPreventDefault) {
  47742. evt.preventDefault();
  47743. }
  47744. };
  47745. this._onGestureStart = function (e) {
  47746. if (window.MSGesture === undefined) {
  47747. return;
  47748. }
  47749. if (!_this._MSGestureHandler) {
  47750. _this._MSGestureHandler = new MSGesture();
  47751. _this._MSGestureHandler.target = element;
  47752. }
  47753. _this._MSGestureHandler.addPointer(e.pointerId);
  47754. };
  47755. this._onGesture = function (e) {
  47756. _this.camera.radius *= e.scale;
  47757. if (e.preventDefault) {
  47758. if (!noPreventDefault) {
  47759. e.stopPropagation();
  47760. e.preventDefault();
  47761. }
  47762. }
  47763. };
  47764. element.addEventListener("mousemove", this._onMouseMove, false);
  47765. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47766. element.addEventListener("MSGestureChange", this._onGesture, false);
  47767. BABYLON.Tools.RegisterTopRootEvents([
  47768. { name: "blur", handler: this._onLostFocus }
  47769. ]);
  47770. };
  47771. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47772. if (this._onLostFocus) {
  47773. BABYLON.Tools.UnregisterTopRootEvents([
  47774. { name: "blur", handler: this._onLostFocus }
  47775. ]);
  47776. }
  47777. if (element && this._observer) {
  47778. this.camera.getScene().onPointerObservable.remove(this._observer);
  47779. this._observer = null;
  47780. if (this._onContextMenu) {
  47781. element.removeEventListener("contextmenu", this._onContextMenu);
  47782. }
  47783. if (this._onMouseMove) {
  47784. element.removeEventListener("mousemove", this._onMouseMove);
  47785. }
  47786. if (this._onGestureStart) {
  47787. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47788. }
  47789. if (this._onGesture) {
  47790. element.removeEventListener("MSGestureChange", this._onGesture);
  47791. }
  47792. this._isPanClick = false;
  47793. this.pinchInwards = true;
  47794. this._onMouseMove = null;
  47795. this._onGestureStart = null;
  47796. this._onGesture = null;
  47797. this._MSGestureHandler = null;
  47798. this._onLostFocus = null;
  47799. this._onContextMenu = null;
  47800. }
  47801. };
  47802. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47803. return "ArcRotateCameraPointersInput";
  47804. };
  47805. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47806. return "pointers";
  47807. };
  47808. __decorate([
  47809. BABYLON.serialize()
  47810. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47811. __decorate([
  47812. BABYLON.serialize()
  47813. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47814. __decorate([
  47815. BABYLON.serialize()
  47816. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47817. __decorate([
  47818. BABYLON.serialize()
  47819. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47820. __decorate([
  47821. BABYLON.serialize()
  47822. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47823. __decorate([
  47824. BABYLON.serialize()
  47825. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47826. __decorate([
  47827. BABYLON.serialize()
  47828. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47829. __decorate([
  47830. BABYLON.serialize()
  47831. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47832. return ArcRotateCameraPointersInput;
  47833. }());
  47834. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47835. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47836. })(BABYLON || (BABYLON = {}));
  47837. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47838. var BABYLON;
  47839. (function (BABYLON) {
  47840. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47841. __extends(ArcRotateCameraInputsManager, _super);
  47842. function ArcRotateCameraInputsManager(camera) {
  47843. return _super.call(this, camera) || this;
  47844. }
  47845. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47846. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47847. return this;
  47848. };
  47849. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47850. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47851. return this;
  47852. };
  47853. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47854. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47855. return this;
  47856. };
  47857. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47858. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47859. return this;
  47860. };
  47861. return ArcRotateCameraInputsManager;
  47862. }(BABYLON.CameraInputsManager));
  47863. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47864. })(BABYLON || (BABYLON = {}));
  47865. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47866. var BABYLON;
  47867. (function (BABYLON) {
  47868. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47869. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47870. });
  47871. var ArcRotateCamera = /** @class */ (function (_super) {
  47872. __extends(ArcRotateCamera, _super);
  47873. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47874. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47875. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47876. _this.inertialAlphaOffset = 0;
  47877. _this.inertialBetaOffset = 0;
  47878. _this.inertialRadiusOffset = 0;
  47879. _this.lowerAlphaLimit = null;
  47880. _this.upperAlphaLimit = null;
  47881. _this.lowerBetaLimit = 0.01;
  47882. _this.upperBetaLimit = Math.PI;
  47883. _this.lowerRadiusLimit = null;
  47884. _this.upperRadiusLimit = null;
  47885. _this.inertialPanningX = 0;
  47886. _this.inertialPanningY = 0;
  47887. _this.pinchToPanMaxDistance = 20;
  47888. _this.panningDistanceLimit = null;
  47889. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47890. _this.panningInertia = 0.9;
  47891. //-- end properties for backward compatibility for inputs
  47892. _this.zoomOnFactor = 1;
  47893. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47894. _this.allowUpsideDown = true;
  47895. /** @hidden */
  47896. _this._viewMatrix = new BABYLON.Matrix();
  47897. // Panning
  47898. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47899. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47900. _this.checkCollisions = false;
  47901. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47902. _this._previousPosition = BABYLON.Vector3.Zero();
  47903. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47904. _this._newPosition = BABYLON.Vector3.Zero();
  47905. _this._computationVector = BABYLON.Vector3.Zero();
  47906. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47907. if (collidedMesh === void 0) { collidedMesh = null; }
  47908. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47909. newPosition.multiplyInPlace(_this._collider._radius);
  47910. }
  47911. if (!collidedMesh) {
  47912. _this._previousPosition.copyFrom(_this.position);
  47913. }
  47914. else {
  47915. _this.setPosition(newPosition);
  47916. if (_this.onCollide) {
  47917. _this.onCollide(collidedMesh);
  47918. }
  47919. }
  47920. // Recompute because of constraints
  47921. var cosa = Math.cos(_this.alpha);
  47922. var sina = Math.sin(_this.alpha);
  47923. var cosb = Math.cos(_this.beta);
  47924. var sinb = Math.sin(_this.beta);
  47925. if (sinb === 0) {
  47926. sinb = 0.0001;
  47927. }
  47928. var target = _this._getTargetPosition();
  47929. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47930. target.addToRef(_this._computationVector, _this._newPosition);
  47931. _this.position.copyFrom(_this._newPosition);
  47932. var up = _this.upVector;
  47933. if (_this.allowUpsideDown && _this.beta < 0) {
  47934. up = up.clone();
  47935. up = up.negate();
  47936. }
  47937. _this._computeViewMatrix(_this.position, target, up);
  47938. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47939. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47940. _this._collisionTriggered = false;
  47941. };
  47942. _this._target = BABYLON.Vector3.Zero();
  47943. if (target) {
  47944. _this.setTarget(target);
  47945. }
  47946. _this.alpha = alpha;
  47947. _this.beta = beta;
  47948. _this.radius = radius;
  47949. _this.getViewMatrix();
  47950. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47951. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47952. return _this;
  47953. }
  47954. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47955. get: function () {
  47956. return this._target;
  47957. },
  47958. set: function (value) {
  47959. this.setTarget(value);
  47960. },
  47961. enumerable: true,
  47962. configurable: true
  47963. });
  47964. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47965. //-- begin properties for backward compatibility for inputs
  47966. get: function () {
  47967. var pointers = this.inputs.attached["pointers"];
  47968. if (pointers)
  47969. return pointers.angularSensibilityX;
  47970. return 0;
  47971. },
  47972. set: function (value) {
  47973. var pointers = this.inputs.attached["pointers"];
  47974. if (pointers) {
  47975. pointers.angularSensibilityX = value;
  47976. }
  47977. },
  47978. enumerable: true,
  47979. configurable: true
  47980. });
  47981. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47982. get: function () {
  47983. var pointers = this.inputs.attached["pointers"];
  47984. if (pointers)
  47985. return pointers.angularSensibilityY;
  47986. return 0;
  47987. },
  47988. set: function (value) {
  47989. var pointers = this.inputs.attached["pointers"];
  47990. if (pointers) {
  47991. pointers.angularSensibilityY = value;
  47992. }
  47993. },
  47994. enumerable: true,
  47995. configurable: true
  47996. });
  47997. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47998. get: function () {
  47999. var pointers = this.inputs.attached["pointers"];
  48000. if (pointers)
  48001. return pointers.pinchPrecision;
  48002. return 0;
  48003. },
  48004. set: function (value) {
  48005. var pointers = this.inputs.attached["pointers"];
  48006. if (pointers) {
  48007. pointers.pinchPrecision = value;
  48008. }
  48009. },
  48010. enumerable: true,
  48011. configurable: true
  48012. });
  48013. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48014. get: function () {
  48015. var pointers = this.inputs.attached["pointers"];
  48016. if (pointers)
  48017. return pointers.pinchDeltaPercentage;
  48018. return 0;
  48019. },
  48020. set: function (value) {
  48021. var pointers = this.inputs.attached["pointers"];
  48022. if (pointers) {
  48023. pointers.pinchDeltaPercentage = value;
  48024. }
  48025. },
  48026. enumerable: true,
  48027. configurable: true
  48028. });
  48029. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48030. get: function () {
  48031. var pointers = this.inputs.attached["pointers"];
  48032. if (pointers)
  48033. return pointers.panningSensibility;
  48034. return 0;
  48035. },
  48036. set: function (value) {
  48037. var pointers = this.inputs.attached["pointers"];
  48038. if (pointers) {
  48039. pointers.panningSensibility = value;
  48040. }
  48041. },
  48042. enumerable: true,
  48043. configurable: true
  48044. });
  48045. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48046. get: function () {
  48047. var keyboard = this.inputs.attached["keyboard"];
  48048. if (keyboard)
  48049. return keyboard.keysUp;
  48050. return [];
  48051. },
  48052. set: function (value) {
  48053. var keyboard = this.inputs.attached["keyboard"];
  48054. if (keyboard)
  48055. keyboard.keysUp = value;
  48056. },
  48057. enumerable: true,
  48058. configurable: true
  48059. });
  48060. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48061. get: function () {
  48062. var keyboard = this.inputs.attached["keyboard"];
  48063. if (keyboard)
  48064. return keyboard.keysDown;
  48065. return [];
  48066. },
  48067. set: function (value) {
  48068. var keyboard = this.inputs.attached["keyboard"];
  48069. if (keyboard)
  48070. keyboard.keysDown = value;
  48071. },
  48072. enumerable: true,
  48073. configurable: true
  48074. });
  48075. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48076. get: function () {
  48077. var keyboard = this.inputs.attached["keyboard"];
  48078. if (keyboard)
  48079. return keyboard.keysLeft;
  48080. return [];
  48081. },
  48082. set: function (value) {
  48083. var keyboard = this.inputs.attached["keyboard"];
  48084. if (keyboard)
  48085. keyboard.keysLeft = value;
  48086. },
  48087. enumerable: true,
  48088. configurable: true
  48089. });
  48090. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48091. get: function () {
  48092. var keyboard = this.inputs.attached["keyboard"];
  48093. if (keyboard)
  48094. return keyboard.keysRight;
  48095. return [];
  48096. },
  48097. set: function (value) {
  48098. var keyboard = this.inputs.attached["keyboard"];
  48099. if (keyboard)
  48100. keyboard.keysRight = value;
  48101. },
  48102. enumerable: true,
  48103. configurable: true
  48104. });
  48105. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48106. get: function () {
  48107. var mousewheel = this.inputs.attached["mousewheel"];
  48108. if (mousewheel)
  48109. return mousewheel.wheelPrecision;
  48110. return 0;
  48111. },
  48112. set: function (value) {
  48113. var mousewheel = this.inputs.attached["mousewheel"];
  48114. if (mousewheel)
  48115. mousewheel.wheelPrecision = value;
  48116. },
  48117. enumerable: true,
  48118. configurable: true
  48119. });
  48120. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48121. get: function () {
  48122. var mousewheel = this.inputs.attached["mousewheel"];
  48123. if (mousewheel)
  48124. return mousewheel.wheelDeltaPercentage;
  48125. return 0;
  48126. },
  48127. set: function (value) {
  48128. var mousewheel = this.inputs.attached["mousewheel"];
  48129. if (mousewheel)
  48130. mousewheel.wheelDeltaPercentage = value;
  48131. },
  48132. enumerable: true,
  48133. configurable: true
  48134. });
  48135. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48136. get: function () {
  48137. return this._bouncingBehavior;
  48138. },
  48139. enumerable: true,
  48140. configurable: true
  48141. });
  48142. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48143. get: function () {
  48144. return this._bouncingBehavior != null;
  48145. },
  48146. set: function (value) {
  48147. if (value === this.useBouncingBehavior) {
  48148. return;
  48149. }
  48150. if (value) {
  48151. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48152. this.addBehavior(this._bouncingBehavior);
  48153. }
  48154. else if (this._bouncingBehavior) {
  48155. this.removeBehavior(this._bouncingBehavior);
  48156. this._bouncingBehavior = null;
  48157. }
  48158. },
  48159. enumerable: true,
  48160. configurable: true
  48161. });
  48162. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48163. get: function () {
  48164. return this._framingBehavior;
  48165. },
  48166. enumerable: true,
  48167. configurable: true
  48168. });
  48169. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48170. get: function () {
  48171. return this._framingBehavior != null;
  48172. },
  48173. set: function (value) {
  48174. if (value === this.useFramingBehavior) {
  48175. return;
  48176. }
  48177. if (value) {
  48178. this._framingBehavior = new BABYLON.FramingBehavior();
  48179. this.addBehavior(this._framingBehavior);
  48180. }
  48181. else if (this._framingBehavior) {
  48182. this.removeBehavior(this._framingBehavior);
  48183. this._framingBehavior = null;
  48184. }
  48185. },
  48186. enumerable: true,
  48187. configurable: true
  48188. });
  48189. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48190. get: function () {
  48191. return this._autoRotationBehavior;
  48192. },
  48193. enumerable: true,
  48194. configurable: true
  48195. });
  48196. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48197. get: function () {
  48198. return this._autoRotationBehavior != null;
  48199. },
  48200. set: function (value) {
  48201. if (value === this.useAutoRotationBehavior) {
  48202. return;
  48203. }
  48204. if (value) {
  48205. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48206. this.addBehavior(this._autoRotationBehavior);
  48207. }
  48208. else if (this._autoRotationBehavior) {
  48209. this.removeBehavior(this._autoRotationBehavior);
  48210. this._autoRotationBehavior = null;
  48211. }
  48212. },
  48213. enumerable: true,
  48214. configurable: true
  48215. });
  48216. // Cache
  48217. /** @hidden */
  48218. ArcRotateCamera.prototype._initCache = function () {
  48219. _super.prototype._initCache.call(this);
  48220. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48221. this._cache.alpha = undefined;
  48222. this._cache.beta = undefined;
  48223. this._cache.radius = undefined;
  48224. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48225. };
  48226. /** @hidden */
  48227. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48228. if (!ignoreParentClass) {
  48229. _super.prototype._updateCache.call(this);
  48230. }
  48231. this._cache._target.copyFrom(this._getTargetPosition());
  48232. this._cache.alpha = this.alpha;
  48233. this._cache.beta = this.beta;
  48234. this._cache.radius = this.radius;
  48235. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48236. };
  48237. ArcRotateCamera.prototype._getTargetPosition = function () {
  48238. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48239. var pos = this._targetHost.getAbsolutePosition();
  48240. if (this._targetBoundingCenter) {
  48241. pos.addToRef(this._targetBoundingCenter, this._target);
  48242. }
  48243. else {
  48244. this._target.copyFrom(pos);
  48245. }
  48246. }
  48247. var lockedTargetPosition = this._getLockedTargetPosition();
  48248. if (lockedTargetPosition) {
  48249. return lockedTargetPosition;
  48250. }
  48251. return this._target;
  48252. };
  48253. ArcRotateCamera.prototype.storeState = function () {
  48254. this._storedAlpha = this.alpha;
  48255. this._storedBeta = this.beta;
  48256. this._storedRadius = this.radius;
  48257. this._storedTarget = this._getTargetPosition().clone();
  48258. return _super.prototype.storeState.call(this);
  48259. };
  48260. /**
  48261. * @hidden
  48262. * Restored camera state. You must call storeState() first
  48263. */
  48264. ArcRotateCamera.prototype._restoreStateValues = function () {
  48265. if (!_super.prototype._restoreStateValues.call(this)) {
  48266. return false;
  48267. }
  48268. this.alpha = this._storedAlpha;
  48269. this.beta = this._storedBeta;
  48270. this.radius = this._storedRadius;
  48271. this.setTarget(this._storedTarget.clone());
  48272. this.inertialAlphaOffset = 0;
  48273. this.inertialBetaOffset = 0;
  48274. this.inertialRadiusOffset = 0;
  48275. this.inertialPanningX = 0;
  48276. this.inertialPanningY = 0;
  48277. return true;
  48278. };
  48279. // Synchronized
  48280. /** @hidden */
  48281. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48282. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48283. return false;
  48284. return this._cache._target.equals(this._getTargetPosition())
  48285. && this._cache.alpha === this.alpha
  48286. && this._cache.beta === this.beta
  48287. && this._cache.radius === this.radius
  48288. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48289. };
  48290. // Methods
  48291. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48292. var _this = this;
  48293. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48294. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48295. this._useCtrlForPanning = useCtrlForPanning;
  48296. this._panningMouseButton = panningMouseButton;
  48297. this.inputs.attachElement(element, noPreventDefault);
  48298. this._reset = function () {
  48299. _this.inertialAlphaOffset = 0;
  48300. _this.inertialBetaOffset = 0;
  48301. _this.inertialRadiusOffset = 0;
  48302. _this.inertialPanningX = 0;
  48303. _this.inertialPanningY = 0;
  48304. };
  48305. };
  48306. ArcRotateCamera.prototype.detachControl = function (element) {
  48307. this.inputs.detachElement(element);
  48308. if (this._reset) {
  48309. this._reset();
  48310. }
  48311. };
  48312. /** @hidden */
  48313. ArcRotateCamera.prototype._checkInputs = function () {
  48314. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48315. if (this._collisionTriggered) {
  48316. return;
  48317. }
  48318. this.inputs.checkInputs();
  48319. // Inertia
  48320. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48321. var inertialAlphaOffset = this.inertialAlphaOffset;
  48322. if (this.beta <= 0)
  48323. inertialAlphaOffset *= -1;
  48324. if (this.getScene().useRightHandedSystem)
  48325. inertialAlphaOffset *= -1;
  48326. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48327. inertialAlphaOffset *= -1;
  48328. this.alpha += inertialAlphaOffset;
  48329. this.beta += this.inertialBetaOffset;
  48330. this.radius -= this.inertialRadiusOffset;
  48331. this.inertialAlphaOffset *= this.inertia;
  48332. this.inertialBetaOffset *= this.inertia;
  48333. this.inertialRadiusOffset *= this.inertia;
  48334. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48335. this.inertialAlphaOffset = 0;
  48336. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48337. this.inertialBetaOffset = 0;
  48338. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48339. this.inertialRadiusOffset = 0;
  48340. }
  48341. // Panning inertia
  48342. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48343. if (!this._localDirection) {
  48344. this._localDirection = BABYLON.Vector3.Zero();
  48345. this._transformedDirection = BABYLON.Vector3.Zero();
  48346. }
  48347. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48348. this._localDirection.multiplyInPlace(this.panningAxis);
  48349. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48350. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48351. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48352. if (!this.panningAxis.y) {
  48353. this._transformedDirection.y = 0;
  48354. }
  48355. if (!this._targetHost) {
  48356. if (this.panningDistanceLimit) {
  48357. this._transformedDirection.addInPlace(this._target);
  48358. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48359. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48360. this._target.copyFrom(this._transformedDirection);
  48361. }
  48362. }
  48363. else {
  48364. this._target.addInPlace(this._transformedDirection);
  48365. }
  48366. }
  48367. this.inertialPanningX *= this.panningInertia;
  48368. this.inertialPanningY *= this.panningInertia;
  48369. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48370. this.inertialPanningX = 0;
  48371. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48372. this.inertialPanningY = 0;
  48373. }
  48374. // Limits
  48375. this._checkLimits();
  48376. _super.prototype._checkInputs.call(this);
  48377. };
  48378. ArcRotateCamera.prototype._checkLimits = function () {
  48379. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48380. if (this.allowUpsideDown && this.beta > Math.PI) {
  48381. this.beta = this.beta - (2 * Math.PI);
  48382. }
  48383. }
  48384. else {
  48385. if (this.beta < this.lowerBetaLimit) {
  48386. this.beta = this.lowerBetaLimit;
  48387. }
  48388. }
  48389. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48390. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48391. this.beta = this.beta + (2 * Math.PI);
  48392. }
  48393. }
  48394. else {
  48395. if (this.beta > this.upperBetaLimit) {
  48396. this.beta = this.upperBetaLimit;
  48397. }
  48398. }
  48399. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48400. this.alpha = this.lowerAlphaLimit;
  48401. }
  48402. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48403. this.alpha = this.upperAlphaLimit;
  48404. }
  48405. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48406. this.radius = this.lowerRadiusLimit;
  48407. }
  48408. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48409. this.radius = this.upperRadiusLimit;
  48410. }
  48411. };
  48412. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48413. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48414. this.radius = this._computationVector.length();
  48415. if (this.radius === 0) {
  48416. this.radius = 0.0001; // Just to avoid division by zero
  48417. }
  48418. // Alpha
  48419. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48420. if (this._computationVector.z < 0) {
  48421. this.alpha = 2 * Math.PI - this.alpha;
  48422. }
  48423. // Beta
  48424. this.beta = Math.acos(this._computationVector.y / this.radius);
  48425. this._checkLimits();
  48426. };
  48427. ArcRotateCamera.prototype.setPosition = function (position) {
  48428. if (this.position.equals(position)) {
  48429. return;
  48430. }
  48431. this.position.copyFrom(position);
  48432. this.rebuildAnglesAndRadius();
  48433. };
  48434. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48435. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48436. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48437. if (target.getBoundingInfo) {
  48438. if (toBoundingCenter) {
  48439. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48440. }
  48441. else {
  48442. this._targetBoundingCenter = null;
  48443. }
  48444. this._targetHost = target;
  48445. this._target = this._getTargetPosition();
  48446. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48447. }
  48448. else {
  48449. var newTarget = target;
  48450. var currentTarget = this._getTargetPosition();
  48451. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48452. return;
  48453. }
  48454. this._targetHost = null;
  48455. this._target = newTarget;
  48456. this._targetBoundingCenter = null;
  48457. this.onMeshTargetChangedObservable.notifyObservers(null);
  48458. }
  48459. this.rebuildAnglesAndRadius();
  48460. };
  48461. /** @hidden */
  48462. ArcRotateCamera.prototype._getViewMatrix = function () {
  48463. // Compute
  48464. var cosa = Math.cos(this.alpha);
  48465. var sina = Math.sin(this.alpha);
  48466. var cosb = Math.cos(this.beta);
  48467. var sinb = Math.sin(this.beta);
  48468. if (sinb === 0) {
  48469. sinb = 0.0001;
  48470. }
  48471. var target = this._getTargetPosition();
  48472. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48473. target.addToRef(this._computationVector, this._newPosition);
  48474. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48475. if (!this._collider) {
  48476. this._collider = new BABYLON.Collider();
  48477. }
  48478. this._collider._radius = this.collisionRadius;
  48479. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48480. this._collisionTriggered = true;
  48481. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48482. }
  48483. else {
  48484. this.position.copyFrom(this._newPosition);
  48485. var up = this.upVector;
  48486. if (this.allowUpsideDown && sinb < 0) {
  48487. up = up.clone();
  48488. up = up.negate();
  48489. }
  48490. this._computeViewMatrix(this.position, target, up);
  48491. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48492. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48493. }
  48494. this._currentTarget = target;
  48495. return this._viewMatrix;
  48496. };
  48497. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48498. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48499. meshes = meshes || this.getScene().meshes;
  48500. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48501. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48502. this.radius = distance * this.zoomOnFactor;
  48503. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48504. };
  48505. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48506. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48507. var meshesOrMinMaxVector;
  48508. var distance;
  48509. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48510. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48511. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48512. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48513. }
  48514. else { //minMaxVector and distance
  48515. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48516. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48517. distance = minMaxVectorAndDistance.distance;
  48518. }
  48519. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48520. if (!doNotUpdateMaxZ) {
  48521. this.maxZ = distance * 2;
  48522. }
  48523. };
  48524. /**
  48525. * @override
  48526. * Override Camera.createRigCamera
  48527. */
  48528. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48529. var alphaShift = 0;
  48530. switch (this.cameraRigMode) {
  48531. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48532. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48533. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48534. case BABYLON.Camera.RIG_MODE_VR:
  48535. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48536. break;
  48537. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48538. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48539. break;
  48540. }
  48541. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48542. rigCam._cameraRigParams = {};
  48543. return rigCam;
  48544. };
  48545. /**
  48546. * @hidden
  48547. * @override
  48548. * Override Camera._updateRigCameras
  48549. */
  48550. ArcRotateCamera.prototype._updateRigCameras = function () {
  48551. var camLeft = this._rigCameras[0];
  48552. var camRight = this._rigCameras[1];
  48553. camLeft.beta = camRight.beta = this.beta;
  48554. camLeft.radius = camRight.radius = this.radius;
  48555. switch (this.cameraRigMode) {
  48556. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48559. case BABYLON.Camera.RIG_MODE_VR:
  48560. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48561. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48562. break;
  48563. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48564. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48565. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48566. break;
  48567. }
  48568. _super.prototype._updateRigCameras.call(this);
  48569. };
  48570. ArcRotateCamera.prototype.dispose = function () {
  48571. this.inputs.clear();
  48572. _super.prototype.dispose.call(this);
  48573. };
  48574. ArcRotateCamera.prototype.getClassName = function () {
  48575. return "ArcRotateCamera";
  48576. };
  48577. __decorate([
  48578. BABYLON.serialize()
  48579. ], ArcRotateCamera.prototype, "alpha", void 0);
  48580. __decorate([
  48581. BABYLON.serialize()
  48582. ], ArcRotateCamera.prototype, "beta", void 0);
  48583. __decorate([
  48584. BABYLON.serialize()
  48585. ], ArcRotateCamera.prototype, "radius", void 0);
  48586. __decorate([
  48587. BABYLON.serializeAsVector3("target")
  48588. ], ArcRotateCamera.prototype, "_target", void 0);
  48589. __decorate([
  48590. BABYLON.serialize()
  48591. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48592. __decorate([
  48593. BABYLON.serialize()
  48594. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48595. __decorate([
  48596. BABYLON.serialize()
  48597. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48598. __decorate([
  48599. BABYLON.serialize()
  48600. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48601. __decorate([
  48602. BABYLON.serialize()
  48603. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48604. __decorate([
  48605. BABYLON.serialize()
  48606. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48607. __decorate([
  48608. BABYLON.serialize()
  48609. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48610. __decorate([
  48611. BABYLON.serialize()
  48612. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48613. __decorate([
  48614. BABYLON.serialize()
  48615. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48616. __decorate([
  48617. BABYLON.serialize()
  48618. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48619. __decorate([
  48620. BABYLON.serialize()
  48621. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48622. __decorate([
  48623. BABYLON.serialize()
  48624. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48625. __decorate([
  48626. BABYLON.serialize()
  48627. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48628. __decorate([
  48629. BABYLON.serializeAsVector3()
  48630. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48631. __decorate([
  48632. BABYLON.serialize()
  48633. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48634. __decorate([
  48635. BABYLON.serialize()
  48636. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48637. __decorate([
  48638. BABYLON.serialize()
  48639. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48640. return ArcRotateCamera;
  48641. }(BABYLON.TargetCamera));
  48642. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48643. })(BABYLON || (BABYLON = {}));
  48644. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48645. var BABYLON;
  48646. (function (BABYLON) {
  48647. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48648. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48649. });
  48650. /**
  48651. * The HemisphericLight simulates the ambient environment light,
  48652. * so the passed direction is the light reflection direction, not the incoming direction.
  48653. */
  48654. var HemisphericLight = /** @class */ (function (_super) {
  48655. __extends(HemisphericLight, _super);
  48656. /**
  48657. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48658. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48659. * The HemisphericLight can't cast shadows.
  48660. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48661. * @param name The friendly name of the light
  48662. * @param direction The direction of the light reflection
  48663. * @param scene The scene the light belongs to
  48664. */
  48665. function HemisphericLight(name, direction, scene) {
  48666. var _this = _super.call(this, name, scene) || this;
  48667. /**
  48668. * The groundColor is the light in the opposite direction to the one specified during creation.
  48669. * 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.
  48670. */
  48671. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48672. _this.direction = direction || BABYLON.Vector3.Up();
  48673. return _this;
  48674. }
  48675. HemisphericLight.prototype._buildUniformLayout = function () {
  48676. this._uniformBuffer.addUniform("vLightData", 4);
  48677. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48678. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48679. this._uniformBuffer.addUniform("vLightGround", 3);
  48680. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48681. this._uniformBuffer.addUniform("depthValues", 2);
  48682. this._uniformBuffer.create();
  48683. };
  48684. /**
  48685. * Returns the string "HemisphericLight".
  48686. * @return The class name
  48687. */
  48688. HemisphericLight.prototype.getClassName = function () {
  48689. return "HemisphericLight";
  48690. };
  48691. /**
  48692. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48693. * Returns the updated direction.
  48694. * @param target The target the direction should point to
  48695. * @return The computed direction
  48696. */
  48697. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48698. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48699. return this.direction;
  48700. };
  48701. /**
  48702. * Returns the shadow generator associated to the light.
  48703. * @returns Always null for hemispheric lights because it does not support shadows.
  48704. */
  48705. HemisphericLight.prototype.getShadowGenerator = function () {
  48706. return null;
  48707. };
  48708. /**
  48709. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48710. * @param effect The effect to update
  48711. * @param lightIndex The index of the light in the effect to update
  48712. * @returns The hemispheric light
  48713. */
  48714. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48715. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48716. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48717. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48718. return this;
  48719. };
  48720. /**
  48721. * @hidden internal use only.
  48722. */
  48723. HemisphericLight.prototype._getWorldMatrix = function () {
  48724. if (!this._worldMatrix) {
  48725. this._worldMatrix = BABYLON.Matrix.Identity();
  48726. }
  48727. return this._worldMatrix;
  48728. };
  48729. /**
  48730. * Returns the integer 3.
  48731. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48732. */
  48733. HemisphericLight.prototype.getTypeID = function () {
  48734. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48735. };
  48736. /**
  48737. * Prepares the list of defines specific to the light type.
  48738. * @param defines the list of defines
  48739. * @param lightIndex defines the index of the light for the effect
  48740. */
  48741. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48742. defines["HEMILIGHT" + lightIndex] = true;
  48743. };
  48744. __decorate([
  48745. BABYLON.serializeAsColor3()
  48746. ], HemisphericLight.prototype, "groundColor", void 0);
  48747. __decorate([
  48748. BABYLON.serializeAsVector3()
  48749. ], HemisphericLight.prototype, "direction", void 0);
  48750. return HemisphericLight;
  48751. }(BABYLON.Light));
  48752. BABYLON.HemisphericLight = HemisphericLight;
  48753. })(BABYLON || (BABYLON = {}));
  48754. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48755. var BABYLON;
  48756. (function (BABYLON) {
  48757. /**
  48758. * Base implementation IShadowLight
  48759. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48760. */
  48761. var ShadowLight = /** @class */ (function (_super) {
  48762. __extends(ShadowLight, _super);
  48763. function ShadowLight() {
  48764. var _this = _super !== null && _super.apply(this, arguments) || this;
  48765. _this._needProjectionMatrixCompute = true;
  48766. return _this;
  48767. }
  48768. ShadowLight.prototype._setPosition = function (value) {
  48769. this._position = value;
  48770. };
  48771. Object.defineProperty(ShadowLight.prototype, "position", {
  48772. /**
  48773. * Sets the position the shadow will be casted from. Also use as the light position for both
  48774. * point and spot lights.
  48775. */
  48776. get: function () {
  48777. return this._position;
  48778. },
  48779. /**
  48780. * Sets the position the shadow will be casted from. Also use as the light position for both
  48781. * point and spot lights.
  48782. */
  48783. set: function (value) {
  48784. this._setPosition(value);
  48785. },
  48786. enumerable: true,
  48787. configurable: true
  48788. });
  48789. ShadowLight.prototype._setDirection = function (value) {
  48790. this._direction = value;
  48791. };
  48792. Object.defineProperty(ShadowLight.prototype, "direction", {
  48793. /**
  48794. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48795. * Also use as the light direction on spot and directional lights.
  48796. */
  48797. get: function () {
  48798. return this._direction;
  48799. },
  48800. /**
  48801. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48802. * Also use as the light direction on spot and directional lights.
  48803. */
  48804. set: function (value) {
  48805. this._setDirection(value);
  48806. },
  48807. enumerable: true,
  48808. configurable: true
  48809. });
  48810. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48811. /**
  48812. * Gets the shadow projection clipping minimum z value.
  48813. */
  48814. get: function () {
  48815. return this._shadowMinZ;
  48816. },
  48817. /**
  48818. * Sets the shadow projection clipping minimum z value.
  48819. */
  48820. set: function (value) {
  48821. this._shadowMinZ = value;
  48822. this.forceProjectionMatrixCompute();
  48823. },
  48824. enumerable: true,
  48825. configurable: true
  48826. });
  48827. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48828. /**
  48829. * Sets the shadow projection clipping maximum z value.
  48830. */
  48831. get: function () {
  48832. return this._shadowMaxZ;
  48833. },
  48834. /**
  48835. * Gets the shadow projection clipping maximum z value.
  48836. */
  48837. set: function (value) {
  48838. this._shadowMaxZ = value;
  48839. this.forceProjectionMatrixCompute();
  48840. },
  48841. enumerable: true,
  48842. configurable: true
  48843. });
  48844. /**
  48845. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48846. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48847. */
  48848. ShadowLight.prototype.computeTransformedInformation = function () {
  48849. if (this.parent && this.parent.getWorldMatrix) {
  48850. if (!this.transformedPosition) {
  48851. this.transformedPosition = BABYLON.Vector3.Zero();
  48852. }
  48853. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48854. // In case the direction is present.
  48855. if (this.direction) {
  48856. if (!this.transformedDirection) {
  48857. this.transformedDirection = BABYLON.Vector3.Zero();
  48858. }
  48859. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48860. }
  48861. return true;
  48862. }
  48863. return false;
  48864. };
  48865. /**
  48866. * Return the depth scale used for the shadow map.
  48867. * @returns the depth scale.
  48868. */
  48869. ShadowLight.prototype.getDepthScale = function () {
  48870. return 50.0;
  48871. };
  48872. /**
  48873. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48874. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48875. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48876. */
  48877. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48878. return this.transformedDirection ? this.transformedDirection : this.direction;
  48879. };
  48880. /**
  48881. * Returns the ShadowLight absolute position in the World.
  48882. * @returns the position vector in world space
  48883. */
  48884. ShadowLight.prototype.getAbsolutePosition = function () {
  48885. return this.transformedPosition ? this.transformedPosition : this.position;
  48886. };
  48887. /**
  48888. * Sets the ShadowLight direction toward the passed target.
  48889. * @param target The point tot target in local space
  48890. * @returns the updated ShadowLight direction
  48891. */
  48892. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48893. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48894. return this.direction;
  48895. };
  48896. /**
  48897. * Returns the light rotation in euler definition.
  48898. * @returns the x y z rotation in local space.
  48899. */
  48900. ShadowLight.prototype.getRotation = function () {
  48901. this.direction.normalize();
  48902. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48903. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48904. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48905. };
  48906. /**
  48907. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48908. * @returns true if a cube texture needs to be use
  48909. */
  48910. ShadowLight.prototype.needCube = function () {
  48911. return false;
  48912. };
  48913. /**
  48914. * Detects if the projection matrix requires to be recomputed this frame.
  48915. * @returns true if it requires to be recomputed otherwise, false.
  48916. */
  48917. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48918. return this._needProjectionMatrixCompute;
  48919. };
  48920. /**
  48921. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48922. */
  48923. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48924. this._needProjectionMatrixCompute = true;
  48925. };
  48926. /**
  48927. * Get the world matrix of the sahdow lights.
  48928. * @hidden Internal Use Only
  48929. */
  48930. ShadowLight.prototype._getWorldMatrix = function () {
  48931. if (!this._worldMatrix) {
  48932. this._worldMatrix = BABYLON.Matrix.Identity();
  48933. }
  48934. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48935. return this._worldMatrix;
  48936. };
  48937. /**
  48938. * Gets the minZ used for shadow according to both the scene and the light.
  48939. * @param activeCamera The camera we are returning the min for
  48940. * @returns the depth min z
  48941. */
  48942. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48943. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48944. };
  48945. /**
  48946. * Gets the maxZ used for shadow according to both the scene and the light.
  48947. * @param activeCamera The camera we are returning the max for
  48948. * @returns the depth max z
  48949. */
  48950. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48951. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48952. };
  48953. /**
  48954. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48955. * @param matrix The materix to updated with the projection information
  48956. * @param viewMatrix The transform matrix of the light
  48957. * @param renderList The list of mesh to render in the map
  48958. * @returns The current light
  48959. */
  48960. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48961. if (this.customProjectionMatrixBuilder) {
  48962. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48963. }
  48964. else {
  48965. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48966. }
  48967. return this;
  48968. };
  48969. __decorate([
  48970. BABYLON.serializeAsVector3()
  48971. ], ShadowLight.prototype, "position", null);
  48972. __decorate([
  48973. BABYLON.serializeAsVector3()
  48974. ], ShadowLight.prototype, "direction", null);
  48975. __decorate([
  48976. BABYLON.serialize()
  48977. ], ShadowLight.prototype, "shadowMinZ", null);
  48978. __decorate([
  48979. BABYLON.serialize()
  48980. ], ShadowLight.prototype, "shadowMaxZ", null);
  48981. return ShadowLight;
  48982. }(BABYLON.Light));
  48983. BABYLON.ShadowLight = ShadowLight;
  48984. })(BABYLON || (BABYLON = {}));
  48985. //# sourceMappingURL=babylon.shadowLight.js.map
  48986. var BABYLON;
  48987. (function (BABYLON) {
  48988. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48989. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48990. });
  48991. /**
  48992. * A point light is a light defined by an unique point in world space.
  48993. * The light is emitted in every direction from this point.
  48994. * A good example of a point light is a standard light bulb.
  48995. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48996. */
  48997. var PointLight = /** @class */ (function (_super) {
  48998. __extends(PointLight, _super);
  48999. /**
  49000. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49001. * A PointLight emits the light in every direction.
  49002. * It can cast shadows.
  49003. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49004. * ```javascript
  49005. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49006. * ```
  49007. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49008. * @param name The light friendly name
  49009. * @param position The position of the point light in the scene
  49010. * @param scene The scene the lights belongs to
  49011. */
  49012. function PointLight(name, position, scene) {
  49013. var _this = _super.call(this, name, scene) || this;
  49014. _this._shadowAngle = Math.PI / 2;
  49015. _this.position = position;
  49016. return _this;
  49017. }
  49018. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49019. /**
  49020. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49021. * This specifies what angle the shadow will use to be created.
  49022. *
  49023. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49024. */
  49025. get: function () {
  49026. return this._shadowAngle;
  49027. },
  49028. /**
  49029. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49030. * This specifies what angle the shadow will use to be created.
  49031. *
  49032. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49033. */
  49034. set: function (value) {
  49035. this._shadowAngle = value;
  49036. this.forceProjectionMatrixCompute();
  49037. },
  49038. enumerable: true,
  49039. configurable: true
  49040. });
  49041. Object.defineProperty(PointLight.prototype, "direction", {
  49042. /**
  49043. * Gets the direction if it has been set.
  49044. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49045. */
  49046. get: function () {
  49047. return this._direction;
  49048. },
  49049. /**
  49050. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49051. */
  49052. set: function (value) {
  49053. var previousNeedCube = this.needCube();
  49054. this._direction = value;
  49055. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49056. this._shadowGenerator.recreateShadowMap();
  49057. }
  49058. },
  49059. enumerable: true,
  49060. configurable: true
  49061. });
  49062. /**
  49063. * Returns the string "PointLight"
  49064. * @returns the class name
  49065. */
  49066. PointLight.prototype.getClassName = function () {
  49067. return "PointLight";
  49068. };
  49069. /**
  49070. * Returns the integer 0.
  49071. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49072. */
  49073. PointLight.prototype.getTypeID = function () {
  49074. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49075. };
  49076. /**
  49077. * Specifies wether or not the shadowmap should be a cube texture.
  49078. * @returns true if the shadowmap needs to be a cube texture.
  49079. */
  49080. PointLight.prototype.needCube = function () {
  49081. return !this.direction;
  49082. };
  49083. /**
  49084. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49085. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49086. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49087. */
  49088. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49089. if (this.direction) {
  49090. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49091. }
  49092. else {
  49093. switch (faceIndex) {
  49094. case 0:
  49095. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49096. case 1:
  49097. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49098. case 2:
  49099. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49100. case 3:
  49101. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49102. case 4:
  49103. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49104. case 5:
  49105. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49106. }
  49107. }
  49108. return BABYLON.Vector3.Zero();
  49109. };
  49110. /**
  49111. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49112. * - fov = PI / 2
  49113. * - aspect ratio : 1.0
  49114. * - z-near and far equal to the active camera minZ and maxZ.
  49115. * Returns the PointLight.
  49116. */
  49117. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49118. var activeCamera = this.getScene().activeCamera;
  49119. if (!activeCamera) {
  49120. return;
  49121. }
  49122. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49123. };
  49124. PointLight.prototype._buildUniformLayout = function () {
  49125. this._uniformBuffer.addUniform("vLightData", 4);
  49126. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49127. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49128. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49129. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49130. this._uniformBuffer.addUniform("depthValues", 2);
  49131. this._uniformBuffer.create();
  49132. };
  49133. /**
  49134. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49135. * @param effect The effect to update
  49136. * @param lightIndex The index of the light in the effect to update
  49137. * @returns The point light
  49138. */
  49139. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49140. if (this.computeTransformedInformation()) {
  49141. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49142. }
  49143. else {
  49144. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49145. }
  49146. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49147. return this;
  49148. };
  49149. /**
  49150. * Prepares the list of defines specific to the light type.
  49151. * @param defines the list of defines
  49152. * @param lightIndex defines the index of the light for the effect
  49153. */
  49154. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49155. defines["POINTLIGHT" + lightIndex] = true;
  49156. };
  49157. __decorate([
  49158. BABYLON.serialize()
  49159. ], PointLight.prototype, "shadowAngle", null);
  49160. return PointLight;
  49161. }(BABYLON.ShadowLight));
  49162. BABYLON.PointLight = PointLight;
  49163. })(BABYLON || (BABYLON = {}));
  49164. //# sourceMappingURL=babylon.pointLight.js.map
  49165. var BABYLON;
  49166. (function (BABYLON) {
  49167. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49168. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49169. });
  49170. /**
  49171. * A directional light is defined by a direction (what a surprise!).
  49172. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49173. * 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.
  49174. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49175. */
  49176. var DirectionalLight = /** @class */ (function (_super) {
  49177. __extends(DirectionalLight, _super);
  49178. /**
  49179. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49180. * The directional light is emitted from everywhere in the given direction.
  49181. * It can cast shawdows.
  49182. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49183. * @param name The friendly name of the light
  49184. * @param direction The direction of the light
  49185. * @param scene The scene the light belongs to
  49186. */
  49187. function DirectionalLight(name, direction, scene) {
  49188. var _this = _super.call(this, name, scene) || this;
  49189. _this._shadowFrustumSize = 0;
  49190. _this._shadowOrthoScale = 0.1;
  49191. /**
  49192. * Automatically compute the projection matrix to best fit (including all the casters)
  49193. * on each frame.
  49194. */
  49195. _this.autoUpdateExtends = true;
  49196. // Cache
  49197. _this._orthoLeft = Number.MAX_VALUE;
  49198. _this._orthoRight = Number.MIN_VALUE;
  49199. _this._orthoTop = Number.MIN_VALUE;
  49200. _this._orthoBottom = Number.MAX_VALUE;
  49201. _this.position = direction.scale(-1.0);
  49202. _this.direction = direction;
  49203. return _this;
  49204. }
  49205. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49206. /**
  49207. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49208. */
  49209. get: function () {
  49210. return this._shadowFrustumSize;
  49211. },
  49212. /**
  49213. * Specifies a fix frustum size for the shadow generation.
  49214. */
  49215. set: function (value) {
  49216. this._shadowFrustumSize = value;
  49217. this.forceProjectionMatrixCompute();
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49223. /**
  49224. * Gets the shadow projection scale against the optimal computed one.
  49225. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49226. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49227. */
  49228. get: function () {
  49229. return this._shadowOrthoScale;
  49230. },
  49231. /**
  49232. * Sets the shadow projection scale against the optimal computed one.
  49233. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49234. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49235. */
  49236. set: function (value) {
  49237. this._shadowOrthoScale = value;
  49238. this.forceProjectionMatrixCompute();
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. /**
  49244. * Returns the string "DirectionalLight".
  49245. * @return The class name
  49246. */
  49247. DirectionalLight.prototype.getClassName = function () {
  49248. return "DirectionalLight";
  49249. };
  49250. /**
  49251. * Returns the integer 1.
  49252. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49253. */
  49254. DirectionalLight.prototype.getTypeID = function () {
  49255. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49256. };
  49257. /**
  49258. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49259. * Returns the DirectionalLight Shadow projection matrix.
  49260. */
  49261. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49262. if (this.shadowFrustumSize > 0) {
  49263. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49264. }
  49265. else {
  49266. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49267. }
  49268. };
  49269. /**
  49270. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49271. * Returns the DirectionalLight Shadow projection matrix.
  49272. */
  49273. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49274. var activeCamera = this.getScene().activeCamera;
  49275. if (!activeCamera) {
  49276. return;
  49277. }
  49278. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49279. };
  49280. /**
  49281. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49282. * Returns the DirectionalLight Shadow projection matrix.
  49283. */
  49284. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49285. var activeCamera = this.getScene().activeCamera;
  49286. if (!activeCamera) {
  49287. return;
  49288. }
  49289. // Check extends
  49290. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49291. var tempVector3 = BABYLON.Vector3.Zero();
  49292. this._orthoLeft = Number.MAX_VALUE;
  49293. this._orthoRight = Number.MIN_VALUE;
  49294. this._orthoTop = Number.MIN_VALUE;
  49295. this._orthoBottom = Number.MAX_VALUE;
  49296. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49297. var mesh = renderList[meshIndex];
  49298. if (!mesh) {
  49299. continue;
  49300. }
  49301. var boundingInfo = mesh.getBoundingInfo();
  49302. var boundingBox = boundingInfo.boundingBox;
  49303. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49304. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49305. if (tempVector3.x < this._orthoLeft)
  49306. this._orthoLeft = tempVector3.x;
  49307. if (tempVector3.y < this._orthoBottom)
  49308. this._orthoBottom = tempVector3.y;
  49309. if (tempVector3.x > this._orthoRight)
  49310. this._orthoRight = tempVector3.x;
  49311. if (tempVector3.y > this._orthoTop)
  49312. this._orthoTop = tempVector3.y;
  49313. }
  49314. }
  49315. }
  49316. var xOffset = this._orthoRight - this._orthoLeft;
  49317. var yOffset = this._orthoTop - this._orthoBottom;
  49318. 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);
  49319. };
  49320. DirectionalLight.prototype._buildUniformLayout = function () {
  49321. this._uniformBuffer.addUniform("vLightData", 4);
  49322. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49323. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49324. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49325. this._uniformBuffer.addUniform("depthValues", 2);
  49326. this._uniformBuffer.create();
  49327. };
  49328. /**
  49329. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49330. * @param effect The effect to update
  49331. * @param lightIndex The index of the light in the effect to update
  49332. * @returns The directional light
  49333. */
  49334. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49335. if (this.computeTransformedInformation()) {
  49336. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49337. return this;
  49338. }
  49339. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49340. return this;
  49341. };
  49342. /**
  49343. * Gets the minZ used for shadow according to both the scene and the light.
  49344. *
  49345. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49346. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49347. * @param activeCamera The camera we are returning the min for
  49348. * @returns the depth min z
  49349. */
  49350. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49351. return 1;
  49352. };
  49353. /**
  49354. * Gets the maxZ used for shadow according to both the scene and the light.
  49355. *
  49356. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49357. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49358. * @param activeCamera The camera we are returning the max for
  49359. * @returns the depth max z
  49360. */
  49361. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49362. return 1;
  49363. };
  49364. /**
  49365. * Prepares the list of defines specific to the light type.
  49366. * @param defines the list of defines
  49367. * @param lightIndex defines the index of the light for the effect
  49368. */
  49369. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49370. defines["DIRLIGHT" + lightIndex] = true;
  49371. };
  49372. __decorate([
  49373. BABYLON.serialize()
  49374. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49375. __decorate([
  49376. BABYLON.serialize()
  49377. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49378. __decorate([
  49379. BABYLON.serialize()
  49380. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49381. return DirectionalLight;
  49382. }(BABYLON.ShadowLight));
  49383. BABYLON.DirectionalLight = DirectionalLight;
  49384. })(BABYLON || (BABYLON = {}));
  49385. //# sourceMappingURL=babylon.directionalLight.js.map
  49386. var BABYLON;
  49387. (function (BABYLON) {
  49388. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49389. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49390. });
  49391. /**
  49392. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49393. * These values define a cone of light starting from the position, emitting toward the direction.
  49394. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49395. * and the exponent defines the speed of the decay of the light with distance (reach).
  49396. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49397. */
  49398. var SpotLight = /** @class */ (function (_super) {
  49399. __extends(SpotLight, _super);
  49400. /**
  49401. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49402. * It can cast shadows.
  49403. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49404. * @param name The light friendly name
  49405. * @param position The position of the spot light in the scene
  49406. * @param direction The direction of the light in the scene
  49407. * @param angle The cone angle of the light in Radians
  49408. * @param exponent The light decay speed with the distance from the emission spot
  49409. * @param scene The scene the lights belongs to
  49410. */
  49411. function SpotLight(name, position, direction, angle, exponent, scene) {
  49412. var _this = _super.call(this, name, scene) || this;
  49413. _this._innerAngle = 0;
  49414. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49415. _this._projectionTextureLightNear = 1e-6;
  49416. _this._projectionTextureLightFar = 1000.0;
  49417. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49418. _this._projectionTextureViewLightDirty = true;
  49419. _this._projectionTextureProjectionLightDirty = true;
  49420. _this._projectionTextureDirty = true;
  49421. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49422. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49423. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49424. _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);
  49425. _this.position = position;
  49426. _this.direction = direction;
  49427. _this.angle = angle;
  49428. _this.exponent = exponent;
  49429. return _this;
  49430. }
  49431. Object.defineProperty(SpotLight.prototype, "angle", {
  49432. /**
  49433. * Gets the cone angle of the spot light in Radians.
  49434. */
  49435. get: function () {
  49436. return this._angle;
  49437. },
  49438. /**
  49439. * Sets the cone angle of the spot light in Radians.
  49440. */
  49441. set: function (value) {
  49442. this._angle = value;
  49443. this._cosHalfAngle = Math.cos(value * 0.5);
  49444. this._projectionTextureProjectionLightDirty = true;
  49445. this.forceProjectionMatrixCompute();
  49446. this._computeAngleValues();
  49447. },
  49448. enumerable: true,
  49449. configurable: true
  49450. });
  49451. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49452. /**
  49453. * Only used in gltf falloff mode, this defines the angle where
  49454. * the directional falloff will start before cutting at angle which could be seen
  49455. * as outer angle.
  49456. */
  49457. get: function () {
  49458. return this._angle;
  49459. },
  49460. /**
  49461. * Only used in gltf falloff mode, this defines the angle where
  49462. * the directional falloff will start before cutting at angle which could be seen
  49463. * as outer angle.
  49464. */
  49465. set: function (value) {
  49466. this._innerAngle = value;
  49467. this._computeAngleValues();
  49468. },
  49469. enumerable: true,
  49470. configurable: true
  49471. });
  49472. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49473. /**
  49474. * Allows scaling the angle of the light for shadow generation only.
  49475. */
  49476. get: function () {
  49477. return this._shadowAngleScale;
  49478. },
  49479. /**
  49480. * Allows scaling the angle of the light for shadow generation only.
  49481. */
  49482. set: function (value) {
  49483. this._shadowAngleScale = value;
  49484. this.forceProjectionMatrixCompute();
  49485. },
  49486. enumerable: true,
  49487. configurable: true
  49488. });
  49489. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49490. /**
  49491. * Allows reading the projecton texture
  49492. */
  49493. get: function () {
  49494. return this._projectionTextureMatrix;
  49495. },
  49496. enumerable: true,
  49497. configurable: true
  49498. });
  49499. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49500. /**
  49501. * Gets the near clip of the Spotlight for texture projection.
  49502. */
  49503. get: function () {
  49504. return this._projectionTextureLightNear;
  49505. },
  49506. /**
  49507. * Sets the near clip of the Spotlight for texture projection.
  49508. */
  49509. set: function (value) {
  49510. this._projectionTextureLightNear = value;
  49511. this._projectionTextureProjectionLightDirty = true;
  49512. },
  49513. enumerable: true,
  49514. configurable: true
  49515. });
  49516. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49517. /**
  49518. * Gets the far clip of the Spotlight for texture projection.
  49519. */
  49520. get: function () {
  49521. return this._projectionTextureLightFar;
  49522. },
  49523. /**
  49524. * Sets the far clip of the Spotlight for texture projection.
  49525. */
  49526. set: function (value) {
  49527. this._projectionTextureLightFar = value;
  49528. this._projectionTextureProjectionLightDirty = true;
  49529. },
  49530. enumerable: true,
  49531. configurable: true
  49532. });
  49533. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49534. /**
  49535. * Gets the Up vector of the Spotlight for texture projection.
  49536. */
  49537. get: function () {
  49538. return this._projectionTextureUpDirection;
  49539. },
  49540. /**
  49541. * Sets the Up vector of the Spotlight for texture projection.
  49542. */
  49543. set: function (value) {
  49544. this._projectionTextureUpDirection = value;
  49545. this._projectionTextureProjectionLightDirty = true;
  49546. },
  49547. enumerable: true,
  49548. configurable: true
  49549. });
  49550. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49551. /**
  49552. * Gets the projection texture of the light.
  49553. */
  49554. get: function () {
  49555. return this._projectionTexture;
  49556. },
  49557. /**
  49558. * Sets the projection texture of the light.
  49559. */
  49560. set: function (value) {
  49561. this._projectionTexture = value;
  49562. this._projectionTextureDirty = true;
  49563. },
  49564. enumerable: true,
  49565. configurable: true
  49566. });
  49567. /**
  49568. * Returns the string "SpotLight".
  49569. * @returns the class name
  49570. */
  49571. SpotLight.prototype.getClassName = function () {
  49572. return "SpotLight";
  49573. };
  49574. /**
  49575. * Returns the integer 2.
  49576. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49577. */
  49578. SpotLight.prototype.getTypeID = function () {
  49579. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49580. };
  49581. /**
  49582. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49583. */
  49584. SpotLight.prototype._setDirection = function (value) {
  49585. _super.prototype._setDirection.call(this, value);
  49586. this._projectionTextureViewLightDirty = true;
  49587. };
  49588. /**
  49589. * Overrides the position setter to recompute the projection texture view light Matrix.
  49590. */
  49591. SpotLight.prototype._setPosition = function (value) {
  49592. _super.prototype._setPosition.call(this, value);
  49593. this._projectionTextureViewLightDirty = true;
  49594. };
  49595. /**
  49596. * 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.
  49597. * Returns the SpotLight.
  49598. */
  49599. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49600. var activeCamera = this.getScene().activeCamera;
  49601. if (!activeCamera) {
  49602. return;
  49603. }
  49604. this._shadowAngleScale = this._shadowAngleScale || 1;
  49605. var angle = this._shadowAngleScale * this._angle;
  49606. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49607. };
  49608. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49609. this._projectionTextureViewLightDirty = false;
  49610. this._projectionTextureDirty = true;
  49611. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49612. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49613. };
  49614. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49615. this._projectionTextureProjectionLightDirty = false;
  49616. this._projectionTextureDirty = true;
  49617. var light_far = this.projectionTextureLightFar;
  49618. var light_near = this.projectionTextureLightNear;
  49619. var P = light_far / (light_far - light_near);
  49620. var Q = -P * light_near;
  49621. var S = 1.0 / Math.tan(this._angle / 2.0);
  49622. var A = 1.0;
  49623. 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);
  49624. };
  49625. /**
  49626. * Main function for light texture projection matrix computing.
  49627. */
  49628. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49629. this._projectionTextureDirty = false;
  49630. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49631. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49632. };
  49633. SpotLight.prototype._buildUniformLayout = function () {
  49634. this._uniformBuffer.addUniform("vLightData", 4);
  49635. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49636. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49637. this._uniformBuffer.addUniform("vLightDirection", 3);
  49638. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49639. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49640. this._uniformBuffer.addUniform("depthValues", 2);
  49641. this._uniformBuffer.create();
  49642. };
  49643. SpotLight.prototype._computeAngleValues = function () {
  49644. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49645. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49646. };
  49647. /**
  49648. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49649. * @param effect The effect to update
  49650. * @param lightIndex The index of the light in the effect to update
  49651. * @returns The spot light
  49652. */
  49653. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49654. var normalizeDirection;
  49655. if (this.computeTransformedInformation()) {
  49656. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49657. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49658. }
  49659. else {
  49660. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49661. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49662. }
  49663. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49664. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49665. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49666. if (this._projectionTextureViewLightDirty) {
  49667. this._computeProjectionTextureViewLightMatrix();
  49668. }
  49669. if (this._projectionTextureProjectionLightDirty) {
  49670. this._computeProjectionTextureProjectionLightMatrix();
  49671. }
  49672. if (this._projectionTextureDirty) {
  49673. this._computeProjectionTextureMatrix();
  49674. }
  49675. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49676. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49677. }
  49678. return this;
  49679. };
  49680. /**
  49681. * Disposes the light and the associated resources.
  49682. */
  49683. SpotLight.prototype.dispose = function () {
  49684. _super.prototype.dispose.call(this);
  49685. if (this._projectionTexture) {
  49686. this._projectionTexture.dispose();
  49687. }
  49688. };
  49689. /**
  49690. * Prepares the list of defines specific to the light type.
  49691. * @param defines the list of defines
  49692. * @param lightIndex defines the index of the light for the effect
  49693. */
  49694. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49695. defines["SPOTLIGHT" + lightIndex] = true;
  49696. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49697. };
  49698. __decorate([
  49699. BABYLON.serialize()
  49700. ], SpotLight.prototype, "angle", null);
  49701. __decorate([
  49702. BABYLON.serialize()
  49703. ], SpotLight.prototype, "innerAngle", null);
  49704. __decorate([
  49705. BABYLON.serialize()
  49706. ], SpotLight.prototype, "shadowAngleScale", null);
  49707. __decorate([
  49708. BABYLON.serialize()
  49709. ], SpotLight.prototype, "exponent", void 0);
  49710. __decorate([
  49711. BABYLON.serialize()
  49712. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49713. __decorate([
  49714. BABYLON.serialize()
  49715. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49716. __decorate([
  49717. BABYLON.serialize()
  49718. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49719. __decorate([
  49720. BABYLON.serializeAsTexture("projectedLightTexture")
  49721. ], SpotLight.prototype, "_projectionTexture", void 0);
  49722. return SpotLight;
  49723. }(BABYLON.ShadowLight));
  49724. BABYLON.SpotLight = SpotLight;
  49725. })(BABYLON || (BABYLON = {}));
  49726. //# sourceMappingURL=babylon.spotLight.js.map
  49727. var BABYLON;
  49728. (function (BABYLON) {
  49729. /**
  49730. * Class used to override all child animations of a given target
  49731. */
  49732. var AnimationPropertiesOverride = /** @class */ (function () {
  49733. function AnimationPropertiesOverride() {
  49734. /**
  49735. * Gets or sets a value indicating if animation blending must be used
  49736. */
  49737. this.enableBlending = false;
  49738. /**
  49739. * Gets or sets the blending speed to use when enableBlending is true
  49740. */
  49741. this.blendingSpeed = 0.01;
  49742. /**
  49743. * Gets or sets the default loop mode to use
  49744. */
  49745. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49746. }
  49747. return AnimationPropertiesOverride;
  49748. }());
  49749. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49750. })(BABYLON || (BABYLON = {}));
  49751. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49752. var BABYLON;
  49753. (function (BABYLON) {
  49754. /**
  49755. * Represents the range of an animation
  49756. */
  49757. var AnimationRange = /** @class */ (function () {
  49758. /**
  49759. * Initializes the range of an animation
  49760. * @param name The name of the animation range
  49761. * @param from The starting frame of the animation
  49762. * @param to The ending frame of the animation
  49763. */
  49764. function AnimationRange(
  49765. /**The name of the animation range**/
  49766. name,
  49767. /**The starting frame of the animation */
  49768. from,
  49769. /**The ending frame of the animation*/
  49770. to) {
  49771. this.name = name;
  49772. this.from = from;
  49773. this.to = to;
  49774. }
  49775. /**
  49776. * Makes a copy of the animation range
  49777. * @returns A copy of the animation range
  49778. */
  49779. AnimationRange.prototype.clone = function () {
  49780. return new AnimationRange(this.name, this.from, this.to);
  49781. };
  49782. return AnimationRange;
  49783. }());
  49784. BABYLON.AnimationRange = AnimationRange;
  49785. /**
  49786. * Composed of a frame, and an action function
  49787. */
  49788. var AnimationEvent = /** @class */ (function () {
  49789. /**
  49790. * Initializes the animation event
  49791. * @param frame The frame for which the event is triggered
  49792. * @param action The event to perform when triggered
  49793. * @param onlyOnce Specifies if the event should be triggered only once
  49794. */
  49795. function AnimationEvent(
  49796. /** The frame for which the event is triggered **/
  49797. frame,
  49798. /** The event to perform when triggered **/
  49799. action,
  49800. /** Specifies if the event should be triggered only once**/
  49801. onlyOnce) {
  49802. this.frame = frame;
  49803. this.action = action;
  49804. this.onlyOnce = onlyOnce;
  49805. /**
  49806. * Specifies if the animation event is done
  49807. */
  49808. this.isDone = false;
  49809. }
  49810. /** @hidden */
  49811. AnimationEvent.prototype._clone = function () {
  49812. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49813. };
  49814. return AnimationEvent;
  49815. }());
  49816. BABYLON.AnimationEvent = AnimationEvent;
  49817. /**
  49818. * A cursor which tracks a point on a path
  49819. */
  49820. var PathCursor = /** @class */ (function () {
  49821. /**
  49822. * Initializes the path cursor
  49823. * @param path The path to track
  49824. */
  49825. function PathCursor(path) {
  49826. this.path = path;
  49827. /**
  49828. * Stores path cursor callbacks for when an onchange event is triggered
  49829. */
  49830. this._onchange = new Array();
  49831. /**
  49832. * The value of the path cursor
  49833. */
  49834. this.value = 0;
  49835. /**
  49836. * The animation array of the path cursor
  49837. */
  49838. this.animations = new Array();
  49839. }
  49840. /**
  49841. * Gets the cursor point on the path
  49842. * @returns A point on the path cursor at the cursor location
  49843. */
  49844. PathCursor.prototype.getPoint = function () {
  49845. var point = this.path.getPointAtLengthPosition(this.value);
  49846. return new BABYLON.Vector3(point.x, 0, point.y);
  49847. };
  49848. /**
  49849. * Moves the cursor ahead by the step amount
  49850. * @param step The amount to move the cursor forward
  49851. * @returns This path cursor
  49852. */
  49853. PathCursor.prototype.moveAhead = function (step) {
  49854. if (step === void 0) { step = 0.002; }
  49855. this.move(step);
  49856. return this;
  49857. };
  49858. /**
  49859. * Moves the cursor behind by the step amount
  49860. * @param step The amount to move the cursor back
  49861. * @returns This path cursor
  49862. */
  49863. PathCursor.prototype.moveBack = function (step) {
  49864. if (step === void 0) { step = 0.002; }
  49865. this.move(-step);
  49866. return this;
  49867. };
  49868. /**
  49869. * Moves the cursor by the step amount
  49870. * If the step amount is greater than one, an exception is thrown
  49871. * @param step The amount to move the cursor
  49872. * @returns This path cursor
  49873. */
  49874. PathCursor.prototype.move = function (step) {
  49875. if (Math.abs(step) > 1) {
  49876. throw "step size should be less than 1.";
  49877. }
  49878. this.value += step;
  49879. this.ensureLimits();
  49880. this.raiseOnChange();
  49881. return this;
  49882. };
  49883. /**
  49884. * Ensures that the value is limited between zero and one
  49885. * @returns This path cursor
  49886. */
  49887. PathCursor.prototype.ensureLimits = function () {
  49888. while (this.value > 1) {
  49889. this.value -= 1;
  49890. }
  49891. while (this.value < 0) {
  49892. this.value += 1;
  49893. }
  49894. return this;
  49895. };
  49896. /**
  49897. * Runs onchange callbacks on change (used by the animation engine)
  49898. * @returns This path cursor
  49899. */
  49900. PathCursor.prototype.raiseOnChange = function () {
  49901. var _this = this;
  49902. this._onchange.forEach(function (f) { return f(_this); });
  49903. return this;
  49904. };
  49905. /**
  49906. * Executes a function on change
  49907. * @param f A path cursor onchange callback
  49908. * @returns This path cursor
  49909. */
  49910. PathCursor.prototype.onchange = function (f) {
  49911. this._onchange.push(f);
  49912. return this;
  49913. };
  49914. return PathCursor;
  49915. }());
  49916. BABYLON.PathCursor = PathCursor;
  49917. /**
  49918. * Enum for the animation key frame interpolation type
  49919. */
  49920. var AnimationKeyInterpolation;
  49921. (function (AnimationKeyInterpolation) {
  49922. /**
  49923. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49924. */
  49925. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49926. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49927. /**
  49928. * Class used to store any kind of animation
  49929. */
  49930. var Animation = /** @class */ (function () {
  49931. /**
  49932. * Initializes the animation
  49933. * @param name Name of the animation
  49934. * @param targetProperty Property to animate
  49935. * @param framePerSecond The frames per second of the animation
  49936. * @param dataType The data type of the animation
  49937. * @param loopMode The loop mode of the animation
  49938. * @param enableBlendings Specifies if blending should be enabled
  49939. */
  49940. function Animation(
  49941. /**Name of the animation */
  49942. name,
  49943. /**Property to animate */
  49944. targetProperty,
  49945. /**The frames per second of the animation */
  49946. framePerSecond,
  49947. /**The data type of the animation */
  49948. dataType,
  49949. /**The loop mode of the animation */
  49950. loopMode,
  49951. /**Specifies if blending should be enabled */
  49952. enableBlending) {
  49953. this.name = name;
  49954. this.targetProperty = targetProperty;
  49955. this.framePerSecond = framePerSecond;
  49956. this.dataType = dataType;
  49957. this.loopMode = loopMode;
  49958. this.enableBlending = enableBlending;
  49959. /**
  49960. * @hidden Internal use only
  49961. */
  49962. this._runtimeAnimations = new Array();
  49963. /**
  49964. * The set of event that will be linked to this animation
  49965. */
  49966. this._events = new Array();
  49967. /**
  49968. * Stores the blending speed of the animation
  49969. */
  49970. this.blendingSpeed = 0.01;
  49971. /**
  49972. * Stores the animation ranges for the animation
  49973. */
  49974. this._ranges = {};
  49975. this.targetPropertyPath = targetProperty.split(".");
  49976. this.dataType = dataType;
  49977. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49978. }
  49979. /**
  49980. * @hidden Internal use
  49981. */
  49982. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49983. var dataType = undefined;
  49984. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49985. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49986. }
  49987. else if (from instanceof BABYLON.Quaternion) {
  49988. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49989. }
  49990. else if (from instanceof BABYLON.Vector3) {
  49991. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49992. }
  49993. else if (from instanceof BABYLON.Vector2) {
  49994. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49995. }
  49996. else if (from instanceof BABYLON.Color3) {
  49997. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49998. }
  49999. else if (from instanceof BABYLON.Size) {
  50000. dataType = Animation.ANIMATIONTYPE_SIZE;
  50001. }
  50002. if (dataType == undefined) {
  50003. return null;
  50004. }
  50005. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50006. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50007. animation.setKeys(keys);
  50008. if (easingFunction !== undefined) {
  50009. animation.setEasingFunction(easingFunction);
  50010. }
  50011. return animation;
  50012. };
  50013. /**
  50014. * Sets up an animation
  50015. * @param property The property to animate
  50016. * @param animationType The animation type to apply
  50017. * @param framePerSecond The frames per second of the animation
  50018. * @param easingFunction The easing function used in the animation
  50019. * @returns The created animation
  50020. */
  50021. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50022. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50023. animation.setEasingFunction(easingFunction);
  50024. return animation;
  50025. };
  50026. /**
  50027. * Create and start an animation on a node
  50028. * @param name defines the name of the global animation that will be run on all nodes
  50029. * @param node defines the root node where the animation will take place
  50030. * @param targetProperty defines property to animate
  50031. * @param framePerSecond defines the number of frame per second yo use
  50032. * @param totalFrame defines the number of frames in total
  50033. * @param from defines the initial value
  50034. * @param to defines the final value
  50035. * @param loopMode defines which loop mode you want to use (off by default)
  50036. * @param easingFunction defines the easing function to use (linear by default)
  50037. * @param onAnimationEnd defines the callback to call when animation end
  50038. * @returns the animatable created for this animation
  50039. */
  50040. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50041. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50042. if (!animation) {
  50043. return null;
  50044. }
  50045. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50046. };
  50047. /**
  50048. * Create and start an animation on a node and its descendants
  50049. * @param name defines the name of the global animation that will be run on all nodes
  50050. * @param node defines the root node where the animation will take place
  50051. * @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
  50052. * @param targetProperty defines property to animate
  50053. * @param framePerSecond defines the number of frame per second to use
  50054. * @param totalFrame defines the number of frames in total
  50055. * @param from defines the initial value
  50056. * @param to defines the final value
  50057. * @param loopMode defines which loop mode you want to use (off by default)
  50058. * @param easingFunction defines the easing function to use (linear by default)
  50059. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50060. * @returns the list of animatables created for all nodes
  50061. * @example https://www.babylonjs-playground.com/#MH0VLI
  50062. */
  50063. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50064. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50065. if (!animation) {
  50066. return null;
  50067. }
  50068. var scene = node.getScene();
  50069. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50070. };
  50071. /**
  50072. * Creates a new animation, merges it with the existing animations and starts it
  50073. * @param name Name of the animation
  50074. * @param node Node which contains the scene that begins the animations
  50075. * @param targetProperty Specifies which property to animate
  50076. * @param framePerSecond The frames per second of the animation
  50077. * @param totalFrame The total number of frames
  50078. * @param from The frame at the beginning of the animation
  50079. * @param to The frame at the end of the animation
  50080. * @param loopMode Specifies the loop mode of the animation
  50081. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50082. * @param onAnimationEnd Callback to run once the animation is complete
  50083. * @returns Nullable animation
  50084. */
  50085. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50086. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50087. if (!animation) {
  50088. return null;
  50089. }
  50090. node.animations.push(animation);
  50091. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50092. };
  50093. /**
  50094. * Transition property of an host to the target Value
  50095. * @param property The property to transition
  50096. * @param targetValue The target Value of the property
  50097. * @param host The object where the property to animate belongs
  50098. * @param scene Scene used to run the animation
  50099. * @param frameRate Framerate (in frame/s) to use
  50100. * @param transition The transition type we want to use
  50101. * @param duration The duration of the animation, in milliseconds
  50102. * @param onAnimationEnd Callback trigger at the end of the animation
  50103. * @returns Nullable animation
  50104. */
  50105. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50106. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50107. if (duration <= 0) {
  50108. host[property] = targetValue;
  50109. if (onAnimationEnd) {
  50110. onAnimationEnd();
  50111. }
  50112. return null;
  50113. }
  50114. var endFrame = frameRate * (duration / 1000);
  50115. transition.setKeys([{
  50116. frame: 0,
  50117. value: host[property].clone ? host[property].clone() : host[property]
  50118. },
  50119. {
  50120. frame: endFrame,
  50121. value: targetValue
  50122. }]);
  50123. if (!host.animations) {
  50124. host.animations = [];
  50125. }
  50126. host.animations.push(transition);
  50127. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50128. animation.onAnimationEnd = onAnimationEnd;
  50129. return animation;
  50130. };
  50131. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50132. /**
  50133. * Return the array of runtime animations currently using this animation
  50134. */
  50135. get: function () {
  50136. return this._runtimeAnimations;
  50137. },
  50138. enumerable: true,
  50139. configurable: true
  50140. });
  50141. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50142. /**
  50143. * Specifies if any of the runtime animations are currently running
  50144. */
  50145. get: function () {
  50146. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50147. var runtimeAnimation = _a[_i];
  50148. if (!runtimeAnimation.isStopped) {
  50149. return true;
  50150. }
  50151. }
  50152. return false;
  50153. },
  50154. enumerable: true,
  50155. configurable: true
  50156. });
  50157. // Methods
  50158. /**
  50159. * Converts the animation to a string
  50160. * @param fullDetails support for multiple levels of logging within scene loading
  50161. * @returns String form of the animation
  50162. */
  50163. Animation.prototype.toString = function (fullDetails) {
  50164. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50165. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50166. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50167. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50168. if (fullDetails) {
  50169. ret += ", Ranges: {";
  50170. var first = true;
  50171. for (var name in this._ranges) {
  50172. if (first) {
  50173. ret += ", ";
  50174. first = false;
  50175. }
  50176. ret += name;
  50177. }
  50178. ret += "}";
  50179. }
  50180. return ret;
  50181. };
  50182. /**
  50183. * Add an event to this animation
  50184. * @param event Event to add
  50185. */
  50186. Animation.prototype.addEvent = function (event) {
  50187. this._events.push(event);
  50188. };
  50189. /**
  50190. * Remove all events found at the given frame
  50191. * @param frame The frame to remove events from
  50192. */
  50193. Animation.prototype.removeEvents = function (frame) {
  50194. for (var index = 0; index < this._events.length; index++) {
  50195. if (this._events[index].frame === frame) {
  50196. this._events.splice(index, 1);
  50197. index--;
  50198. }
  50199. }
  50200. };
  50201. /**
  50202. * Retrieves all the events from the animation
  50203. * @returns Events from the animation
  50204. */
  50205. Animation.prototype.getEvents = function () {
  50206. return this._events;
  50207. };
  50208. /**
  50209. * Creates an animation range
  50210. * @param name Name of the animation range
  50211. * @param from Starting frame of the animation range
  50212. * @param to Ending frame of the animation
  50213. */
  50214. Animation.prototype.createRange = function (name, from, to) {
  50215. // check name not already in use; could happen for bones after serialized
  50216. if (!this._ranges[name]) {
  50217. this._ranges[name] = new AnimationRange(name, from, to);
  50218. }
  50219. };
  50220. /**
  50221. * Deletes an animation range by name
  50222. * @param name Name of the animation range to delete
  50223. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50224. */
  50225. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50226. if (deleteFrames === void 0) { deleteFrames = true; }
  50227. var range = this._ranges[name];
  50228. if (!range) {
  50229. return;
  50230. }
  50231. if (deleteFrames) {
  50232. var from = range.from;
  50233. var to = range.to;
  50234. // this loop MUST go high to low for multiple splices to work
  50235. for (var key = this._keys.length - 1; key >= 0; key--) {
  50236. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50237. this._keys.splice(key, 1);
  50238. }
  50239. }
  50240. }
  50241. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50242. };
  50243. /**
  50244. * Gets the animation range by name, or null if not defined
  50245. * @param name Name of the animation range
  50246. * @returns Nullable animation range
  50247. */
  50248. Animation.prototype.getRange = function (name) {
  50249. return this._ranges[name];
  50250. };
  50251. /**
  50252. * Gets the key frames from the animation
  50253. * @returns The key frames of the animation
  50254. */
  50255. Animation.prototype.getKeys = function () {
  50256. return this._keys;
  50257. };
  50258. /**
  50259. * Gets the highest frame rate of the animation
  50260. * @returns Highest frame rate of the animation
  50261. */
  50262. Animation.prototype.getHighestFrame = function () {
  50263. var ret = 0;
  50264. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50265. if (ret < this._keys[key].frame) {
  50266. ret = this._keys[key].frame;
  50267. }
  50268. }
  50269. return ret;
  50270. };
  50271. /**
  50272. * Gets the easing function of the animation
  50273. * @returns Easing function of the animation
  50274. */
  50275. Animation.prototype.getEasingFunction = function () {
  50276. return this._easingFunction;
  50277. };
  50278. /**
  50279. * Sets the easing function of the animation
  50280. * @param easingFunction A custom mathematical formula for animation
  50281. */
  50282. Animation.prototype.setEasingFunction = function (easingFunction) {
  50283. this._easingFunction = easingFunction;
  50284. };
  50285. /**
  50286. * Interpolates a scalar linearly
  50287. * @param startValue Start value of the animation curve
  50288. * @param endValue End value of the animation curve
  50289. * @param gradient Scalar amount to interpolate
  50290. * @returns Interpolated scalar value
  50291. */
  50292. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50293. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50294. };
  50295. /**
  50296. * Interpolates a scalar cubically
  50297. * @param startValue Start value of the animation curve
  50298. * @param outTangent End tangent of the animation
  50299. * @param endValue End value of the animation curve
  50300. * @param inTangent Start tangent of the animation curve
  50301. * @param gradient Scalar amount to interpolate
  50302. * @returns Interpolated scalar value
  50303. */
  50304. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50305. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50306. };
  50307. /**
  50308. * Interpolates a quaternion using a spherical linear interpolation
  50309. * @param startValue Start value of the animation curve
  50310. * @param endValue End value of the animation curve
  50311. * @param gradient Scalar amount to interpolate
  50312. * @returns Interpolated quaternion value
  50313. */
  50314. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50315. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50316. };
  50317. /**
  50318. * Interpolates a quaternion cubically
  50319. * @param startValue Start value of the animation curve
  50320. * @param outTangent End tangent of the animation curve
  50321. * @param endValue End value of the animation curve
  50322. * @param inTangent Start tangent of the animation curve
  50323. * @param gradient Scalar amount to interpolate
  50324. * @returns Interpolated quaternion value
  50325. */
  50326. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50327. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50328. };
  50329. /**
  50330. * Interpolates a Vector3 linearl
  50331. * @param startValue Start value of the animation curve
  50332. * @param endValue End value of the animation curve
  50333. * @param gradient Scalar amount to interpolate
  50334. * @returns Interpolated scalar value
  50335. */
  50336. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50337. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50338. };
  50339. /**
  50340. * Interpolates a Vector3 cubically
  50341. * @param startValue Start value of the animation curve
  50342. * @param outTangent End tangent of the animation
  50343. * @param endValue End value of the animation curve
  50344. * @param inTangent Start tangent of the animation curve
  50345. * @param gradient Scalar amount to interpolate
  50346. * @returns InterpolatedVector3 value
  50347. */
  50348. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50349. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50350. };
  50351. /**
  50352. * Interpolates a Vector2 linearly
  50353. * @param startValue Start value of the animation curve
  50354. * @param endValue End value of the animation curve
  50355. * @param gradient Scalar amount to interpolate
  50356. * @returns Interpolated Vector2 value
  50357. */
  50358. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50359. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50360. };
  50361. /**
  50362. * Interpolates a Vector2 cubically
  50363. * @param startValue Start value of the animation curve
  50364. * @param outTangent End tangent of the animation
  50365. * @param endValue End value of the animation curve
  50366. * @param inTangent Start tangent of the animation curve
  50367. * @param gradient Scalar amount to interpolate
  50368. * @returns Interpolated Vector2 value
  50369. */
  50370. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50371. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50372. };
  50373. /**
  50374. * Interpolates a size linearly
  50375. * @param startValue Start value of the animation curve
  50376. * @param endValue End value of the animation curve
  50377. * @param gradient Scalar amount to interpolate
  50378. * @returns Interpolated Size value
  50379. */
  50380. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50381. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50382. };
  50383. /**
  50384. * Interpolates a Color3 linearly
  50385. * @param startValue Start value of the animation curve
  50386. * @param endValue End value of the animation curve
  50387. * @param gradient Scalar amount to interpolate
  50388. * @returns Interpolated Color3 value
  50389. */
  50390. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50391. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50392. };
  50393. /**
  50394. * @hidden Internal use only
  50395. */
  50396. Animation.prototype._getKeyValue = function (value) {
  50397. if (typeof value === "function") {
  50398. return value();
  50399. }
  50400. return value;
  50401. };
  50402. /**
  50403. * @hidden Internal use only
  50404. */
  50405. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50406. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50407. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50408. }
  50409. var keys = this.getKeys();
  50410. // Try to get a hash to find the right key
  50411. 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));
  50412. if (keys[startKeyIndex].frame >= currentFrame) {
  50413. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50414. startKeyIndex--;
  50415. }
  50416. }
  50417. for (var key = startKeyIndex; key < keys.length; key++) {
  50418. var endKey = keys[key + 1];
  50419. if (endKey.frame >= currentFrame) {
  50420. var startKey = keys[key];
  50421. var startValue = this._getKeyValue(startKey.value);
  50422. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50423. return startValue;
  50424. }
  50425. var endValue = this._getKeyValue(endKey.value);
  50426. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50427. var frameDelta = endKey.frame - startKey.frame;
  50428. // gradient : percent of currentFrame between the frame inf and the frame sup
  50429. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50430. // check for easingFunction and correction of gradient
  50431. var easingFunction = this.getEasingFunction();
  50432. if (easingFunction != null) {
  50433. gradient = easingFunction.ease(gradient);
  50434. }
  50435. switch (this.dataType) {
  50436. // Float
  50437. case Animation.ANIMATIONTYPE_FLOAT:
  50438. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50439. switch (loopMode) {
  50440. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50441. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50442. return floatValue;
  50443. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50444. return offsetValue * repeatCount + floatValue;
  50445. }
  50446. break;
  50447. // Quaternion
  50448. case Animation.ANIMATIONTYPE_QUATERNION:
  50449. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50450. switch (loopMode) {
  50451. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50452. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50453. return quatValue;
  50454. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50455. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50456. }
  50457. return quatValue;
  50458. // Vector3
  50459. case Animation.ANIMATIONTYPE_VECTOR3:
  50460. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50461. switch (loopMode) {
  50462. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50463. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50464. return vec3Value;
  50465. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50466. return vec3Value.add(offsetValue.scale(repeatCount));
  50467. }
  50468. // Vector2
  50469. case Animation.ANIMATIONTYPE_VECTOR2:
  50470. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50471. switch (loopMode) {
  50472. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50473. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50474. return vec2Value;
  50475. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50476. return vec2Value.add(offsetValue.scale(repeatCount));
  50477. }
  50478. // Size
  50479. case Animation.ANIMATIONTYPE_SIZE:
  50480. switch (loopMode) {
  50481. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50482. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50483. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50484. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50485. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50486. }
  50487. // Color3
  50488. case Animation.ANIMATIONTYPE_COLOR3:
  50489. switch (loopMode) {
  50490. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50491. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50492. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50493. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50494. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50495. }
  50496. // Matrix
  50497. case Animation.ANIMATIONTYPE_MATRIX:
  50498. switch (loopMode) {
  50499. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50500. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50501. if (Animation.AllowMatricesInterpolation) {
  50502. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50503. }
  50504. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50505. return startValue;
  50506. }
  50507. default:
  50508. break;
  50509. }
  50510. break;
  50511. }
  50512. }
  50513. return this._getKeyValue(keys[keys.length - 1].value);
  50514. };
  50515. /**
  50516. * Defines the function to use to interpolate matrices
  50517. * @param startValue defines the start matrix
  50518. * @param endValue defines the end matrix
  50519. * @param gradient defines the gradient between both matrices
  50520. * @param result defines an optional target matrix where to store the interpolation
  50521. * @returns the interpolated matrix
  50522. */
  50523. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50524. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50525. if (result) {
  50526. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50527. return result;
  50528. }
  50529. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50530. }
  50531. if (result) {
  50532. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50533. return result;
  50534. }
  50535. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50536. };
  50537. /**
  50538. * Makes a copy of the animation
  50539. * @returns Cloned animation
  50540. */
  50541. Animation.prototype.clone = function () {
  50542. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50543. clone.enableBlending = this.enableBlending;
  50544. clone.blendingSpeed = this.blendingSpeed;
  50545. if (this._keys) {
  50546. clone.setKeys(this._keys);
  50547. }
  50548. if (this._ranges) {
  50549. clone._ranges = {};
  50550. for (var name in this._ranges) {
  50551. var range = this._ranges[name];
  50552. if (!range) {
  50553. continue;
  50554. }
  50555. clone._ranges[name] = range.clone();
  50556. }
  50557. }
  50558. return clone;
  50559. };
  50560. /**
  50561. * Sets the key frames of the animation
  50562. * @param values The animation key frames to set
  50563. */
  50564. Animation.prototype.setKeys = function (values) {
  50565. this._keys = values.slice(0);
  50566. };
  50567. /**
  50568. * Serializes the animation to an object
  50569. * @returns Serialized object
  50570. */
  50571. Animation.prototype.serialize = function () {
  50572. var serializationObject = {};
  50573. serializationObject.name = this.name;
  50574. serializationObject.property = this.targetProperty;
  50575. serializationObject.framePerSecond = this.framePerSecond;
  50576. serializationObject.dataType = this.dataType;
  50577. serializationObject.loopBehavior = this.loopMode;
  50578. serializationObject.enableBlending = this.enableBlending;
  50579. serializationObject.blendingSpeed = this.blendingSpeed;
  50580. var dataType = this.dataType;
  50581. serializationObject.keys = [];
  50582. var keys = this.getKeys();
  50583. for (var index = 0; index < keys.length; index++) {
  50584. var animationKey = keys[index];
  50585. var key = {};
  50586. key.frame = animationKey.frame;
  50587. switch (dataType) {
  50588. case Animation.ANIMATIONTYPE_FLOAT:
  50589. key.values = [animationKey.value];
  50590. break;
  50591. case Animation.ANIMATIONTYPE_QUATERNION:
  50592. case Animation.ANIMATIONTYPE_MATRIX:
  50593. case Animation.ANIMATIONTYPE_VECTOR3:
  50594. case Animation.ANIMATIONTYPE_COLOR3:
  50595. key.values = animationKey.value.asArray();
  50596. break;
  50597. }
  50598. serializationObject.keys.push(key);
  50599. }
  50600. serializationObject.ranges = [];
  50601. for (var name in this._ranges) {
  50602. var source = this._ranges[name];
  50603. if (!source) {
  50604. continue;
  50605. }
  50606. var range = {};
  50607. range.name = name;
  50608. range.from = source.from;
  50609. range.to = source.to;
  50610. serializationObject.ranges.push(range);
  50611. }
  50612. return serializationObject;
  50613. };
  50614. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50615. /**
  50616. * Get the float animation type
  50617. */
  50618. get: function () {
  50619. return Animation._ANIMATIONTYPE_FLOAT;
  50620. },
  50621. enumerable: true,
  50622. configurable: true
  50623. });
  50624. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50625. /**
  50626. * Get the Vector3 animation type
  50627. */
  50628. get: function () {
  50629. return Animation._ANIMATIONTYPE_VECTOR3;
  50630. },
  50631. enumerable: true,
  50632. configurable: true
  50633. });
  50634. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50635. /**
  50636. * Get the Vector2 animation type
  50637. */
  50638. get: function () {
  50639. return Animation._ANIMATIONTYPE_VECTOR2;
  50640. },
  50641. enumerable: true,
  50642. configurable: true
  50643. });
  50644. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50645. /**
  50646. * Get the Size animation type
  50647. */
  50648. get: function () {
  50649. return Animation._ANIMATIONTYPE_SIZE;
  50650. },
  50651. enumerable: true,
  50652. configurable: true
  50653. });
  50654. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50655. /**
  50656. * Get the Quaternion animation type
  50657. */
  50658. get: function () {
  50659. return Animation._ANIMATIONTYPE_QUATERNION;
  50660. },
  50661. enumerable: true,
  50662. configurable: true
  50663. });
  50664. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50665. /**
  50666. * Get the Matrix animation type
  50667. */
  50668. get: function () {
  50669. return Animation._ANIMATIONTYPE_MATRIX;
  50670. },
  50671. enumerable: true,
  50672. configurable: true
  50673. });
  50674. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50675. /**
  50676. * Get the Color3 animation type
  50677. */
  50678. get: function () {
  50679. return Animation._ANIMATIONTYPE_COLOR3;
  50680. },
  50681. enumerable: true,
  50682. configurable: true
  50683. });
  50684. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50685. /**
  50686. * Get the Relative Loop Mode
  50687. */
  50688. get: function () {
  50689. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50695. /**
  50696. * Get the Cycle Loop Mode
  50697. */
  50698. get: function () {
  50699. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50705. /**
  50706. * Get the Constant Loop Mode
  50707. */
  50708. get: function () {
  50709. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50710. },
  50711. enumerable: true,
  50712. configurable: true
  50713. });
  50714. /** @hidden */
  50715. Animation._UniversalLerp = function (left, right, amount) {
  50716. var constructor = left.constructor;
  50717. if (constructor.Lerp) { // Lerp supported
  50718. return constructor.Lerp(left, right, amount);
  50719. }
  50720. else if (constructor.Slerp) { // Slerp supported
  50721. return constructor.Slerp(left, right, amount);
  50722. }
  50723. else if (left.toFixed) { // Number
  50724. return left * (1.0 - amount) + amount * right;
  50725. }
  50726. else { // Blending not supported
  50727. return right;
  50728. }
  50729. };
  50730. /**
  50731. * Parses an animation object and creates an animation
  50732. * @param parsedAnimation Parsed animation object
  50733. * @returns Animation object
  50734. */
  50735. Animation.Parse = function (parsedAnimation) {
  50736. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50737. var dataType = parsedAnimation.dataType;
  50738. var keys = [];
  50739. var data;
  50740. var index;
  50741. if (parsedAnimation.enableBlending) {
  50742. animation.enableBlending = parsedAnimation.enableBlending;
  50743. }
  50744. if (parsedAnimation.blendingSpeed) {
  50745. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50746. }
  50747. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50748. var key = parsedAnimation.keys[index];
  50749. var inTangent;
  50750. var outTangent;
  50751. switch (dataType) {
  50752. case Animation.ANIMATIONTYPE_FLOAT:
  50753. data = key.values[0];
  50754. if (key.values.length >= 1) {
  50755. inTangent = key.values[1];
  50756. }
  50757. if (key.values.length >= 2) {
  50758. outTangent = key.values[2];
  50759. }
  50760. break;
  50761. case Animation.ANIMATIONTYPE_QUATERNION:
  50762. data = BABYLON.Quaternion.FromArray(key.values);
  50763. if (key.values.length >= 8) {
  50764. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50765. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50766. inTangent = _inTangent;
  50767. }
  50768. }
  50769. if (key.values.length >= 12) {
  50770. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50771. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50772. outTangent = _outTangent;
  50773. }
  50774. }
  50775. break;
  50776. case Animation.ANIMATIONTYPE_MATRIX:
  50777. data = BABYLON.Matrix.FromArray(key.values);
  50778. break;
  50779. case Animation.ANIMATIONTYPE_COLOR3:
  50780. data = BABYLON.Color3.FromArray(key.values);
  50781. break;
  50782. case Animation.ANIMATIONTYPE_VECTOR3:
  50783. default:
  50784. data = BABYLON.Vector3.FromArray(key.values);
  50785. break;
  50786. }
  50787. var keyData = {};
  50788. keyData.frame = key.frame;
  50789. keyData.value = data;
  50790. if (inTangent != undefined) {
  50791. keyData.inTangent = inTangent;
  50792. }
  50793. if (outTangent != undefined) {
  50794. keyData.outTangent = outTangent;
  50795. }
  50796. keys.push(keyData);
  50797. }
  50798. animation.setKeys(keys);
  50799. if (parsedAnimation.ranges) {
  50800. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50801. data = parsedAnimation.ranges[index];
  50802. animation.createRange(data.name, data.from, data.to);
  50803. }
  50804. }
  50805. return animation;
  50806. };
  50807. /**
  50808. * Appends the serialized animations from the source animations
  50809. * @param source Source containing the animations
  50810. * @param destination Target to store the animations
  50811. */
  50812. Animation.AppendSerializedAnimations = function (source, destination) {
  50813. if (source.animations) {
  50814. destination.animations = [];
  50815. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50816. var animation = source.animations[animationIndex];
  50817. destination.animations.push(animation.serialize());
  50818. }
  50819. }
  50820. };
  50821. /**
  50822. * Use matrix interpolation instead of using direct key value when animating matrices
  50823. */
  50824. Animation.AllowMatricesInterpolation = false;
  50825. /**
  50826. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50827. */
  50828. Animation.AllowMatrixDecomposeForInterpolation = true;
  50829. // Statics
  50830. /**
  50831. * Float animation type
  50832. */
  50833. Animation._ANIMATIONTYPE_FLOAT = 0;
  50834. /**
  50835. * Vector3 animation type
  50836. */
  50837. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50838. /**
  50839. * Quaternion animation type
  50840. */
  50841. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50842. /**
  50843. * Matrix animation type
  50844. */
  50845. Animation._ANIMATIONTYPE_MATRIX = 3;
  50846. /**
  50847. * Color3 animation type
  50848. */
  50849. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50850. /**
  50851. * Vector2 animation type
  50852. */
  50853. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50854. /**
  50855. * Size animation type
  50856. */
  50857. Animation._ANIMATIONTYPE_SIZE = 6;
  50858. /**
  50859. * Relative Loop Mode
  50860. */
  50861. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50862. /**
  50863. * Cycle Loop Mode
  50864. */
  50865. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50866. /**
  50867. * Constant Loop Mode
  50868. */
  50869. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50870. return Animation;
  50871. }());
  50872. BABYLON.Animation = Animation;
  50873. })(BABYLON || (BABYLON = {}));
  50874. //# sourceMappingURL=babylon.animation.js.map
  50875. var BABYLON;
  50876. (function (BABYLON) {
  50877. /**
  50878. * This class defines the direct association between an animation and a target
  50879. */
  50880. var TargetedAnimation = /** @class */ (function () {
  50881. function TargetedAnimation() {
  50882. }
  50883. return TargetedAnimation;
  50884. }());
  50885. BABYLON.TargetedAnimation = TargetedAnimation;
  50886. /**
  50887. * Use this class to create coordinated animations on multiple targets
  50888. */
  50889. var AnimationGroup = /** @class */ (function () {
  50890. function AnimationGroup(name, scene) {
  50891. if (scene === void 0) { scene = null; }
  50892. this.name = name;
  50893. this._targetedAnimations = new Array();
  50894. this._animatables = new Array();
  50895. this._from = Number.MAX_VALUE;
  50896. this._to = -Number.MAX_VALUE;
  50897. this._speedRatio = 1;
  50898. this.onAnimationEndObservable = new BABYLON.Observable();
  50899. /**
  50900. * This observable will notify when all animations have ended.
  50901. */
  50902. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50903. /**
  50904. * This observable will notify when all animations have paused.
  50905. */
  50906. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50907. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50908. this._scene.animationGroups.push(this);
  50909. }
  50910. Object.defineProperty(AnimationGroup.prototype, "from", {
  50911. /**
  50912. * Gets the first frame
  50913. */
  50914. get: function () {
  50915. return this._from;
  50916. },
  50917. enumerable: true,
  50918. configurable: true
  50919. });
  50920. Object.defineProperty(AnimationGroup.prototype, "to", {
  50921. /**
  50922. * Gets the last frame
  50923. */
  50924. get: function () {
  50925. return this._to;
  50926. },
  50927. enumerable: true,
  50928. configurable: true
  50929. });
  50930. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50931. /**
  50932. * Define if the animations are started
  50933. */
  50934. get: function () {
  50935. return this._isStarted;
  50936. },
  50937. enumerable: true,
  50938. configurable: true
  50939. });
  50940. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50941. /**
  50942. * Gets or sets the speed ratio to use for all animations
  50943. */
  50944. get: function () {
  50945. return this._speedRatio;
  50946. },
  50947. /**
  50948. * Gets or sets the speed ratio to use for all animations
  50949. */
  50950. set: function (value) {
  50951. if (this._speedRatio === value) {
  50952. return;
  50953. }
  50954. this._speedRatio = value;
  50955. for (var index = 0; index < this._animatables.length; index++) {
  50956. var animatable = this._animatables[index];
  50957. animatable.speedRatio = this._speedRatio;
  50958. }
  50959. },
  50960. enumerable: true,
  50961. configurable: true
  50962. });
  50963. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50964. /**
  50965. * Gets the targeted animations for this animation group
  50966. */
  50967. get: function () {
  50968. return this._targetedAnimations;
  50969. },
  50970. enumerable: true,
  50971. configurable: true
  50972. });
  50973. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50974. /**
  50975. * returning the list of animatables controlled by this animation group.
  50976. */
  50977. get: function () {
  50978. return this._animatables;
  50979. },
  50980. enumerable: true,
  50981. configurable: true
  50982. });
  50983. /**
  50984. * Add an animation (with its target) in the group
  50985. * @param animation defines the animation we want to add
  50986. * @param target defines the target of the animation
  50987. * @returns the {BABYLON.TargetedAnimation} object
  50988. */
  50989. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50990. var targetedAnimation = {
  50991. animation: animation,
  50992. target: target
  50993. };
  50994. var keys = animation.getKeys();
  50995. if (this._from > keys[0].frame) {
  50996. this._from = keys[0].frame;
  50997. }
  50998. if (this._to < keys[keys.length - 1].frame) {
  50999. this._to = keys[keys.length - 1].frame;
  51000. }
  51001. this._targetedAnimations.push(targetedAnimation);
  51002. return targetedAnimation;
  51003. };
  51004. /**
  51005. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51006. * It can add constant keys at begin or end
  51007. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51008. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51009. */
  51010. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51011. if (beginFrame === void 0) { beginFrame = null; }
  51012. if (endFrame === void 0) { endFrame = null; }
  51013. if (beginFrame == null)
  51014. beginFrame = this._from;
  51015. if (endFrame == null)
  51016. endFrame = this._to;
  51017. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51018. var targetedAnimation = this._targetedAnimations[index];
  51019. var keys = targetedAnimation.animation.getKeys();
  51020. var startKey = keys[0];
  51021. var endKey = keys[keys.length - 1];
  51022. if (startKey.frame > beginFrame) {
  51023. var newKey = {
  51024. frame: beginFrame,
  51025. value: startKey.value,
  51026. inTangent: startKey.inTangent,
  51027. outTangent: startKey.outTangent,
  51028. interpolation: startKey.interpolation
  51029. };
  51030. keys.splice(0, 0, newKey);
  51031. }
  51032. if (endKey.frame < endFrame) {
  51033. var newKey = {
  51034. frame: endFrame,
  51035. value: endKey.value,
  51036. inTangent: endKey.outTangent,
  51037. outTangent: endKey.outTangent,
  51038. interpolation: endKey.interpolation
  51039. };
  51040. keys.push(newKey);
  51041. }
  51042. }
  51043. this._from = beginFrame;
  51044. this._to = endFrame;
  51045. return this;
  51046. };
  51047. /**
  51048. * Start all animations on given targets
  51049. * @param loop defines if animations must loop
  51050. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51051. * @param from defines the from key (optional)
  51052. * @param to defines the to key (optional)
  51053. * @returns the current animation group
  51054. */
  51055. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51056. var _this = this;
  51057. if (loop === void 0) { loop = false; }
  51058. if (speedRatio === void 0) { speedRatio = 1; }
  51059. if (this._isStarted || this._targetedAnimations.length === 0) {
  51060. return this;
  51061. }
  51062. var _loop_1 = function (targetedAnimation) {
  51063. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51064. animatable.onAnimationEnd = function () {
  51065. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51066. _this._checkAnimationGroupEnded(animatable);
  51067. };
  51068. this_1._animatables.push(animatable);
  51069. };
  51070. var this_1 = this;
  51071. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51072. var targetedAnimation = _a[_i];
  51073. _loop_1(targetedAnimation);
  51074. }
  51075. this._speedRatio = speedRatio;
  51076. this._isStarted = true;
  51077. return this;
  51078. };
  51079. /**
  51080. * Pause all animations
  51081. */
  51082. AnimationGroup.prototype.pause = function () {
  51083. if (!this._isStarted) {
  51084. return this;
  51085. }
  51086. for (var index = 0; index < this._animatables.length; index++) {
  51087. var animatable = this._animatables[index];
  51088. animatable.pause();
  51089. }
  51090. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51091. return this;
  51092. };
  51093. /**
  51094. * Play all animations to initial state
  51095. * This function will start() the animations if they were not started or will restart() them if they were paused
  51096. * @param loop defines if animations must loop
  51097. */
  51098. AnimationGroup.prototype.play = function (loop) {
  51099. // only if all animatables are ready and exist
  51100. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51101. if (loop !== undefined) {
  51102. for (var index = 0; index < this._animatables.length; index++) {
  51103. var animatable = this._animatables[index];
  51104. animatable.loopAnimation = loop;
  51105. }
  51106. }
  51107. this.restart();
  51108. }
  51109. else {
  51110. this.stop();
  51111. this.start(loop, this._speedRatio);
  51112. }
  51113. return this;
  51114. };
  51115. /**
  51116. * Reset all animations to initial state
  51117. */
  51118. AnimationGroup.prototype.reset = function () {
  51119. if (!this._isStarted) {
  51120. return this;
  51121. }
  51122. for (var index = 0; index < this._animatables.length; index++) {
  51123. var animatable = this._animatables[index];
  51124. animatable.reset();
  51125. }
  51126. return this;
  51127. };
  51128. /**
  51129. * Restart animations from key 0
  51130. */
  51131. AnimationGroup.prototype.restart = function () {
  51132. if (!this._isStarted) {
  51133. return this;
  51134. }
  51135. for (var index = 0; index < this._animatables.length; index++) {
  51136. var animatable = this._animatables[index];
  51137. animatable.restart();
  51138. }
  51139. return this;
  51140. };
  51141. /**
  51142. * Stop all animations
  51143. */
  51144. AnimationGroup.prototype.stop = function () {
  51145. if (!this._isStarted) {
  51146. return this;
  51147. }
  51148. var list = this._animatables.slice();
  51149. for (var index = 0; index < list.length; index++) {
  51150. list[index].stop();
  51151. }
  51152. this._isStarted = false;
  51153. return this;
  51154. };
  51155. /**
  51156. * Set animation weight for all animatables
  51157. * @param weight defines the weight to use
  51158. * @return the animationGroup
  51159. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51160. */
  51161. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51162. for (var index = 0; index < this._animatables.length; index++) {
  51163. var animatable = this._animatables[index];
  51164. animatable.weight = weight;
  51165. }
  51166. return this;
  51167. };
  51168. /**
  51169. * Synchronize and normalize all animatables with a source animatable
  51170. * @param root defines the root animatable to synchronize with
  51171. * @return the animationGroup
  51172. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51173. */
  51174. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51175. for (var index = 0; index < this._animatables.length; index++) {
  51176. var animatable = this._animatables[index];
  51177. animatable.syncWith(root);
  51178. }
  51179. return this;
  51180. };
  51181. /**
  51182. * Goes to a specific frame in this animation group
  51183. * @param frame the frame number to go to
  51184. * @return the animationGroup
  51185. */
  51186. AnimationGroup.prototype.goToFrame = function (frame) {
  51187. if (!this._isStarted) {
  51188. return this;
  51189. }
  51190. for (var index = 0; index < this._animatables.length; index++) {
  51191. var animatable = this._animatables[index];
  51192. animatable.goToFrame(frame);
  51193. }
  51194. return this;
  51195. };
  51196. /**
  51197. * Dispose all associated resources
  51198. */
  51199. AnimationGroup.prototype.dispose = function () {
  51200. this._targetedAnimations = [];
  51201. this._animatables = [];
  51202. var index = this._scene.animationGroups.indexOf(this);
  51203. if (index > -1) {
  51204. this._scene.animationGroups.splice(index, 1);
  51205. }
  51206. };
  51207. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51208. // animatable should be taken out of the array
  51209. var idx = this._animatables.indexOf(animatable);
  51210. if (idx > -1) {
  51211. this._animatables.splice(idx, 1);
  51212. }
  51213. // all animatables were removed? animation group ended!
  51214. if (this._animatables.length === 0) {
  51215. this._isStarted = false;
  51216. this.onAnimationGroupEndObservable.notifyObservers(this);
  51217. }
  51218. };
  51219. return AnimationGroup;
  51220. }());
  51221. BABYLON.AnimationGroup = AnimationGroup;
  51222. })(BABYLON || (BABYLON = {}));
  51223. //# sourceMappingURL=babylon.animationGroup.js.map
  51224. var BABYLON;
  51225. (function (BABYLON) {
  51226. // Static values to help the garbage collector
  51227. // Quaternion
  51228. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51229. // Vector3
  51230. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51231. // Vector2
  51232. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51233. // Size
  51234. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51235. // Color3
  51236. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51237. /**
  51238. * Defines a runtime animation
  51239. */
  51240. var RuntimeAnimation = /** @class */ (function () {
  51241. /**
  51242. * Create a new RuntimeAnimation object
  51243. * @param target defines the target of the animation
  51244. * @param animation defines the source animation object
  51245. * @param scene defines the hosting scene
  51246. * @param host defines the initiating Animatable
  51247. */
  51248. function RuntimeAnimation(target, animation, scene, host) {
  51249. var _this = this;
  51250. this._events = new Array();
  51251. /**
  51252. * The current frame of the runtime animation
  51253. */
  51254. this._currentFrame = 0;
  51255. /**
  51256. * The original value of the runtime animation
  51257. */
  51258. this._originalValue = new Array();
  51259. /**
  51260. * The offsets cache of the runtime animation
  51261. */
  51262. this._offsetsCache = {};
  51263. /**
  51264. * The high limits cache of the runtime animation
  51265. */
  51266. this._highLimitsCache = {};
  51267. /**
  51268. * Specifies if the runtime animation has been stopped
  51269. */
  51270. this._stopped = false;
  51271. /**
  51272. * The blending factor of the runtime animation
  51273. */
  51274. this._blendingFactor = 0;
  51275. /**
  51276. * The target path of the runtime animation
  51277. */
  51278. this._targetPath = "";
  51279. /**
  51280. * The weight of the runtime animation
  51281. */
  51282. this._weight = 1.0;
  51283. /**
  51284. * The ratio offset of the runtime animation
  51285. */
  51286. this._ratioOffset = 0;
  51287. /**
  51288. * The previous delay of the runtime animation
  51289. */
  51290. this._previousDelay = 0;
  51291. /**
  51292. * The previous ratio of the runtime animation
  51293. */
  51294. this._previousRatio = 0;
  51295. this._animation = animation;
  51296. this._target = target;
  51297. this._scene = scene;
  51298. this._host = host;
  51299. animation._runtimeAnimations.push(this);
  51300. // Cloning events locally
  51301. var events = animation.getEvents();
  51302. if (events && events.length > 0) {
  51303. events.forEach(function (e) {
  51304. _this._events.push(e._clone());
  51305. });
  51306. }
  51307. }
  51308. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51309. /**
  51310. * Gets the current frame of the runtime animation
  51311. */
  51312. get: function () {
  51313. return this._currentFrame;
  51314. },
  51315. enumerable: true,
  51316. configurable: true
  51317. });
  51318. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51319. /**
  51320. * Gets the weight of the runtime animation
  51321. */
  51322. get: function () {
  51323. return this._weight;
  51324. },
  51325. enumerable: true,
  51326. configurable: true
  51327. });
  51328. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51329. /**
  51330. * Gets the current value of the runtime animation
  51331. */
  51332. get: function () {
  51333. return this._currentValue;
  51334. },
  51335. enumerable: true,
  51336. configurable: true
  51337. });
  51338. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51339. /**
  51340. * Gets the target path of the runtime animation
  51341. */
  51342. get: function () {
  51343. return this._targetPath;
  51344. },
  51345. enumerable: true,
  51346. configurable: true
  51347. });
  51348. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51349. /**
  51350. * Gets the actual target of the runtime animation
  51351. */
  51352. get: function () {
  51353. return this._activeTarget;
  51354. },
  51355. enumerable: true,
  51356. configurable: true
  51357. });
  51358. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51359. /**
  51360. * Gets the animation from the runtime animation
  51361. */
  51362. get: function () {
  51363. return this._animation;
  51364. },
  51365. enumerable: true,
  51366. configurable: true
  51367. });
  51368. /**
  51369. * Resets the runtime animation to the beginning
  51370. * @param restoreOriginal defines whether to restore the target property to the original value
  51371. */
  51372. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51373. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51374. if (restoreOriginal) {
  51375. if (this._target instanceof Array) {
  51376. var index = 0;
  51377. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51378. var target = _a[_i];
  51379. if (this._originalValue[index] !== undefined) {
  51380. this._setValue(target, this._originalValue[index], -1);
  51381. }
  51382. index++;
  51383. }
  51384. }
  51385. else {
  51386. if (this._originalValue[0] !== undefined) {
  51387. this._setValue(this._target, this._originalValue[0], -1);
  51388. }
  51389. }
  51390. }
  51391. this._offsetsCache = {};
  51392. this._highLimitsCache = {};
  51393. this._currentFrame = 0;
  51394. this._blendingFactor = 0;
  51395. this._originalValue = new Array();
  51396. // Events
  51397. for (var index = 0; index < this._events.length; index++) {
  51398. this._events[index].isDone = false;
  51399. }
  51400. };
  51401. /**
  51402. * Specifies if the runtime animation is stopped
  51403. * @returns Boolean specifying if the runtime animation is stopped
  51404. */
  51405. RuntimeAnimation.prototype.isStopped = function () {
  51406. return this._stopped;
  51407. };
  51408. /**
  51409. * Disposes of the runtime animation
  51410. */
  51411. RuntimeAnimation.prototype.dispose = function () {
  51412. var index = this._animation.runtimeAnimations.indexOf(this);
  51413. if (index > -1) {
  51414. this._animation.runtimeAnimations.splice(index, 1);
  51415. }
  51416. };
  51417. /**
  51418. * Interpolates the animation from the current frame
  51419. * @param currentFrame The frame to interpolate the animation to
  51420. * @param repeatCount The number of times that the animation should loop
  51421. * @param loopMode The type of looping mode to use
  51422. * @param offsetValue Animation offset value
  51423. * @param highLimitValue The high limit value
  51424. * @returns The interpolated value
  51425. */
  51426. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51427. this._currentFrame = currentFrame;
  51428. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51429. this._workValue = BABYLON.Matrix.Zero();
  51430. }
  51431. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51432. };
  51433. /**
  51434. * Apply the interpolated value to the target
  51435. * @param currentValue defines the value computed by the animation
  51436. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51437. */
  51438. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51439. if (weight === void 0) { weight = 1.0; }
  51440. if (this._target instanceof Array) {
  51441. var index = 0;
  51442. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51443. var target = _a[_i];
  51444. this._setValue(target, currentValue, weight, index);
  51445. index++;
  51446. }
  51447. }
  51448. else {
  51449. this._setValue(this._target, currentValue, weight);
  51450. }
  51451. };
  51452. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51453. if (targetIndex === void 0) { targetIndex = 0; }
  51454. // Set value
  51455. var path;
  51456. var destination;
  51457. var targetPropertyPath = this._animation.targetPropertyPath;
  51458. if (targetPropertyPath.length > 1) {
  51459. var property = target[targetPropertyPath[0]];
  51460. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51461. property = property[targetPropertyPath[index]];
  51462. }
  51463. path = targetPropertyPath[targetPropertyPath.length - 1];
  51464. destination = property;
  51465. }
  51466. else {
  51467. path = targetPropertyPath[0];
  51468. destination = target;
  51469. }
  51470. this._targetPath = path;
  51471. this._activeTarget = destination;
  51472. this._weight = weight;
  51473. if (this._originalValue[targetIndex] === undefined) {
  51474. var originalValue = void 0;
  51475. if (destination.getRestPose && path === "_matrix") { // For bones
  51476. originalValue = destination.getRestPose();
  51477. }
  51478. else {
  51479. originalValue = destination[path];
  51480. }
  51481. if (originalValue && originalValue.clone) {
  51482. this._originalValue[targetIndex] = originalValue.clone();
  51483. }
  51484. else {
  51485. this._originalValue[targetIndex] = originalValue;
  51486. }
  51487. }
  51488. // Blending
  51489. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51490. if (enableBlending && this._blendingFactor <= 1.0) {
  51491. if (!this._originalBlendValue) {
  51492. var originalValue = destination[path];
  51493. if (originalValue.clone) {
  51494. this._originalBlendValue = originalValue.clone();
  51495. }
  51496. else {
  51497. this._originalBlendValue = originalValue;
  51498. }
  51499. }
  51500. if (this._originalBlendValue.m) { // Matrix
  51501. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51502. if (this._currentValue) {
  51503. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51504. }
  51505. else {
  51506. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51507. }
  51508. }
  51509. else {
  51510. if (this._currentValue) {
  51511. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51512. }
  51513. else {
  51514. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51515. }
  51516. }
  51517. }
  51518. else {
  51519. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51520. }
  51521. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51522. this._blendingFactor += blendingSpeed;
  51523. }
  51524. else {
  51525. this._currentValue = currentValue;
  51526. }
  51527. if (weight !== -1.0) {
  51528. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51529. }
  51530. else {
  51531. destination[path] = this._currentValue;
  51532. }
  51533. if (target.markAsDirty) {
  51534. target.markAsDirty(this._animation.targetProperty);
  51535. }
  51536. };
  51537. /**
  51538. * Gets the loop pmode of the runtime animation
  51539. * @returns Loop Mode
  51540. */
  51541. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51542. if (this._target && this._target.animationPropertiesOverride) {
  51543. return this._target.animationPropertiesOverride.loopMode;
  51544. }
  51545. return this._animation.loopMode;
  51546. };
  51547. /**
  51548. * Move the current animation to a given frame
  51549. * @param frame defines the frame to move to
  51550. */
  51551. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51552. var keys = this._animation.getKeys();
  51553. if (frame < keys[0].frame) {
  51554. frame = keys[0].frame;
  51555. }
  51556. else if (frame > keys[keys.length - 1].frame) {
  51557. frame = keys[keys.length - 1].frame;
  51558. }
  51559. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51560. this.setValue(currentValue, -1);
  51561. };
  51562. /**
  51563. * @hidden Internal use only
  51564. */
  51565. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51566. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51567. this._ratioOffset = this._previousRatio - newRatio;
  51568. };
  51569. /**
  51570. * Execute the current animation
  51571. * @param delay defines the delay to add to the current frame
  51572. * @param from defines the lower bound of the animation range
  51573. * @param to defines the upper bound of the animation range
  51574. * @param loop defines if the current animation must loop
  51575. * @param speedRatio defines the current speed ratio
  51576. * @param weight defines the weight of the animation (default is -1 so no weight)
  51577. * @returns a boolean indicating if the animation is running
  51578. */
  51579. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51580. if (weight === void 0) { weight = -1.0; }
  51581. var targetPropertyPath = this._animation.targetPropertyPath;
  51582. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51583. this._stopped = true;
  51584. return false;
  51585. }
  51586. var returnValue = true;
  51587. var keys = this._animation.getKeys();
  51588. // Adding a start key at frame 0 if missing
  51589. if (keys[0].frame !== 0) {
  51590. var newKey = { frame: 0, value: keys[0].value };
  51591. keys.splice(0, 0, newKey);
  51592. }
  51593. // Adding a duplicate key when there is only one key at frame zero
  51594. else if (keys.length === 1) {
  51595. var newKey = { frame: 0.001, value: keys[0].value };
  51596. keys.push(newKey);
  51597. }
  51598. // Check limits
  51599. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51600. from = keys[0].frame;
  51601. }
  51602. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51603. to = keys[keys.length - 1].frame;
  51604. }
  51605. //to and from cannot be the same key
  51606. if (from === to) {
  51607. if (from > keys[0].frame) {
  51608. from--;
  51609. }
  51610. else if (to < keys[keys.length - 1].frame) {
  51611. to++;
  51612. }
  51613. }
  51614. // Compute ratio
  51615. var range = to - from;
  51616. var offsetValue;
  51617. // ratio represents the frame delta between from and to
  51618. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51619. var highLimitValue = 0;
  51620. this._previousDelay = delay;
  51621. this._previousRatio = ratio;
  51622. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51623. returnValue = false;
  51624. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51625. }
  51626. else {
  51627. // Get max value if required
  51628. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51629. var keyOffset = to.toString() + from.toString();
  51630. if (!this._offsetsCache[keyOffset]) {
  51631. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51632. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51633. switch (this._animation.dataType) {
  51634. // Float
  51635. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51636. this._offsetsCache[keyOffset] = toValue - fromValue;
  51637. break;
  51638. // Quaternion
  51639. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51640. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51641. break;
  51642. // Vector3
  51643. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51644. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51645. // Vector2
  51646. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51647. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51648. // Size
  51649. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51650. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51651. // Color3
  51652. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51653. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51654. default:
  51655. break;
  51656. }
  51657. this._highLimitsCache[keyOffset] = toValue;
  51658. }
  51659. highLimitValue = this._highLimitsCache[keyOffset];
  51660. offsetValue = this._offsetsCache[keyOffset];
  51661. }
  51662. }
  51663. if (offsetValue === undefined) {
  51664. switch (this._animation.dataType) {
  51665. // Float
  51666. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51667. offsetValue = 0;
  51668. break;
  51669. // Quaternion
  51670. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51671. offsetValue = _staticOffsetValueQuaternion;
  51672. break;
  51673. // Vector3
  51674. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51675. offsetValue = _staticOffsetValueVector3;
  51676. break;
  51677. // Vector2
  51678. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51679. offsetValue = _staticOffsetValueVector2;
  51680. break;
  51681. // Size
  51682. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51683. offsetValue = _staticOffsetValueSize;
  51684. break;
  51685. // Color3
  51686. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51687. offsetValue = _staticOffsetValueColor3;
  51688. }
  51689. }
  51690. // Compute value
  51691. var repeatCount = (ratio / range) >> 0;
  51692. var currentFrame = returnValue ? from + ratio % range : to;
  51693. // Need to normalize?
  51694. if (this._host && this._host.syncRoot) {
  51695. var syncRoot = this._host.syncRoot;
  51696. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51697. currentFrame = from + (to - from) * hostNormalizedFrame;
  51698. }
  51699. // Reset events if looping
  51700. var events = this._events;
  51701. if (range > 0 && this.currentFrame > currentFrame ||
  51702. range < 0 && this.currentFrame < currentFrame) {
  51703. // Need to reset animation events
  51704. for (var index = 0; index < events.length; index++) {
  51705. if (!events[index].onlyOnce) {
  51706. // reset event, the animation is looping
  51707. events[index].isDone = false;
  51708. }
  51709. }
  51710. }
  51711. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51712. // Set value
  51713. this.setValue(currentValue, weight);
  51714. // Check events
  51715. for (var index = 0; index < events.length; index++) {
  51716. // Make sure current frame has passed event frame and that event frame is within the current range
  51717. // Also, handle both forward and reverse animations
  51718. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51719. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51720. var event = events[index];
  51721. if (!event.isDone) {
  51722. // If event should be done only once, remove it.
  51723. if (event.onlyOnce) {
  51724. events.splice(index, 1);
  51725. index--;
  51726. }
  51727. event.isDone = true;
  51728. event.action(currentFrame);
  51729. } // Don't do anything if the event has already be done.
  51730. }
  51731. }
  51732. if (!returnValue) {
  51733. this._stopped = true;
  51734. }
  51735. return returnValue;
  51736. };
  51737. return RuntimeAnimation;
  51738. }());
  51739. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51740. })(BABYLON || (BABYLON = {}));
  51741. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51742. var BABYLON;
  51743. (function (BABYLON) {
  51744. /**
  51745. * Class used to store an actual running animation
  51746. */
  51747. var Animatable = /** @class */ (function () {
  51748. /**
  51749. * Creates a new Animatable
  51750. * @param scene defines the hosting scene
  51751. * @param target defines the target object
  51752. * @param fromFrame defines the starting frame number (default is 0)
  51753. * @param toFrame defines the ending frame number (default is 100)
  51754. * @param loopAnimation defines if the animation must loop (default is false)
  51755. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51756. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51757. * @param animations defines a group of animation to add to the new Animatable
  51758. */
  51759. function Animatable(scene,
  51760. /** defines the target object */
  51761. target,
  51762. /** defines the starting frame number (default is 0) */
  51763. fromFrame,
  51764. /** defines the ending frame number (default is 100) */
  51765. toFrame,
  51766. /** defines if the animation must loop (default is false) */
  51767. loopAnimation, speedRatio,
  51768. /** defines a callback to call when animation ends if it is not looping */
  51769. onAnimationEnd, animations) {
  51770. if (fromFrame === void 0) { fromFrame = 0; }
  51771. if (toFrame === void 0) { toFrame = 100; }
  51772. if (loopAnimation === void 0) { loopAnimation = false; }
  51773. if (speedRatio === void 0) { speedRatio = 1.0; }
  51774. this.target = target;
  51775. this.fromFrame = fromFrame;
  51776. this.toFrame = toFrame;
  51777. this.loopAnimation = loopAnimation;
  51778. this.onAnimationEnd = onAnimationEnd;
  51779. this._localDelayOffset = null;
  51780. this._pausedDelay = null;
  51781. this._runtimeAnimations = new Array();
  51782. this._paused = false;
  51783. this._speedRatio = 1;
  51784. this._weight = -1.0;
  51785. /**
  51786. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51787. * This will only apply for non looping animation (default is true)
  51788. */
  51789. this.disposeOnEnd = true;
  51790. /**
  51791. * Gets a boolean indicating if the animation has started
  51792. */
  51793. this.animationStarted = false;
  51794. /**
  51795. * Observer raised when the animation ends
  51796. */
  51797. this.onAnimationEndObservable = new BABYLON.Observable();
  51798. this._scene = scene;
  51799. if (animations) {
  51800. this.appendAnimations(target, animations);
  51801. }
  51802. this._speedRatio = speedRatio;
  51803. scene._activeAnimatables.push(this);
  51804. }
  51805. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51806. /**
  51807. * Gets the root Animatable used to synchronize and normalize animations
  51808. */
  51809. get: function () {
  51810. return this._syncRoot;
  51811. },
  51812. enumerable: true,
  51813. configurable: true
  51814. });
  51815. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51816. /**
  51817. * Gets the current frame of the first RuntimeAnimation
  51818. * Used to synchronize Animatables
  51819. */
  51820. get: function () {
  51821. if (this._runtimeAnimations.length === 0) {
  51822. return 0;
  51823. }
  51824. return this._runtimeAnimations[0].currentFrame;
  51825. },
  51826. enumerable: true,
  51827. configurable: true
  51828. });
  51829. Object.defineProperty(Animatable.prototype, "weight", {
  51830. /**
  51831. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51832. */
  51833. get: function () {
  51834. return this._weight;
  51835. },
  51836. set: function (value) {
  51837. if (value === -1) { // -1 is ok and means no weight
  51838. this._weight = -1;
  51839. return;
  51840. }
  51841. // Else weight must be in [0, 1] range
  51842. this._weight = Math.min(Math.max(value, 0), 1.0);
  51843. },
  51844. enumerable: true,
  51845. configurable: true
  51846. });
  51847. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51848. /**
  51849. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51850. */
  51851. get: function () {
  51852. return this._speedRatio;
  51853. },
  51854. set: function (value) {
  51855. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51856. var animation = this._runtimeAnimations[index];
  51857. animation._prepareForSpeedRatioChange(value);
  51858. }
  51859. this._speedRatio = value;
  51860. },
  51861. enumerable: true,
  51862. configurable: true
  51863. });
  51864. // Methods
  51865. /**
  51866. * Synchronize and normalize current Animatable with a source Animatable
  51867. * This is useful when using animation weights and when animations are not of the same length
  51868. * @param root defines the root Animatable to synchronize with
  51869. * @returns the current Animatable
  51870. */
  51871. Animatable.prototype.syncWith = function (root) {
  51872. this._syncRoot = root;
  51873. if (root) {
  51874. // Make sure this animatable will animate after the root
  51875. var index = this._scene._activeAnimatables.indexOf(this);
  51876. if (index > -1) {
  51877. this._scene._activeAnimatables.splice(index, 1);
  51878. this._scene._activeAnimatables.push(this);
  51879. }
  51880. }
  51881. return this;
  51882. };
  51883. /**
  51884. * Gets the list of runtime animations
  51885. * @returns an array of RuntimeAnimation
  51886. */
  51887. Animatable.prototype.getAnimations = function () {
  51888. return this._runtimeAnimations;
  51889. };
  51890. /**
  51891. * Adds more animations to the current animatable
  51892. * @param target defines the target of the animations
  51893. * @param animations defines the new animations to add
  51894. */
  51895. Animatable.prototype.appendAnimations = function (target, animations) {
  51896. for (var index = 0; index < animations.length; index++) {
  51897. var animation = animations[index];
  51898. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51899. }
  51900. };
  51901. /**
  51902. * Gets the source animation for a specific property
  51903. * @param property defines the propertyu to look for
  51904. * @returns null or the source animation for the given property
  51905. */
  51906. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51907. var runtimeAnimations = this._runtimeAnimations;
  51908. for (var index = 0; index < runtimeAnimations.length; index++) {
  51909. if (runtimeAnimations[index].animation.targetProperty === property) {
  51910. return runtimeAnimations[index].animation;
  51911. }
  51912. }
  51913. return null;
  51914. };
  51915. /**
  51916. * Gets the runtime animation for a specific property
  51917. * @param property defines the propertyu to look for
  51918. * @returns null or the runtime animation for the given property
  51919. */
  51920. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51921. var runtimeAnimations = this._runtimeAnimations;
  51922. for (var index = 0; index < runtimeAnimations.length; index++) {
  51923. if (runtimeAnimations[index].animation.targetProperty === property) {
  51924. return runtimeAnimations[index];
  51925. }
  51926. }
  51927. return null;
  51928. };
  51929. /**
  51930. * Resets the animatable to its original state
  51931. */
  51932. Animatable.prototype.reset = function () {
  51933. var runtimeAnimations = this._runtimeAnimations;
  51934. for (var index = 0; index < runtimeAnimations.length; index++) {
  51935. runtimeAnimations[index].reset(true);
  51936. }
  51937. this._localDelayOffset = null;
  51938. this._pausedDelay = null;
  51939. };
  51940. /**
  51941. * Allows the animatable to blend with current running animations
  51942. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51943. * @param blendingSpeed defines the blending speed to use
  51944. */
  51945. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51946. var runtimeAnimations = this._runtimeAnimations;
  51947. for (var index = 0; index < runtimeAnimations.length; index++) {
  51948. runtimeAnimations[index].animation.enableBlending = true;
  51949. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51950. }
  51951. };
  51952. /**
  51953. * Disable animation blending
  51954. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51955. */
  51956. Animatable.prototype.disableBlending = function () {
  51957. var runtimeAnimations = this._runtimeAnimations;
  51958. for (var index = 0; index < runtimeAnimations.length; index++) {
  51959. runtimeAnimations[index].animation.enableBlending = false;
  51960. }
  51961. };
  51962. /**
  51963. * Jump directly to a given frame
  51964. * @param frame defines the frame to jump to
  51965. */
  51966. Animatable.prototype.goToFrame = function (frame) {
  51967. var runtimeAnimations = this._runtimeAnimations;
  51968. if (runtimeAnimations[0]) {
  51969. var fps = runtimeAnimations[0].animation.framePerSecond;
  51970. var currentFrame = runtimeAnimations[0].currentFrame;
  51971. var adjustTime = frame - currentFrame;
  51972. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51973. if (this._localDelayOffset === null) {
  51974. this._localDelayOffset = 0;
  51975. }
  51976. this._localDelayOffset -= delay;
  51977. }
  51978. for (var index = 0; index < runtimeAnimations.length; index++) {
  51979. runtimeAnimations[index].goToFrame(frame);
  51980. }
  51981. };
  51982. /**
  51983. * Pause the animation
  51984. */
  51985. Animatable.prototype.pause = function () {
  51986. if (this._paused) {
  51987. return;
  51988. }
  51989. this._paused = true;
  51990. };
  51991. /**
  51992. * Restart the animation
  51993. */
  51994. Animatable.prototype.restart = function () {
  51995. this._paused = false;
  51996. };
  51997. Animatable.prototype._raiseOnAnimationEnd = function () {
  51998. if (this.onAnimationEnd) {
  51999. this.onAnimationEnd();
  52000. }
  52001. this.onAnimationEndObservable.notifyObservers(this);
  52002. };
  52003. /**
  52004. * Stop and delete the current animation
  52005. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52006. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  52007. */
  52008. Animatable.prototype.stop = function (animationName, targetMask) {
  52009. if (animationName || targetMask) {
  52010. var idx = this._scene._activeAnimatables.indexOf(this);
  52011. if (idx > -1) {
  52012. var runtimeAnimations = this._runtimeAnimations;
  52013. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52014. var runtimeAnimation = runtimeAnimations[index];
  52015. if (animationName && runtimeAnimation.animation.name != animationName) {
  52016. continue;
  52017. }
  52018. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52019. continue;
  52020. }
  52021. runtimeAnimation.dispose();
  52022. runtimeAnimations.splice(index, 1);
  52023. }
  52024. if (runtimeAnimations.length == 0) {
  52025. this._scene._activeAnimatables.splice(idx, 1);
  52026. this._raiseOnAnimationEnd();
  52027. }
  52028. }
  52029. }
  52030. else {
  52031. var index = this._scene._activeAnimatables.indexOf(this);
  52032. if (index > -1) {
  52033. this._scene._activeAnimatables.splice(index, 1);
  52034. var runtimeAnimations = this._runtimeAnimations;
  52035. for (var index = 0; index < runtimeAnimations.length; index++) {
  52036. runtimeAnimations[index].dispose();
  52037. }
  52038. this._raiseOnAnimationEnd();
  52039. }
  52040. }
  52041. };
  52042. /**
  52043. * Wait asynchronously for the animation to end
  52044. * @returns a promise which will be fullfilled when the animation ends
  52045. */
  52046. Animatable.prototype.waitAsync = function () {
  52047. var _this = this;
  52048. return new Promise(function (resolve, reject) {
  52049. _this.onAnimationEndObservable.add(function () {
  52050. resolve(_this);
  52051. }, undefined, undefined, _this, true);
  52052. });
  52053. };
  52054. /** @hidden */
  52055. Animatable.prototype._animate = function (delay) {
  52056. if (this._paused) {
  52057. this.animationStarted = false;
  52058. if (this._pausedDelay === null) {
  52059. this._pausedDelay = delay;
  52060. }
  52061. return true;
  52062. }
  52063. if (this._localDelayOffset === null) {
  52064. this._localDelayOffset = delay;
  52065. this._pausedDelay = null;
  52066. }
  52067. else if (this._pausedDelay !== null) {
  52068. this._localDelayOffset += delay - this._pausedDelay;
  52069. this._pausedDelay = null;
  52070. }
  52071. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52072. return true;
  52073. }
  52074. // Animating
  52075. var running = false;
  52076. var runtimeAnimations = this._runtimeAnimations;
  52077. var index;
  52078. for (index = 0; index < runtimeAnimations.length; index++) {
  52079. var animation = runtimeAnimations[index];
  52080. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52081. running = running || isRunning;
  52082. }
  52083. this.animationStarted = running;
  52084. if (!running) {
  52085. if (this.disposeOnEnd) {
  52086. // Remove from active animatables
  52087. index = this._scene._activeAnimatables.indexOf(this);
  52088. this._scene._activeAnimatables.splice(index, 1);
  52089. // Dispose all runtime animations
  52090. for (index = 0; index < runtimeAnimations.length; index++) {
  52091. runtimeAnimations[index].dispose();
  52092. }
  52093. }
  52094. this._raiseOnAnimationEnd();
  52095. if (this.disposeOnEnd) {
  52096. this.onAnimationEnd = null;
  52097. this.onAnimationEndObservable.clear();
  52098. }
  52099. }
  52100. return running;
  52101. };
  52102. return Animatable;
  52103. }());
  52104. BABYLON.Animatable = Animatable;
  52105. })(BABYLON || (BABYLON = {}));
  52106. //# sourceMappingURL=babylon.animatable.js.map
  52107. var BABYLON;
  52108. (function (BABYLON) {
  52109. var EasingFunction = /** @class */ (function () {
  52110. function EasingFunction() {
  52111. // Properties
  52112. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52113. }
  52114. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52115. get: function () {
  52116. return EasingFunction._EASINGMODE_EASEIN;
  52117. },
  52118. enumerable: true,
  52119. configurable: true
  52120. });
  52121. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52122. get: function () {
  52123. return EasingFunction._EASINGMODE_EASEOUT;
  52124. },
  52125. enumerable: true,
  52126. configurable: true
  52127. });
  52128. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52129. get: function () {
  52130. return EasingFunction._EASINGMODE_EASEINOUT;
  52131. },
  52132. enumerable: true,
  52133. configurable: true
  52134. });
  52135. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52136. var n = Math.min(Math.max(easingMode, 0), 2);
  52137. this._easingMode = n;
  52138. };
  52139. EasingFunction.prototype.getEasingMode = function () {
  52140. return this._easingMode;
  52141. };
  52142. EasingFunction.prototype.easeInCore = function (gradient) {
  52143. throw new Error('You must implement this method');
  52144. };
  52145. EasingFunction.prototype.ease = function (gradient) {
  52146. switch (this._easingMode) {
  52147. case EasingFunction.EASINGMODE_EASEIN:
  52148. return this.easeInCore(gradient);
  52149. case EasingFunction.EASINGMODE_EASEOUT:
  52150. return (1 - this.easeInCore(1 - gradient));
  52151. }
  52152. if (gradient >= 0.5) {
  52153. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52154. }
  52155. return (this.easeInCore(gradient * 2) * 0.5);
  52156. };
  52157. //Statics
  52158. EasingFunction._EASINGMODE_EASEIN = 0;
  52159. EasingFunction._EASINGMODE_EASEOUT = 1;
  52160. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52161. return EasingFunction;
  52162. }());
  52163. BABYLON.EasingFunction = EasingFunction;
  52164. var CircleEase = /** @class */ (function (_super) {
  52165. __extends(CircleEase, _super);
  52166. function CircleEase() {
  52167. return _super !== null && _super.apply(this, arguments) || this;
  52168. }
  52169. CircleEase.prototype.easeInCore = function (gradient) {
  52170. gradient = Math.max(0, Math.min(1, gradient));
  52171. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52172. };
  52173. return CircleEase;
  52174. }(EasingFunction));
  52175. BABYLON.CircleEase = CircleEase;
  52176. var BackEase = /** @class */ (function (_super) {
  52177. __extends(BackEase, _super);
  52178. function BackEase(amplitude) {
  52179. if (amplitude === void 0) { amplitude = 1; }
  52180. var _this = _super.call(this) || this;
  52181. _this.amplitude = amplitude;
  52182. return _this;
  52183. }
  52184. BackEase.prototype.easeInCore = function (gradient) {
  52185. var num = Math.max(0, this.amplitude);
  52186. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52187. };
  52188. return BackEase;
  52189. }(EasingFunction));
  52190. BABYLON.BackEase = BackEase;
  52191. var BounceEase = /** @class */ (function (_super) {
  52192. __extends(BounceEase, _super);
  52193. function BounceEase(bounces, bounciness) {
  52194. if (bounces === void 0) { bounces = 3; }
  52195. if (bounciness === void 0) { bounciness = 2; }
  52196. var _this = _super.call(this) || this;
  52197. _this.bounces = bounces;
  52198. _this.bounciness = bounciness;
  52199. return _this;
  52200. }
  52201. BounceEase.prototype.easeInCore = function (gradient) {
  52202. var y = Math.max(0.0, this.bounces);
  52203. var bounciness = this.bounciness;
  52204. if (bounciness <= 1.0) {
  52205. bounciness = 1.001;
  52206. }
  52207. var num9 = Math.pow(bounciness, y);
  52208. var num5 = 1.0 - bounciness;
  52209. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52210. var num15 = gradient * num4;
  52211. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52212. var num3 = Math.floor(num65);
  52213. var num13 = num3 + 1.0;
  52214. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52215. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52216. var num7 = (num8 + num12) * 0.5;
  52217. var num6 = gradient - num7;
  52218. var num2 = num7 - num8;
  52219. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52220. };
  52221. return BounceEase;
  52222. }(EasingFunction));
  52223. BABYLON.BounceEase = BounceEase;
  52224. var CubicEase = /** @class */ (function (_super) {
  52225. __extends(CubicEase, _super);
  52226. function CubicEase() {
  52227. return _super !== null && _super.apply(this, arguments) || this;
  52228. }
  52229. CubicEase.prototype.easeInCore = function (gradient) {
  52230. return (gradient * gradient * gradient);
  52231. };
  52232. return CubicEase;
  52233. }(EasingFunction));
  52234. BABYLON.CubicEase = CubicEase;
  52235. var ElasticEase = /** @class */ (function (_super) {
  52236. __extends(ElasticEase, _super);
  52237. function ElasticEase(oscillations, springiness) {
  52238. if (oscillations === void 0) { oscillations = 3; }
  52239. if (springiness === void 0) { springiness = 3; }
  52240. var _this = _super.call(this) || this;
  52241. _this.oscillations = oscillations;
  52242. _this.springiness = springiness;
  52243. return _this;
  52244. }
  52245. ElasticEase.prototype.easeInCore = function (gradient) {
  52246. var num2;
  52247. var num3 = Math.max(0.0, this.oscillations);
  52248. var num = Math.max(0.0, this.springiness);
  52249. if (num == 0) {
  52250. num2 = gradient;
  52251. }
  52252. else {
  52253. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52254. }
  52255. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52256. };
  52257. return ElasticEase;
  52258. }(EasingFunction));
  52259. BABYLON.ElasticEase = ElasticEase;
  52260. var ExponentialEase = /** @class */ (function (_super) {
  52261. __extends(ExponentialEase, _super);
  52262. function ExponentialEase(exponent) {
  52263. if (exponent === void 0) { exponent = 2; }
  52264. var _this = _super.call(this) || this;
  52265. _this.exponent = exponent;
  52266. return _this;
  52267. }
  52268. ExponentialEase.prototype.easeInCore = function (gradient) {
  52269. if (this.exponent <= 0) {
  52270. return gradient;
  52271. }
  52272. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52273. };
  52274. return ExponentialEase;
  52275. }(EasingFunction));
  52276. BABYLON.ExponentialEase = ExponentialEase;
  52277. var PowerEase = /** @class */ (function (_super) {
  52278. __extends(PowerEase, _super);
  52279. function PowerEase(power) {
  52280. if (power === void 0) { power = 2; }
  52281. var _this = _super.call(this) || this;
  52282. _this.power = power;
  52283. return _this;
  52284. }
  52285. PowerEase.prototype.easeInCore = function (gradient) {
  52286. var y = Math.max(0.0, this.power);
  52287. return Math.pow(gradient, y);
  52288. };
  52289. return PowerEase;
  52290. }(EasingFunction));
  52291. BABYLON.PowerEase = PowerEase;
  52292. var QuadraticEase = /** @class */ (function (_super) {
  52293. __extends(QuadraticEase, _super);
  52294. function QuadraticEase() {
  52295. return _super !== null && _super.apply(this, arguments) || this;
  52296. }
  52297. QuadraticEase.prototype.easeInCore = function (gradient) {
  52298. return (gradient * gradient);
  52299. };
  52300. return QuadraticEase;
  52301. }(EasingFunction));
  52302. BABYLON.QuadraticEase = QuadraticEase;
  52303. var QuarticEase = /** @class */ (function (_super) {
  52304. __extends(QuarticEase, _super);
  52305. function QuarticEase() {
  52306. return _super !== null && _super.apply(this, arguments) || this;
  52307. }
  52308. QuarticEase.prototype.easeInCore = function (gradient) {
  52309. return (gradient * gradient * gradient * gradient);
  52310. };
  52311. return QuarticEase;
  52312. }(EasingFunction));
  52313. BABYLON.QuarticEase = QuarticEase;
  52314. var QuinticEase = /** @class */ (function (_super) {
  52315. __extends(QuinticEase, _super);
  52316. function QuinticEase() {
  52317. return _super !== null && _super.apply(this, arguments) || this;
  52318. }
  52319. QuinticEase.prototype.easeInCore = function (gradient) {
  52320. return (gradient * gradient * gradient * gradient * gradient);
  52321. };
  52322. return QuinticEase;
  52323. }(EasingFunction));
  52324. BABYLON.QuinticEase = QuinticEase;
  52325. var SineEase = /** @class */ (function (_super) {
  52326. __extends(SineEase, _super);
  52327. function SineEase() {
  52328. return _super !== null && _super.apply(this, arguments) || this;
  52329. }
  52330. SineEase.prototype.easeInCore = function (gradient) {
  52331. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52332. };
  52333. return SineEase;
  52334. }(EasingFunction));
  52335. BABYLON.SineEase = SineEase;
  52336. var BezierCurveEase = /** @class */ (function (_super) {
  52337. __extends(BezierCurveEase, _super);
  52338. function BezierCurveEase(x1, y1, x2, y2) {
  52339. if (x1 === void 0) { x1 = 0; }
  52340. if (y1 === void 0) { y1 = 0; }
  52341. if (x2 === void 0) { x2 = 1; }
  52342. if (y2 === void 0) { y2 = 1; }
  52343. var _this = _super.call(this) || this;
  52344. _this.x1 = x1;
  52345. _this.y1 = y1;
  52346. _this.x2 = x2;
  52347. _this.y2 = y2;
  52348. return _this;
  52349. }
  52350. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52351. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52352. };
  52353. return BezierCurveEase;
  52354. }(EasingFunction));
  52355. BABYLON.BezierCurveEase = BezierCurveEase;
  52356. })(BABYLON || (BABYLON = {}));
  52357. //# sourceMappingURL=babylon.easing.js.map
  52358. var BABYLON;
  52359. (function (BABYLON) {
  52360. /**
  52361. * A Condition applied to an Action
  52362. */
  52363. var Condition = /** @class */ (function () {
  52364. /**
  52365. * Creates a new Condition
  52366. * @param actionManager the manager of the action the condition is applied to
  52367. */
  52368. function Condition(actionManager) {
  52369. this._actionManager = actionManager;
  52370. }
  52371. /**
  52372. * Check if the current condition is valid
  52373. * @returns a boolean
  52374. */
  52375. Condition.prototype.isValid = function () {
  52376. return true;
  52377. };
  52378. /**
  52379. * Internal only
  52380. * @hidden
  52381. */
  52382. Condition.prototype._getProperty = function (propertyPath) {
  52383. return this._actionManager._getProperty(propertyPath);
  52384. };
  52385. /**
  52386. * Internal only
  52387. * @hidden
  52388. */
  52389. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52390. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52391. };
  52392. /**
  52393. * Serialize placeholder for child classes
  52394. * @returns the serialized object
  52395. */
  52396. Condition.prototype.serialize = function () {
  52397. };
  52398. /**
  52399. * Internal only
  52400. * @hidden
  52401. */
  52402. Condition.prototype._serialize = function (serializedCondition) {
  52403. return {
  52404. type: 2,
  52405. children: [],
  52406. name: serializedCondition.name,
  52407. properties: serializedCondition.properties
  52408. };
  52409. };
  52410. return Condition;
  52411. }());
  52412. BABYLON.Condition = Condition;
  52413. /**
  52414. * Defines specific conditional operators as extensions of Condition
  52415. */
  52416. var ValueCondition = /** @class */ (function (_super) {
  52417. __extends(ValueCondition, _super);
  52418. /**
  52419. * Creates a new ValueCondition
  52420. * @param actionManager manager for the action the condition applies to
  52421. * @param target for the action
  52422. * @param propertyPath path to specify the property of the target the conditional operator uses
  52423. * @param value the value compared by the conditional operator against the current value of the property
  52424. * @param operator the conditional operator, default ValueCondition.IsEqual
  52425. */
  52426. function ValueCondition(actionManager, target,
  52427. /** path to specify the property of the target the conditional operator uses */
  52428. propertyPath,
  52429. /** the value compared by the conditional operator against the current value of the property */
  52430. value,
  52431. /** the conditional operator, default ValueCondition.IsEqual */
  52432. operator) {
  52433. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52434. var _this = _super.call(this, actionManager) || this;
  52435. _this.propertyPath = propertyPath;
  52436. _this.value = value;
  52437. _this.operator = operator;
  52438. _this._target = target;
  52439. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52440. _this._property = _this._getProperty(_this.propertyPath);
  52441. return _this;
  52442. }
  52443. Object.defineProperty(ValueCondition, "IsEqual", {
  52444. /**
  52445. * returns the number for IsEqual
  52446. */
  52447. get: function () {
  52448. return ValueCondition._IsEqual;
  52449. },
  52450. enumerable: true,
  52451. configurable: true
  52452. });
  52453. Object.defineProperty(ValueCondition, "IsDifferent", {
  52454. /**
  52455. * Returns the number for IsDifferent
  52456. */
  52457. get: function () {
  52458. return ValueCondition._IsDifferent;
  52459. },
  52460. enumerable: true,
  52461. configurable: true
  52462. });
  52463. Object.defineProperty(ValueCondition, "IsGreater", {
  52464. /**
  52465. * Returns the number for IsGreater
  52466. */
  52467. get: function () {
  52468. return ValueCondition._IsGreater;
  52469. },
  52470. enumerable: true,
  52471. configurable: true
  52472. });
  52473. Object.defineProperty(ValueCondition, "IsLesser", {
  52474. /**
  52475. * Returns the number for IsLesser
  52476. */
  52477. get: function () {
  52478. return ValueCondition._IsLesser;
  52479. },
  52480. enumerable: true,
  52481. configurable: true
  52482. });
  52483. /**
  52484. * Compares the given value with the property value for the specified conditional operator
  52485. * @returns the result of the comparison
  52486. */
  52487. ValueCondition.prototype.isValid = function () {
  52488. switch (this.operator) {
  52489. case ValueCondition.IsGreater:
  52490. return this._effectiveTarget[this._property] > this.value;
  52491. case ValueCondition.IsLesser:
  52492. return this._effectiveTarget[this._property] < this.value;
  52493. case ValueCondition.IsEqual:
  52494. case ValueCondition.IsDifferent:
  52495. var check;
  52496. if (this.value.equals) {
  52497. check = this.value.equals(this._effectiveTarget[this._property]);
  52498. }
  52499. else {
  52500. check = this.value === this._effectiveTarget[this._property];
  52501. }
  52502. return this.operator === ValueCondition.IsEqual ? check : !check;
  52503. }
  52504. return false;
  52505. };
  52506. /**
  52507. * Serialize the ValueCondition into a JSON compatible object
  52508. * @returns serialization object
  52509. */
  52510. ValueCondition.prototype.serialize = function () {
  52511. return this._serialize({
  52512. name: "ValueCondition",
  52513. properties: [
  52514. BABYLON.Action._GetTargetProperty(this._target),
  52515. { name: "propertyPath", value: this.propertyPath },
  52516. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52517. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52518. ]
  52519. });
  52520. };
  52521. /**
  52522. * Gets the name of the conditional operator for the ValueCondition
  52523. * @param operator the conditional operator
  52524. * @returns the name
  52525. */
  52526. ValueCondition.GetOperatorName = function (operator) {
  52527. switch (operator) {
  52528. case ValueCondition._IsEqual: return "IsEqual";
  52529. case ValueCondition._IsDifferent: return "IsDifferent";
  52530. case ValueCondition._IsGreater: return "IsGreater";
  52531. case ValueCondition._IsLesser: return "IsLesser";
  52532. default: return "";
  52533. }
  52534. };
  52535. /**
  52536. * Internal only
  52537. * @hidden
  52538. */
  52539. ValueCondition._IsEqual = 0;
  52540. /**
  52541. * Internal only
  52542. * @hidden
  52543. */
  52544. ValueCondition._IsDifferent = 1;
  52545. /**
  52546. * Internal only
  52547. * @hidden
  52548. */
  52549. ValueCondition._IsGreater = 2;
  52550. /**
  52551. * Internal only
  52552. * @hidden
  52553. */
  52554. ValueCondition._IsLesser = 3;
  52555. return ValueCondition;
  52556. }(Condition));
  52557. BABYLON.ValueCondition = ValueCondition;
  52558. /**
  52559. * Defines a predicate condition as an extension of Condition
  52560. */
  52561. var PredicateCondition = /** @class */ (function (_super) {
  52562. __extends(PredicateCondition, _super);
  52563. /**
  52564. * Creates a new PredicateCondition
  52565. * @param actionManager manager for the action the condition applies to
  52566. * @param predicate defines the predicate function used to validate the condition
  52567. */
  52568. function PredicateCondition(actionManager,
  52569. /** defines the predicate function used to validate the condition */
  52570. predicate) {
  52571. var _this = _super.call(this, actionManager) || this;
  52572. _this.predicate = predicate;
  52573. return _this;
  52574. }
  52575. /**
  52576. * @returns the validity of the predicate condition
  52577. */
  52578. PredicateCondition.prototype.isValid = function () {
  52579. return this.predicate();
  52580. };
  52581. return PredicateCondition;
  52582. }(Condition));
  52583. BABYLON.PredicateCondition = PredicateCondition;
  52584. /**
  52585. * Defines a state condition as an extension of Condition
  52586. */
  52587. var StateCondition = /** @class */ (function (_super) {
  52588. __extends(StateCondition, _super);
  52589. /**
  52590. * Creates a new StateCondition
  52591. * @param actionManager manager for the action the condition applies to
  52592. * @param target of the condition
  52593. * @param value to compare with target state
  52594. */
  52595. function StateCondition(actionManager, target, value) {
  52596. var _this = _super.call(this, actionManager) || this;
  52597. _this.value = value;
  52598. _this._target = target;
  52599. return _this;
  52600. }
  52601. /**
  52602. * @returns the validity of the state
  52603. */
  52604. StateCondition.prototype.isValid = function () {
  52605. return this._target.state === this.value;
  52606. };
  52607. /**
  52608. * Serialize the StateCondition into a JSON compatible object
  52609. * @returns serialization object
  52610. */
  52611. StateCondition.prototype.serialize = function () {
  52612. return this._serialize({
  52613. name: "StateCondition",
  52614. properties: [
  52615. BABYLON.Action._GetTargetProperty(this._target),
  52616. { name: "value", value: this.value }
  52617. ]
  52618. });
  52619. };
  52620. return StateCondition;
  52621. }(Condition));
  52622. BABYLON.StateCondition = StateCondition;
  52623. })(BABYLON || (BABYLON = {}));
  52624. //# sourceMappingURL=babylon.condition.js.map
  52625. var BABYLON;
  52626. (function (BABYLON) {
  52627. /**
  52628. * The action to be carried out following a trigger
  52629. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52630. */
  52631. var Action = /** @class */ (function () {
  52632. /**
  52633. * Creates a new Action
  52634. * @param triggerOptions the trigger, with or without parameters, for the action
  52635. * @param condition an optional determinant of action
  52636. */
  52637. function Action(
  52638. /** the trigger, with or without parameters, for the action */
  52639. triggerOptions, condition) {
  52640. this.triggerOptions = triggerOptions;
  52641. /**
  52642. * An event triggered prior to action being executed.
  52643. */
  52644. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52645. if (triggerOptions.parameter) {
  52646. this.trigger = triggerOptions.trigger;
  52647. this._triggerParameter = triggerOptions.parameter;
  52648. }
  52649. else {
  52650. this.trigger = triggerOptions;
  52651. }
  52652. this._nextActiveAction = this;
  52653. this._condition = condition;
  52654. }
  52655. /**
  52656. * Internal only
  52657. * @hidden
  52658. */
  52659. Action.prototype._prepare = function () {
  52660. };
  52661. /**
  52662. * Gets the trigger parameters
  52663. * @returns the trigger parameters
  52664. */
  52665. Action.prototype.getTriggerParameter = function () {
  52666. return this._triggerParameter;
  52667. };
  52668. /**
  52669. * Internal only - executes current action event
  52670. * @hidden
  52671. */
  52672. Action.prototype._executeCurrent = function (evt) {
  52673. if (this._nextActiveAction._condition) {
  52674. var condition = this._nextActiveAction._condition;
  52675. var currentRenderId = this._actionManager.getScene().getRenderId();
  52676. // We cache the current evaluation for the current frame
  52677. if (condition._evaluationId === currentRenderId) {
  52678. if (!condition._currentResult) {
  52679. return;
  52680. }
  52681. }
  52682. else {
  52683. condition._evaluationId = currentRenderId;
  52684. if (!condition.isValid()) {
  52685. condition._currentResult = false;
  52686. return;
  52687. }
  52688. condition._currentResult = true;
  52689. }
  52690. }
  52691. this.onBeforeExecuteObservable.notifyObservers(this);
  52692. this._nextActiveAction.execute(evt);
  52693. this.skipToNextActiveAction();
  52694. };
  52695. /**
  52696. * Execute placeholder for child classes
  52697. * @param evt optional action event
  52698. */
  52699. Action.prototype.execute = function (evt) {
  52700. };
  52701. /**
  52702. * Skips to next active action
  52703. */
  52704. Action.prototype.skipToNextActiveAction = function () {
  52705. if (this._nextActiveAction._child) {
  52706. if (!this._nextActiveAction._child._actionManager) {
  52707. this._nextActiveAction._child._actionManager = this._actionManager;
  52708. }
  52709. this._nextActiveAction = this._nextActiveAction._child;
  52710. }
  52711. else {
  52712. this._nextActiveAction = this;
  52713. }
  52714. };
  52715. /**
  52716. * Adds action to chain of actions, may be a DoNothingAction
  52717. * @param action defines the next action to execute
  52718. * @returns The action passed in
  52719. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52720. */
  52721. Action.prototype.then = function (action) {
  52722. this._child = action;
  52723. action._actionManager = this._actionManager;
  52724. action._prepare();
  52725. return action;
  52726. };
  52727. /**
  52728. * Internal only
  52729. * @hidden
  52730. */
  52731. Action.prototype._getProperty = function (propertyPath) {
  52732. return this._actionManager._getProperty(propertyPath);
  52733. };
  52734. /**
  52735. * Internal only
  52736. * @hidden
  52737. */
  52738. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52739. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52740. };
  52741. /**
  52742. * Serialize placeholder for child classes
  52743. * @param parent of child
  52744. * @returns the serialized object
  52745. */
  52746. Action.prototype.serialize = function (parent) {
  52747. };
  52748. /**
  52749. * Internal only called by serialize
  52750. * @hidden
  52751. */
  52752. Action.prototype._serialize = function (serializedAction, parent) {
  52753. var serializationObject = {
  52754. type: 1,
  52755. children: [],
  52756. name: serializedAction.name,
  52757. properties: serializedAction.properties || []
  52758. };
  52759. // Serialize child
  52760. if (this._child) {
  52761. this._child.serialize(serializationObject);
  52762. }
  52763. // Check if "this" has a condition
  52764. if (this._condition) {
  52765. var serializedCondition = this._condition.serialize();
  52766. serializedCondition.children.push(serializationObject);
  52767. if (parent) {
  52768. parent.children.push(serializedCondition);
  52769. }
  52770. return serializedCondition;
  52771. }
  52772. if (parent) {
  52773. parent.children.push(serializationObject);
  52774. }
  52775. return serializationObject;
  52776. };
  52777. /**
  52778. * Internal only
  52779. * @hidden
  52780. */
  52781. Action._SerializeValueAsString = function (value) {
  52782. if (typeof value === "number") {
  52783. return value.toString();
  52784. }
  52785. if (typeof value === "boolean") {
  52786. return value ? "true" : "false";
  52787. }
  52788. if (value instanceof BABYLON.Vector2) {
  52789. return value.x + ", " + value.y;
  52790. }
  52791. if (value instanceof BABYLON.Vector3) {
  52792. return value.x + ", " + value.y + ", " + value.z;
  52793. }
  52794. if (value instanceof BABYLON.Color3) {
  52795. return value.r + ", " + value.g + ", " + value.b;
  52796. }
  52797. if (value instanceof BABYLON.Color4) {
  52798. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52799. }
  52800. return value; // string
  52801. };
  52802. /**
  52803. * Internal only
  52804. * @hidden
  52805. */
  52806. Action._GetTargetProperty = function (target) {
  52807. return {
  52808. name: "target",
  52809. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52810. : target instanceof BABYLON.Light ? "LightProperties"
  52811. : target instanceof BABYLON.Camera ? "CameraProperties"
  52812. : "SceneProperties",
  52813. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52814. };
  52815. };
  52816. return Action;
  52817. }());
  52818. BABYLON.Action = Action;
  52819. })(BABYLON || (BABYLON = {}));
  52820. //# sourceMappingURL=babylon.action.js.map
  52821. var BABYLON;
  52822. (function (BABYLON) {
  52823. /**
  52824. * ActionEvent is the event being sent when an action is triggered.
  52825. */
  52826. var ActionEvent = /** @class */ (function () {
  52827. /**
  52828. * Creates a new ActionEvent
  52829. * @param source The mesh or sprite that triggered the action
  52830. * @param pointerX The X mouse cursor position at the time of the event
  52831. * @param pointerY The Y mouse cursor position at the time of the event
  52832. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52833. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52834. * @param additionalData additional data for the event
  52835. */
  52836. function ActionEvent(
  52837. /** The mesh or sprite that triggered the action */
  52838. source,
  52839. /** The X mouse cursor position at the time of the event */
  52840. pointerX,
  52841. /** The Y mouse cursor position at the time of the event */
  52842. pointerY,
  52843. /** The mesh that is currently pointed at (can be null) */
  52844. meshUnderPointer,
  52845. /** the original (browser) event that triggered the ActionEvent */
  52846. sourceEvent,
  52847. /** additional data for the event */
  52848. additionalData) {
  52849. this.source = source;
  52850. this.pointerX = pointerX;
  52851. this.pointerY = pointerY;
  52852. this.meshUnderPointer = meshUnderPointer;
  52853. this.sourceEvent = sourceEvent;
  52854. this.additionalData = additionalData;
  52855. }
  52856. /**
  52857. * Helper function to auto-create an ActionEvent from a source mesh.
  52858. * @param source The source mesh that triggered the event
  52859. * @param evt The original (browser) event
  52860. * @param additionalData additional data for the event
  52861. * @returns the new ActionEvent
  52862. */
  52863. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52864. var scene = source.getScene();
  52865. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52866. };
  52867. /**
  52868. * Helper function to auto-create an ActionEvent from a source sprite
  52869. * @param source The source sprite that triggered the event
  52870. * @param scene Scene associated with the sprite
  52871. * @param evt The original (browser) event
  52872. * @param additionalData additional data for the event
  52873. * @returns the new ActionEvent
  52874. */
  52875. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52876. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52877. };
  52878. /**
  52879. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52880. * @param scene the scene where the event occurred
  52881. * @param evt The original (browser) event
  52882. * @returns the new ActionEvent
  52883. */
  52884. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52885. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52886. };
  52887. /**
  52888. * Helper function to auto-create an ActionEvent from a primitive
  52889. * @param prim defines the target primitive
  52890. * @param pointerPos defines the pointer position
  52891. * @param evt The original (browser) event
  52892. * @param additionalData additional data for the event
  52893. * @returns the new ActionEvent
  52894. */
  52895. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52896. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52897. };
  52898. return ActionEvent;
  52899. }());
  52900. BABYLON.ActionEvent = ActionEvent;
  52901. /**
  52902. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52903. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52904. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52905. */
  52906. var ActionManager = /** @class */ (function () {
  52907. /**
  52908. * Creates a new action manager
  52909. * @param scene defines the hosting scene
  52910. */
  52911. function ActionManager(scene) {
  52912. // Members
  52913. /** Gets the list of actions */
  52914. this.actions = new Array();
  52915. /** Gets the cursor to use when hovering items */
  52916. this.hoverCursor = '';
  52917. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52918. scene.actionManagers.push(this);
  52919. }
  52920. Object.defineProperty(ActionManager, "NothingTrigger", {
  52921. /**
  52922. * Nothing
  52923. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52924. */
  52925. get: function () {
  52926. return ActionManager._NothingTrigger;
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52932. /**
  52933. * On pick
  52934. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52935. */
  52936. get: function () {
  52937. return ActionManager._OnPickTrigger;
  52938. },
  52939. enumerable: true,
  52940. configurable: true
  52941. });
  52942. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52943. /**
  52944. * On left pick
  52945. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52946. */
  52947. get: function () {
  52948. return ActionManager._OnLeftPickTrigger;
  52949. },
  52950. enumerable: true,
  52951. configurable: true
  52952. });
  52953. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52954. /**
  52955. * On right pick
  52956. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52957. */
  52958. get: function () {
  52959. return ActionManager._OnRightPickTrigger;
  52960. },
  52961. enumerable: true,
  52962. configurable: true
  52963. });
  52964. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52965. /**
  52966. * On center pick
  52967. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52968. */
  52969. get: function () {
  52970. return ActionManager._OnCenterPickTrigger;
  52971. },
  52972. enumerable: true,
  52973. configurable: true
  52974. });
  52975. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52976. /**
  52977. * On pick down
  52978. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52979. */
  52980. get: function () {
  52981. return ActionManager._OnPickDownTrigger;
  52982. },
  52983. enumerable: true,
  52984. configurable: true
  52985. });
  52986. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52987. /**
  52988. * On double pick
  52989. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52990. */
  52991. get: function () {
  52992. return ActionManager._OnDoublePickTrigger;
  52993. },
  52994. enumerable: true,
  52995. configurable: true
  52996. });
  52997. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52998. /**
  52999. * On pick up
  53000. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53001. */
  53002. get: function () {
  53003. return ActionManager._OnPickUpTrigger;
  53004. },
  53005. enumerable: true,
  53006. configurable: true
  53007. });
  53008. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53009. /**
  53010. * On pick out.
  53011. * This trigger will only be raised if you also declared a OnPickDown
  53012. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53013. */
  53014. get: function () {
  53015. return ActionManager._OnPickOutTrigger;
  53016. },
  53017. enumerable: true,
  53018. configurable: true
  53019. });
  53020. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53021. /**
  53022. * On long press
  53023. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53024. */
  53025. get: function () {
  53026. return ActionManager._OnLongPressTrigger;
  53027. },
  53028. enumerable: true,
  53029. configurable: true
  53030. });
  53031. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53032. /**
  53033. * On pointer over
  53034. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53035. */
  53036. get: function () {
  53037. return ActionManager._OnPointerOverTrigger;
  53038. },
  53039. enumerable: true,
  53040. configurable: true
  53041. });
  53042. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53043. /**
  53044. * On pointer out
  53045. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53046. */
  53047. get: function () {
  53048. return ActionManager._OnPointerOutTrigger;
  53049. },
  53050. enumerable: true,
  53051. configurable: true
  53052. });
  53053. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53054. /**
  53055. * On every frame
  53056. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53057. */
  53058. get: function () {
  53059. return ActionManager._OnEveryFrameTrigger;
  53060. },
  53061. enumerable: true,
  53062. configurable: true
  53063. });
  53064. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53065. /**
  53066. * On intersection enter
  53067. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53068. */
  53069. get: function () {
  53070. return ActionManager._OnIntersectionEnterTrigger;
  53071. },
  53072. enumerable: true,
  53073. configurable: true
  53074. });
  53075. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53076. /**
  53077. * On intersection exit
  53078. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53079. */
  53080. get: function () {
  53081. return ActionManager._OnIntersectionExitTrigger;
  53082. },
  53083. enumerable: true,
  53084. configurable: true
  53085. });
  53086. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53087. /**
  53088. * On key down
  53089. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53090. */
  53091. get: function () {
  53092. return ActionManager._OnKeyDownTrigger;
  53093. },
  53094. enumerable: true,
  53095. configurable: true
  53096. });
  53097. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53098. /**
  53099. * On key up
  53100. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53101. */
  53102. get: function () {
  53103. return ActionManager._OnKeyUpTrigger;
  53104. },
  53105. enumerable: true,
  53106. configurable: true
  53107. });
  53108. // Methods
  53109. /**
  53110. * Releases all associated resources
  53111. */
  53112. ActionManager.prototype.dispose = function () {
  53113. var index = this._scene.actionManagers.indexOf(this);
  53114. for (var i = 0; i < this.actions.length; i++) {
  53115. var action = this.actions[i];
  53116. ActionManager.Triggers[action.trigger]--;
  53117. if (ActionManager.Triggers[action.trigger] === 0) {
  53118. delete ActionManager.Triggers[action.trigger];
  53119. }
  53120. }
  53121. if (index > -1) {
  53122. this._scene.actionManagers.splice(index, 1);
  53123. }
  53124. };
  53125. /**
  53126. * Gets hosting scene
  53127. * @returns the hosting scene
  53128. */
  53129. ActionManager.prototype.getScene = function () {
  53130. return this._scene;
  53131. };
  53132. /**
  53133. * Does this action manager handles actions of any of the given triggers
  53134. * @param triggers defines the triggers to be tested
  53135. * @return a boolean indicating whether one (or more) of the triggers is handled
  53136. */
  53137. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53138. for (var index = 0; index < this.actions.length; index++) {
  53139. var action = this.actions[index];
  53140. if (triggers.indexOf(action.trigger) > -1) {
  53141. return true;
  53142. }
  53143. }
  53144. return false;
  53145. };
  53146. /**
  53147. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53148. * speed.
  53149. * @param triggerA defines the trigger to be tested
  53150. * @param triggerB defines the trigger to be tested
  53151. * @return a boolean indicating whether one (or more) of the triggers is handled
  53152. */
  53153. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53154. for (var index = 0; index < this.actions.length; index++) {
  53155. var action = this.actions[index];
  53156. if (triggerA == action.trigger || triggerB == action.trigger) {
  53157. return true;
  53158. }
  53159. }
  53160. return false;
  53161. };
  53162. /**
  53163. * Does this action manager handles actions of a given trigger
  53164. * @param trigger defines the trigger to be tested
  53165. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53166. * @return whether the trigger is handled
  53167. */
  53168. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53169. for (var index = 0; index < this.actions.length; index++) {
  53170. var action = this.actions[index];
  53171. if (action.trigger === trigger) {
  53172. if (parameterPredicate) {
  53173. if (parameterPredicate(action.getTriggerParameter())) {
  53174. return true;
  53175. }
  53176. }
  53177. else {
  53178. return true;
  53179. }
  53180. }
  53181. }
  53182. return false;
  53183. };
  53184. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53185. /**
  53186. * Does this action manager has pointer triggers
  53187. */
  53188. get: function () {
  53189. for (var index = 0; index < this.actions.length; index++) {
  53190. var action = this.actions[index];
  53191. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53192. return true;
  53193. }
  53194. }
  53195. return false;
  53196. },
  53197. enumerable: true,
  53198. configurable: true
  53199. });
  53200. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53201. /**
  53202. * Does this action manager has pick triggers
  53203. */
  53204. get: function () {
  53205. for (var index = 0; index < this.actions.length; index++) {
  53206. var action = this.actions[index];
  53207. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53208. return true;
  53209. }
  53210. }
  53211. return false;
  53212. },
  53213. enumerable: true,
  53214. configurable: true
  53215. });
  53216. Object.defineProperty(ActionManager, "HasTriggers", {
  53217. /**
  53218. * Does exist one action manager with at least one trigger
  53219. **/
  53220. get: function () {
  53221. for (var t in ActionManager.Triggers) {
  53222. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53223. return true;
  53224. }
  53225. }
  53226. return false;
  53227. },
  53228. enumerable: true,
  53229. configurable: true
  53230. });
  53231. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53232. /**
  53233. * Does exist one action manager with at least one pick trigger
  53234. **/
  53235. get: function () {
  53236. for (var t in ActionManager.Triggers) {
  53237. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53238. var t_int = parseInt(t);
  53239. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53240. return true;
  53241. }
  53242. }
  53243. }
  53244. return false;
  53245. },
  53246. enumerable: true,
  53247. configurable: true
  53248. });
  53249. /**
  53250. * Does exist one action manager that handles actions of a given trigger
  53251. * @param trigger defines the trigger to be tested
  53252. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53253. **/
  53254. ActionManager.HasSpecificTrigger = function (trigger) {
  53255. for (var t in ActionManager.Triggers) {
  53256. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53257. var t_int = parseInt(t);
  53258. if (t_int === trigger) {
  53259. return true;
  53260. }
  53261. }
  53262. }
  53263. return false;
  53264. };
  53265. /**
  53266. * Registers an action to this action manager
  53267. * @param action defines the action to be registered
  53268. * @return the action amended (prepared) after registration
  53269. */
  53270. ActionManager.prototype.registerAction = function (action) {
  53271. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53272. if (this.getScene().actionManager !== this) {
  53273. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53274. return null;
  53275. }
  53276. }
  53277. this.actions.push(action);
  53278. if (ActionManager.Triggers[action.trigger]) {
  53279. ActionManager.Triggers[action.trigger]++;
  53280. }
  53281. else {
  53282. ActionManager.Triggers[action.trigger] = 1;
  53283. }
  53284. action._actionManager = this;
  53285. action._prepare();
  53286. return action;
  53287. };
  53288. /**
  53289. * Unregisters an action to this action manager
  53290. * @param action defines the action to be unregistered
  53291. * @return a boolean indicating whether the action has been unregistered
  53292. */
  53293. ActionManager.prototype.unregisterAction = function (action) {
  53294. var index = this.actions.indexOf(action);
  53295. if (index !== -1) {
  53296. this.actions.splice(index, 1);
  53297. ActionManager.Triggers[action.trigger] -= 1;
  53298. if (ActionManager.Triggers[action.trigger] === 0) {
  53299. delete ActionManager.Triggers[action.trigger];
  53300. }
  53301. delete action._actionManager;
  53302. return true;
  53303. }
  53304. return false;
  53305. };
  53306. /**
  53307. * Process a specific trigger
  53308. * @param trigger defines the trigger to process
  53309. * @param evt defines the event details to be processed
  53310. */
  53311. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53312. for (var index = 0; index < this.actions.length; index++) {
  53313. var action = this.actions[index];
  53314. if (action.trigger === trigger) {
  53315. if (evt) {
  53316. if (trigger === ActionManager.OnKeyUpTrigger
  53317. || trigger === ActionManager.OnKeyDownTrigger) {
  53318. var parameter = action.getTriggerParameter();
  53319. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53320. if (!parameter.toLowerCase) {
  53321. continue;
  53322. }
  53323. var lowerCase = parameter.toLowerCase();
  53324. if (lowerCase !== evt.sourceEvent.key) {
  53325. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53326. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53327. if (actualkey !== lowerCase) {
  53328. continue;
  53329. }
  53330. }
  53331. }
  53332. }
  53333. }
  53334. action._executeCurrent(evt);
  53335. }
  53336. }
  53337. };
  53338. /** @hidden */
  53339. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53340. var properties = propertyPath.split(".");
  53341. for (var index = 0; index < properties.length - 1; index++) {
  53342. target = target[properties[index]];
  53343. }
  53344. return target;
  53345. };
  53346. /** @hidden */
  53347. ActionManager.prototype._getProperty = function (propertyPath) {
  53348. var properties = propertyPath.split(".");
  53349. return properties[properties.length - 1];
  53350. };
  53351. /**
  53352. * Serialize this manager to a JSON object
  53353. * @param name defines the property name to store this manager
  53354. * @returns a JSON representation of this manager
  53355. */
  53356. ActionManager.prototype.serialize = function (name) {
  53357. var root = {
  53358. children: new Array(),
  53359. name: name,
  53360. type: 3,
  53361. properties: new Array() // Empty for root but required
  53362. };
  53363. for (var i = 0; i < this.actions.length; i++) {
  53364. var triggerObject = {
  53365. type: 0,
  53366. children: new Array(),
  53367. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53368. properties: new Array()
  53369. };
  53370. var triggerOptions = this.actions[i].triggerOptions;
  53371. if (triggerOptions && typeof triggerOptions !== "number") {
  53372. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53373. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53374. }
  53375. else {
  53376. var parameter = {};
  53377. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53378. if (triggerOptions.parameter.mesh) {
  53379. parameter._meshId = triggerOptions.parameter.mesh.id;
  53380. }
  53381. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53382. }
  53383. }
  53384. // Serialize child action, recursively
  53385. this.actions[i].serialize(triggerObject);
  53386. // Add serialized trigger
  53387. root.children.push(triggerObject);
  53388. }
  53389. return root;
  53390. };
  53391. /**
  53392. * Creates a new ActionManager from a JSON data
  53393. * @param parsedActions defines the JSON data to read from
  53394. * @param object defines the hosting mesh
  53395. * @param scene defines the hosting scene
  53396. */
  53397. ActionManager.Parse = function (parsedActions, object, scene) {
  53398. var actionManager = new ActionManager(scene);
  53399. if (object === null)
  53400. scene.actionManager = actionManager;
  53401. else
  53402. object.actionManager = actionManager;
  53403. // instanciate a new object
  53404. var instanciate = function (name, params) {
  53405. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53406. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53407. newInstance.constructor.apply(newInstance, params);
  53408. return newInstance;
  53409. };
  53410. var parseParameter = function (name, value, target, propertyPath) {
  53411. if (propertyPath === null) {
  53412. // String, boolean or float
  53413. var floatValue = parseFloat(value);
  53414. if (value === "true" || value === "false")
  53415. return value === "true";
  53416. else
  53417. return isNaN(floatValue) ? value : floatValue;
  53418. }
  53419. var effectiveTarget = propertyPath.split(".");
  53420. var values = value.split(",");
  53421. // Get effective Target
  53422. for (var i = 0; i < effectiveTarget.length; i++) {
  53423. target = target[effectiveTarget[i]];
  53424. }
  53425. // Return appropriate value with its type
  53426. if (typeof (target) === "boolean")
  53427. return values[0] === "true";
  53428. if (typeof (target) === "string")
  53429. return values[0];
  53430. // Parameters with multiple values such as Vector3 etc.
  53431. var split = new Array();
  53432. for (var i = 0; i < values.length; i++)
  53433. split.push(parseFloat(values[i]));
  53434. if (target instanceof BABYLON.Vector3)
  53435. return BABYLON.Vector3.FromArray(split);
  53436. if (target instanceof BABYLON.Vector4)
  53437. return BABYLON.Vector4.FromArray(split);
  53438. if (target instanceof BABYLON.Color3)
  53439. return BABYLON.Color3.FromArray(split);
  53440. if (target instanceof BABYLON.Color4)
  53441. return BABYLON.Color4.FromArray(split);
  53442. return parseFloat(values[0]);
  53443. };
  53444. // traverse graph per trigger
  53445. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53446. if (combineArray === void 0) { combineArray = null; }
  53447. if (parsedAction.detached)
  53448. return;
  53449. var parameters = new Array();
  53450. var target = null;
  53451. var propertyPath = null;
  53452. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53453. // Parameters
  53454. if (parsedAction.type === 2)
  53455. parameters.push(actionManager);
  53456. else
  53457. parameters.push(trigger);
  53458. if (combine) {
  53459. var actions = new Array();
  53460. for (var j = 0; j < parsedAction.combine.length; j++) {
  53461. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53462. }
  53463. parameters.push(actions);
  53464. }
  53465. else {
  53466. for (var i = 0; i < parsedAction.properties.length; i++) {
  53467. var value = parsedAction.properties[i].value;
  53468. var name = parsedAction.properties[i].name;
  53469. var targetType = parsedAction.properties[i].targetType;
  53470. if (name === "target")
  53471. if (targetType !== null && targetType === "SceneProperties")
  53472. value = target = scene;
  53473. else
  53474. value = target = scene.getNodeByName(value);
  53475. else if (name === "parent")
  53476. value = scene.getNodeByName(value);
  53477. else if (name === "sound")
  53478. value = scene.getSoundByName(value);
  53479. else if (name !== "propertyPath") {
  53480. if (parsedAction.type === 2 && name === "operator")
  53481. value = BABYLON.ValueCondition[value];
  53482. else
  53483. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53484. }
  53485. else {
  53486. propertyPath = value;
  53487. }
  53488. parameters.push(value);
  53489. }
  53490. }
  53491. if (combineArray === null) {
  53492. parameters.push(condition);
  53493. }
  53494. else {
  53495. parameters.push(null);
  53496. }
  53497. // If interpolate value action
  53498. if (parsedAction.name === "InterpolateValueAction") {
  53499. var param = parameters[parameters.length - 2];
  53500. parameters[parameters.length - 1] = param;
  53501. parameters[parameters.length - 2] = condition;
  53502. }
  53503. // Action or condition(s) and not CombineAction
  53504. var newAction = instanciate(parsedAction.name, parameters);
  53505. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53506. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53507. if (action)
  53508. action.then(nothing);
  53509. else
  53510. actionManager.registerAction(nothing);
  53511. action = nothing;
  53512. }
  53513. if (combineArray === null) {
  53514. if (newAction instanceof BABYLON.Condition) {
  53515. condition = newAction;
  53516. newAction = action;
  53517. }
  53518. else {
  53519. condition = null;
  53520. if (action)
  53521. action.then(newAction);
  53522. else
  53523. actionManager.registerAction(newAction);
  53524. }
  53525. }
  53526. else {
  53527. combineArray.push(newAction);
  53528. }
  53529. for (var i = 0; i < parsedAction.children.length; i++)
  53530. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53531. };
  53532. // triggers
  53533. for (var i = 0; i < parsedActions.children.length; i++) {
  53534. var triggerParams;
  53535. var trigger = parsedActions.children[i];
  53536. if (trigger.properties.length > 0) {
  53537. var param = trigger.properties[0].value;
  53538. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53539. if (value._meshId) {
  53540. value.mesh = scene.getMeshByID(value._meshId);
  53541. }
  53542. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53543. }
  53544. else
  53545. triggerParams = ActionManager[trigger.name];
  53546. for (var j = 0; j < trigger.children.length; j++) {
  53547. if (!trigger.detached)
  53548. traverse(trigger.children[j], triggerParams, null, null);
  53549. }
  53550. }
  53551. };
  53552. /**
  53553. * Get a trigger name by index
  53554. * @param trigger defines the trigger index
  53555. * @returns a trigger name
  53556. */
  53557. ActionManager.GetTriggerName = function (trigger) {
  53558. switch (trigger) {
  53559. case 0: return "NothingTrigger";
  53560. case 1: return "OnPickTrigger";
  53561. case 2: return "OnLeftPickTrigger";
  53562. case 3: return "OnRightPickTrigger";
  53563. case 4: return "OnCenterPickTrigger";
  53564. case 5: return "OnPickDownTrigger";
  53565. case 6: return "OnPickUpTrigger";
  53566. case 7: return "OnLongPressTrigger";
  53567. case 8: return "OnPointerOverTrigger";
  53568. case 9: return "OnPointerOutTrigger";
  53569. case 10: return "OnEveryFrameTrigger";
  53570. case 11: return "OnIntersectionEnterTrigger";
  53571. case 12: return "OnIntersectionExitTrigger";
  53572. case 13: return "OnKeyDownTrigger";
  53573. case 14: return "OnKeyUpTrigger";
  53574. case 15: return "OnPickOutTrigger";
  53575. default: return "";
  53576. }
  53577. };
  53578. // Statics
  53579. ActionManager._NothingTrigger = 0;
  53580. ActionManager._OnPickTrigger = 1;
  53581. ActionManager._OnLeftPickTrigger = 2;
  53582. ActionManager._OnRightPickTrigger = 3;
  53583. ActionManager._OnCenterPickTrigger = 4;
  53584. ActionManager._OnPickDownTrigger = 5;
  53585. ActionManager._OnDoublePickTrigger = 6;
  53586. ActionManager._OnPickUpTrigger = 7;
  53587. ActionManager._OnLongPressTrigger = 8;
  53588. ActionManager._OnPointerOverTrigger = 9;
  53589. ActionManager._OnPointerOutTrigger = 10;
  53590. ActionManager._OnEveryFrameTrigger = 11;
  53591. ActionManager._OnIntersectionEnterTrigger = 12;
  53592. ActionManager._OnIntersectionExitTrigger = 13;
  53593. ActionManager._OnKeyDownTrigger = 14;
  53594. ActionManager._OnKeyUpTrigger = 15;
  53595. ActionManager._OnPickOutTrigger = 16;
  53596. /** Gets the list of active triggers */
  53597. ActionManager.Triggers = {};
  53598. return ActionManager;
  53599. }());
  53600. BABYLON.ActionManager = ActionManager;
  53601. })(BABYLON || (BABYLON = {}));
  53602. //# sourceMappingURL=babylon.actionManager.js.map
  53603. var BABYLON;
  53604. (function (BABYLON) {
  53605. var InterpolateValueAction = /** @class */ (function (_super) {
  53606. __extends(InterpolateValueAction, _super);
  53607. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53608. if (duration === void 0) { duration = 1000; }
  53609. var _this = _super.call(this, triggerOptions, condition) || this;
  53610. _this.propertyPath = propertyPath;
  53611. _this.value = value;
  53612. _this.duration = duration;
  53613. _this.stopOtherAnimations = stopOtherAnimations;
  53614. _this.onInterpolationDone = onInterpolationDone;
  53615. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53616. _this._target = _this._effectiveTarget = target;
  53617. return _this;
  53618. }
  53619. /** @hidden */
  53620. InterpolateValueAction.prototype._prepare = function () {
  53621. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53622. this._property = this._getProperty(this.propertyPath);
  53623. };
  53624. InterpolateValueAction.prototype.execute = function () {
  53625. var _this = this;
  53626. var scene = this._actionManager.getScene();
  53627. var keys = [
  53628. {
  53629. frame: 0,
  53630. value: this._effectiveTarget[this._property]
  53631. }, {
  53632. frame: 100,
  53633. value: this.value
  53634. }
  53635. ];
  53636. var dataType;
  53637. if (typeof this.value === "number") {
  53638. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53639. }
  53640. else if (this.value instanceof BABYLON.Color3) {
  53641. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53642. }
  53643. else if (this.value instanceof BABYLON.Vector3) {
  53644. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53645. }
  53646. else if (this.value instanceof BABYLON.Matrix) {
  53647. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53648. }
  53649. else if (this.value instanceof BABYLON.Quaternion) {
  53650. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53651. }
  53652. else {
  53653. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53654. return;
  53655. }
  53656. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53657. animation.setKeys(keys);
  53658. if (this.stopOtherAnimations) {
  53659. scene.stopAnimation(this._effectiveTarget);
  53660. }
  53661. var wrapper = function () {
  53662. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53663. if (_this.onInterpolationDone) {
  53664. _this.onInterpolationDone();
  53665. }
  53666. };
  53667. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53668. };
  53669. InterpolateValueAction.prototype.serialize = function (parent) {
  53670. return _super.prototype._serialize.call(this, {
  53671. name: "InterpolateValueAction",
  53672. properties: [
  53673. BABYLON.Action._GetTargetProperty(this._target),
  53674. { name: "propertyPath", value: this.propertyPath },
  53675. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53676. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53677. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53678. ]
  53679. }, parent);
  53680. };
  53681. return InterpolateValueAction;
  53682. }(BABYLON.Action));
  53683. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53684. })(BABYLON || (BABYLON = {}));
  53685. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53686. var BABYLON;
  53687. (function (BABYLON) {
  53688. var SwitchBooleanAction = /** @class */ (function (_super) {
  53689. __extends(SwitchBooleanAction, _super);
  53690. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53691. var _this = _super.call(this, triggerOptions, condition) || this;
  53692. _this.propertyPath = propertyPath;
  53693. _this._target = _this._effectiveTarget = target;
  53694. return _this;
  53695. }
  53696. /** @hidden */
  53697. SwitchBooleanAction.prototype._prepare = function () {
  53698. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53699. this._property = this._getProperty(this.propertyPath);
  53700. };
  53701. SwitchBooleanAction.prototype.execute = function () {
  53702. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53703. };
  53704. SwitchBooleanAction.prototype.serialize = function (parent) {
  53705. return _super.prototype._serialize.call(this, {
  53706. name: "SwitchBooleanAction",
  53707. properties: [
  53708. BABYLON.Action._GetTargetProperty(this._target),
  53709. { name: "propertyPath", value: this.propertyPath }
  53710. ]
  53711. }, parent);
  53712. };
  53713. return SwitchBooleanAction;
  53714. }(BABYLON.Action));
  53715. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53716. var SetStateAction = /** @class */ (function (_super) {
  53717. __extends(SetStateAction, _super);
  53718. function SetStateAction(triggerOptions, target, value, condition) {
  53719. var _this = _super.call(this, triggerOptions, condition) || this;
  53720. _this.value = value;
  53721. _this._target = target;
  53722. return _this;
  53723. }
  53724. SetStateAction.prototype.execute = function () {
  53725. this._target.state = this.value;
  53726. };
  53727. SetStateAction.prototype.serialize = function (parent) {
  53728. return _super.prototype._serialize.call(this, {
  53729. name: "SetStateAction",
  53730. properties: [
  53731. BABYLON.Action._GetTargetProperty(this._target),
  53732. { name: "value", value: this.value }
  53733. ]
  53734. }, parent);
  53735. };
  53736. return SetStateAction;
  53737. }(BABYLON.Action));
  53738. BABYLON.SetStateAction = SetStateAction;
  53739. var SetValueAction = /** @class */ (function (_super) {
  53740. __extends(SetValueAction, _super);
  53741. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53742. var _this = _super.call(this, triggerOptions, condition) || this;
  53743. _this.propertyPath = propertyPath;
  53744. _this.value = value;
  53745. _this._target = _this._effectiveTarget = target;
  53746. return _this;
  53747. }
  53748. /** @hidden */
  53749. SetValueAction.prototype._prepare = function () {
  53750. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53751. this._property = this._getProperty(this.propertyPath);
  53752. };
  53753. SetValueAction.prototype.execute = function () {
  53754. this._effectiveTarget[this._property] = this.value;
  53755. if (this._target.markAsDirty) {
  53756. this._target.markAsDirty(this._property);
  53757. }
  53758. };
  53759. SetValueAction.prototype.serialize = function (parent) {
  53760. return _super.prototype._serialize.call(this, {
  53761. name: "SetValueAction",
  53762. properties: [
  53763. BABYLON.Action._GetTargetProperty(this._target),
  53764. { name: "propertyPath", value: this.propertyPath },
  53765. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53766. ]
  53767. }, parent);
  53768. };
  53769. return SetValueAction;
  53770. }(BABYLON.Action));
  53771. BABYLON.SetValueAction = SetValueAction;
  53772. var IncrementValueAction = /** @class */ (function (_super) {
  53773. __extends(IncrementValueAction, _super);
  53774. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53775. var _this = _super.call(this, triggerOptions, condition) || this;
  53776. _this.propertyPath = propertyPath;
  53777. _this.value = value;
  53778. _this._target = _this._effectiveTarget = target;
  53779. return _this;
  53780. }
  53781. /** @hidden */
  53782. IncrementValueAction.prototype._prepare = function () {
  53783. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53784. this._property = this._getProperty(this.propertyPath);
  53785. if (typeof this._effectiveTarget[this._property] !== "number") {
  53786. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53787. }
  53788. };
  53789. IncrementValueAction.prototype.execute = function () {
  53790. this._effectiveTarget[this._property] += this.value;
  53791. if (this._target.markAsDirty) {
  53792. this._target.markAsDirty(this._property);
  53793. }
  53794. };
  53795. IncrementValueAction.prototype.serialize = function (parent) {
  53796. return _super.prototype._serialize.call(this, {
  53797. name: "IncrementValueAction",
  53798. properties: [
  53799. BABYLON.Action._GetTargetProperty(this._target),
  53800. { name: "propertyPath", value: this.propertyPath },
  53801. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53802. ]
  53803. }, parent);
  53804. };
  53805. return IncrementValueAction;
  53806. }(BABYLON.Action));
  53807. BABYLON.IncrementValueAction = IncrementValueAction;
  53808. var PlayAnimationAction = /** @class */ (function (_super) {
  53809. __extends(PlayAnimationAction, _super);
  53810. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53811. var _this = _super.call(this, triggerOptions, condition) || this;
  53812. _this.from = from;
  53813. _this.to = to;
  53814. _this.loop = loop;
  53815. _this._target = target;
  53816. return _this;
  53817. }
  53818. /** @hidden */
  53819. PlayAnimationAction.prototype._prepare = function () {
  53820. };
  53821. PlayAnimationAction.prototype.execute = function () {
  53822. var scene = this._actionManager.getScene();
  53823. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53824. };
  53825. PlayAnimationAction.prototype.serialize = function (parent) {
  53826. return _super.prototype._serialize.call(this, {
  53827. name: "PlayAnimationAction",
  53828. properties: [
  53829. BABYLON.Action._GetTargetProperty(this._target),
  53830. { name: "from", value: String(this.from) },
  53831. { name: "to", value: String(this.to) },
  53832. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53833. ]
  53834. }, parent);
  53835. };
  53836. return PlayAnimationAction;
  53837. }(BABYLON.Action));
  53838. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53839. var StopAnimationAction = /** @class */ (function (_super) {
  53840. __extends(StopAnimationAction, _super);
  53841. function StopAnimationAction(triggerOptions, target, condition) {
  53842. var _this = _super.call(this, triggerOptions, condition) || this;
  53843. _this._target = target;
  53844. return _this;
  53845. }
  53846. /** @hidden */
  53847. StopAnimationAction.prototype._prepare = function () {
  53848. };
  53849. StopAnimationAction.prototype.execute = function () {
  53850. var scene = this._actionManager.getScene();
  53851. scene.stopAnimation(this._target);
  53852. };
  53853. StopAnimationAction.prototype.serialize = function (parent) {
  53854. return _super.prototype._serialize.call(this, {
  53855. name: "StopAnimationAction",
  53856. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53857. }, parent);
  53858. };
  53859. return StopAnimationAction;
  53860. }(BABYLON.Action));
  53861. BABYLON.StopAnimationAction = StopAnimationAction;
  53862. var DoNothingAction = /** @class */ (function (_super) {
  53863. __extends(DoNothingAction, _super);
  53864. function DoNothingAction(triggerOptions, condition) {
  53865. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53866. return _super.call(this, triggerOptions, condition) || this;
  53867. }
  53868. DoNothingAction.prototype.execute = function () {
  53869. };
  53870. DoNothingAction.prototype.serialize = function (parent) {
  53871. return _super.prototype._serialize.call(this, {
  53872. name: "DoNothingAction",
  53873. properties: []
  53874. }, parent);
  53875. };
  53876. return DoNothingAction;
  53877. }(BABYLON.Action));
  53878. BABYLON.DoNothingAction = DoNothingAction;
  53879. var CombineAction = /** @class */ (function (_super) {
  53880. __extends(CombineAction, _super);
  53881. function CombineAction(triggerOptions, children, condition) {
  53882. var _this = _super.call(this, triggerOptions, condition) || this;
  53883. _this.children = children;
  53884. return _this;
  53885. }
  53886. /** @hidden */
  53887. CombineAction.prototype._prepare = function () {
  53888. for (var index = 0; index < this.children.length; index++) {
  53889. this.children[index]._actionManager = this._actionManager;
  53890. this.children[index]._prepare();
  53891. }
  53892. };
  53893. CombineAction.prototype.execute = function (evt) {
  53894. for (var index = 0; index < this.children.length; index++) {
  53895. this.children[index].execute(evt);
  53896. }
  53897. };
  53898. CombineAction.prototype.serialize = function (parent) {
  53899. var serializationObject = _super.prototype._serialize.call(this, {
  53900. name: "CombineAction",
  53901. properties: [],
  53902. combine: []
  53903. }, parent);
  53904. for (var i = 0; i < this.children.length; i++) {
  53905. serializationObject.combine.push(this.children[i].serialize(null));
  53906. }
  53907. return serializationObject;
  53908. };
  53909. return CombineAction;
  53910. }(BABYLON.Action));
  53911. BABYLON.CombineAction = CombineAction;
  53912. var ExecuteCodeAction = /** @class */ (function (_super) {
  53913. __extends(ExecuteCodeAction, _super);
  53914. function ExecuteCodeAction(triggerOptions, func, condition) {
  53915. var _this = _super.call(this, triggerOptions, condition) || this;
  53916. _this.func = func;
  53917. return _this;
  53918. }
  53919. ExecuteCodeAction.prototype.execute = function (evt) {
  53920. this.func(evt);
  53921. };
  53922. return ExecuteCodeAction;
  53923. }(BABYLON.Action));
  53924. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53925. var SetParentAction = /** @class */ (function (_super) {
  53926. __extends(SetParentAction, _super);
  53927. function SetParentAction(triggerOptions, target, parent, condition) {
  53928. var _this = _super.call(this, triggerOptions, condition) || this;
  53929. _this._target = target;
  53930. _this._parent = parent;
  53931. return _this;
  53932. }
  53933. /** @hidden */
  53934. SetParentAction.prototype._prepare = function () {
  53935. };
  53936. SetParentAction.prototype.execute = function () {
  53937. if (this._target.parent === this._parent) {
  53938. return;
  53939. }
  53940. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53941. invertParentWorldMatrix.invert();
  53942. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53943. this._target.parent = this._parent;
  53944. };
  53945. SetParentAction.prototype.serialize = function (parent) {
  53946. return _super.prototype._serialize.call(this, {
  53947. name: "SetParentAction",
  53948. properties: [
  53949. BABYLON.Action._GetTargetProperty(this._target),
  53950. BABYLON.Action._GetTargetProperty(this._parent),
  53951. ]
  53952. }, parent);
  53953. };
  53954. return SetParentAction;
  53955. }(BABYLON.Action));
  53956. BABYLON.SetParentAction = SetParentAction;
  53957. var PlaySoundAction = /** @class */ (function (_super) {
  53958. __extends(PlaySoundAction, _super);
  53959. function PlaySoundAction(triggerOptions, sound, condition) {
  53960. var _this = _super.call(this, triggerOptions, condition) || this;
  53961. _this._sound = sound;
  53962. return _this;
  53963. }
  53964. /** @hidden */
  53965. PlaySoundAction.prototype._prepare = function () {
  53966. };
  53967. PlaySoundAction.prototype.execute = function () {
  53968. if (this._sound !== undefined)
  53969. this._sound.play();
  53970. };
  53971. PlaySoundAction.prototype.serialize = function (parent) {
  53972. return _super.prototype._serialize.call(this, {
  53973. name: "PlaySoundAction",
  53974. properties: [{ name: "sound", value: this._sound.name }]
  53975. }, parent);
  53976. };
  53977. return PlaySoundAction;
  53978. }(BABYLON.Action));
  53979. BABYLON.PlaySoundAction = PlaySoundAction;
  53980. var StopSoundAction = /** @class */ (function (_super) {
  53981. __extends(StopSoundAction, _super);
  53982. function StopSoundAction(triggerOptions, sound, condition) {
  53983. var _this = _super.call(this, triggerOptions, condition) || this;
  53984. _this._sound = sound;
  53985. return _this;
  53986. }
  53987. /** @hidden */
  53988. StopSoundAction.prototype._prepare = function () {
  53989. };
  53990. StopSoundAction.prototype.execute = function () {
  53991. if (this._sound !== undefined)
  53992. this._sound.stop();
  53993. };
  53994. StopSoundAction.prototype.serialize = function (parent) {
  53995. return _super.prototype._serialize.call(this, {
  53996. name: "StopSoundAction",
  53997. properties: [{ name: "sound", value: this._sound.name }]
  53998. }, parent);
  53999. };
  54000. return StopSoundAction;
  54001. }(BABYLON.Action));
  54002. BABYLON.StopSoundAction = StopSoundAction;
  54003. })(BABYLON || (BABYLON = {}));
  54004. //# sourceMappingURL=babylon.directActions.js.map
  54005. var BABYLON;
  54006. (function (BABYLON) {
  54007. var SpriteManager = /** @class */ (function () {
  54008. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54009. if (epsilon === void 0) { epsilon = 0.01; }
  54010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54011. this.name = name;
  54012. this.sprites = new Array();
  54013. this.renderingGroupId = 0;
  54014. this.layerMask = 0x0FFFFFFF;
  54015. this.fogEnabled = true;
  54016. this.isPickable = false;
  54017. /**
  54018. * An event triggered when the manager is disposed.
  54019. */
  54020. this.onDisposeObservable = new BABYLON.Observable();
  54021. this._vertexBuffers = {};
  54022. this._capacity = capacity;
  54023. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54024. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54025. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54026. if (cellSize.width && cellSize.height) {
  54027. this.cellWidth = cellSize.width;
  54028. this.cellHeight = cellSize.height;
  54029. }
  54030. else if (cellSize !== undefined) {
  54031. this.cellWidth = cellSize;
  54032. this.cellHeight = cellSize;
  54033. }
  54034. else {
  54035. return;
  54036. }
  54037. this._epsilon = epsilon;
  54038. this._scene = scene;
  54039. this._scene.spriteManagers.push(this);
  54040. var indices = [];
  54041. var index = 0;
  54042. for (var count = 0; count < capacity; count++) {
  54043. indices.push(index);
  54044. indices.push(index + 1);
  54045. indices.push(index + 2);
  54046. indices.push(index);
  54047. indices.push(index + 2);
  54048. indices.push(index + 3);
  54049. index += 4;
  54050. }
  54051. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54052. // VBO
  54053. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54054. this._vertexData = new Float32Array(capacity * 16 * 4);
  54055. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54056. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54057. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54058. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54059. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54060. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54061. this._vertexBuffers["options"] = options;
  54062. this._vertexBuffers["cellInfo"] = cellInfo;
  54063. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54064. // Effects
  54065. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54066. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54067. }
  54068. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54069. set: function (callback) {
  54070. if (this._onDisposeObserver) {
  54071. this.onDisposeObservable.remove(this._onDisposeObserver);
  54072. }
  54073. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54074. },
  54075. enumerable: true,
  54076. configurable: true
  54077. });
  54078. Object.defineProperty(SpriteManager.prototype, "texture", {
  54079. get: function () {
  54080. return this._spriteTexture;
  54081. },
  54082. set: function (value) {
  54083. this._spriteTexture = value;
  54084. },
  54085. enumerable: true,
  54086. configurable: true
  54087. });
  54088. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54089. var arrayOffset = index * 16;
  54090. if (offsetX === 0)
  54091. offsetX = this._epsilon;
  54092. else if (offsetX === 1)
  54093. offsetX = 1 - this._epsilon;
  54094. if (offsetY === 0)
  54095. offsetY = this._epsilon;
  54096. else if (offsetY === 1)
  54097. offsetY = 1 - this._epsilon;
  54098. this._vertexData[arrayOffset] = sprite.position.x;
  54099. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54100. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54101. this._vertexData[arrayOffset + 3] = sprite.angle;
  54102. this._vertexData[arrayOffset + 4] = sprite.width;
  54103. this._vertexData[arrayOffset + 5] = sprite.height;
  54104. this._vertexData[arrayOffset + 6] = offsetX;
  54105. this._vertexData[arrayOffset + 7] = offsetY;
  54106. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54107. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54108. var offset = (sprite.cellIndex / rowSize) >> 0;
  54109. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54110. this._vertexData[arrayOffset + 11] = offset;
  54111. // Color
  54112. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54113. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54114. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54115. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54116. };
  54117. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54118. var count = Math.min(this._capacity, this.sprites.length);
  54119. var min = BABYLON.Vector3.Zero();
  54120. var max = BABYLON.Vector3.Zero();
  54121. var distance = Number.MAX_VALUE;
  54122. var currentSprite = null;
  54123. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54124. var cameraView = camera.getViewMatrix();
  54125. for (var index = 0; index < count; index++) {
  54126. var sprite = this.sprites[index];
  54127. if (!sprite) {
  54128. continue;
  54129. }
  54130. if (predicate) {
  54131. if (!predicate(sprite)) {
  54132. continue;
  54133. }
  54134. }
  54135. else if (!sprite.isPickable) {
  54136. continue;
  54137. }
  54138. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54139. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54140. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54141. if (ray.intersectsBoxMinMax(min, max)) {
  54142. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54143. if (distance > currentDistance) {
  54144. distance = currentDistance;
  54145. currentSprite = sprite;
  54146. if (fastCheck) {
  54147. break;
  54148. }
  54149. }
  54150. }
  54151. }
  54152. if (currentSprite) {
  54153. var result = new BABYLON.PickingInfo();
  54154. result.hit = true;
  54155. result.pickedSprite = currentSprite;
  54156. result.distance = distance;
  54157. return result;
  54158. }
  54159. return null;
  54160. };
  54161. SpriteManager.prototype.render = function () {
  54162. // Check
  54163. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54164. return;
  54165. var engine = this._scene.getEngine();
  54166. var baseSize = this._spriteTexture.getBaseSize();
  54167. // Sprites
  54168. var deltaTime = engine.getDeltaTime();
  54169. var max = Math.min(this._capacity, this.sprites.length);
  54170. var rowSize = baseSize.width / this.cellWidth;
  54171. var offset = 0;
  54172. for (var index = 0; index < max; index++) {
  54173. var sprite = this.sprites[index];
  54174. if (!sprite || !sprite.isVisible) {
  54175. continue;
  54176. }
  54177. sprite._animate(deltaTime);
  54178. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54179. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54180. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54181. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54182. }
  54183. this._buffer.update(this._vertexData);
  54184. // Render
  54185. var effect = this._effectBase;
  54186. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54187. effect = this._effectFog;
  54188. }
  54189. engine.enableEffect(effect);
  54190. var viewMatrix = this._scene.getViewMatrix();
  54191. effect.setTexture("diffuseSampler", this._spriteTexture);
  54192. effect.setMatrix("view", viewMatrix);
  54193. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54194. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54195. // Fog
  54196. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54197. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54198. effect.setColor3("vFogColor", this._scene.fogColor);
  54199. }
  54200. // VBOs
  54201. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54202. // Draw order
  54203. engine.setDepthFunctionToLessOrEqual();
  54204. effect.setBool("alphaTest", true);
  54205. engine.setColorWrite(false);
  54206. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54207. engine.setColorWrite(true);
  54208. effect.setBool("alphaTest", false);
  54209. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54210. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54211. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54212. };
  54213. SpriteManager.prototype.dispose = function () {
  54214. if (this._buffer) {
  54215. this._buffer.dispose();
  54216. this._buffer = null;
  54217. }
  54218. if (this._indexBuffer) {
  54219. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54220. this._indexBuffer = null;
  54221. }
  54222. if (this._spriteTexture) {
  54223. this._spriteTexture.dispose();
  54224. this._spriteTexture = null;
  54225. }
  54226. // Remove from scene
  54227. var index = this._scene.spriteManagers.indexOf(this);
  54228. this._scene.spriteManagers.splice(index, 1);
  54229. // Callback
  54230. this.onDisposeObservable.notifyObservers(this);
  54231. this.onDisposeObservable.clear();
  54232. };
  54233. return SpriteManager;
  54234. }());
  54235. BABYLON.SpriteManager = SpriteManager;
  54236. })(BABYLON || (BABYLON = {}));
  54237. //# sourceMappingURL=babylon.spriteManager.js.map
  54238. var BABYLON;
  54239. (function (BABYLON) {
  54240. var Sprite = /** @class */ (function () {
  54241. function Sprite(name, manager) {
  54242. this.name = name;
  54243. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54244. this.width = 1.0;
  54245. this.height = 1.0;
  54246. this.angle = 0;
  54247. this.cellIndex = 0;
  54248. this.invertU = 0;
  54249. this.invertV = 0;
  54250. this.animations = new Array();
  54251. this.isPickable = false;
  54252. this._animationStarted = false;
  54253. this._loopAnimation = false;
  54254. this._fromIndex = 0;
  54255. this._toIndex = 0;
  54256. this._delay = 0;
  54257. this._direction = 1;
  54258. this._time = 0;
  54259. /**
  54260. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54261. */
  54262. this.isVisible = true;
  54263. this._manager = manager;
  54264. this._manager.sprites.push(this);
  54265. this.position = BABYLON.Vector3.Zero();
  54266. }
  54267. Object.defineProperty(Sprite.prototype, "size", {
  54268. get: function () {
  54269. return this.width;
  54270. },
  54271. set: function (value) {
  54272. this.width = value;
  54273. this.height = value;
  54274. },
  54275. enumerable: true,
  54276. configurable: true
  54277. });
  54278. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54279. this._fromIndex = from;
  54280. this._toIndex = to;
  54281. this._loopAnimation = loop;
  54282. this._delay = delay;
  54283. this._animationStarted = true;
  54284. this._direction = from < to ? 1 : -1;
  54285. this.cellIndex = from;
  54286. this._time = 0;
  54287. this._onAnimationEnd = onAnimationEnd;
  54288. };
  54289. Sprite.prototype.stopAnimation = function () {
  54290. this._animationStarted = false;
  54291. };
  54292. /** @hidden */
  54293. Sprite.prototype._animate = function (deltaTime) {
  54294. if (!this._animationStarted)
  54295. return;
  54296. this._time += deltaTime;
  54297. if (this._time > this._delay) {
  54298. this._time = this._time % this._delay;
  54299. this.cellIndex += this._direction;
  54300. if (this.cellIndex > this._toIndex) {
  54301. if (this._loopAnimation) {
  54302. this.cellIndex = this._fromIndex;
  54303. }
  54304. else {
  54305. this.cellIndex = this._toIndex;
  54306. this._animationStarted = false;
  54307. if (this._onAnimationEnd) {
  54308. this._onAnimationEnd();
  54309. }
  54310. if (this.disposeWhenFinishedAnimating) {
  54311. this.dispose();
  54312. }
  54313. }
  54314. }
  54315. }
  54316. };
  54317. Sprite.prototype.dispose = function () {
  54318. for (var i = 0; i < this._manager.sprites.length; i++) {
  54319. if (this._manager.sprites[i] == this) {
  54320. this._manager.sprites.splice(i, 1);
  54321. }
  54322. }
  54323. };
  54324. return Sprite;
  54325. }());
  54326. BABYLON.Sprite = Sprite;
  54327. })(BABYLON || (BABYLON = {}));
  54328. //# sourceMappingURL=babylon.sprite.js.map
  54329. var BABYLON;
  54330. (function (BABYLON) {
  54331. var IntersectionInfo = /** @class */ (function () {
  54332. function IntersectionInfo(bu, bv, distance) {
  54333. this.bu = bu;
  54334. this.bv = bv;
  54335. this.distance = distance;
  54336. this.faceId = 0;
  54337. this.subMeshId = 0;
  54338. }
  54339. return IntersectionInfo;
  54340. }());
  54341. BABYLON.IntersectionInfo = IntersectionInfo;
  54342. /**
  54343. * Information about the result of picking within a scene
  54344. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54345. */
  54346. var PickingInfo = /** @class */ (function () {
  54347. function PickingInfo() {
  54348. /**
  54349. * If the pick collided with an object
  54350. */
  54351. this.hit = false;
  54352. /**
  54353. * Distance away where the pick collided
  54354. */
  54355. this.distance = 0;
  54356. /**
  54357. * The location of pick collision
  54358. */
  54359. this.pickedPoint = null;
  54360. /**
  54361. * The mesh corresponding the the pick collision
  54362. */
  54363. this.pickedMesh = null;
  54364. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54365. this.bu = 0;
  54366. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54367. this.bv = 0;
  54368. /** The id of the face on the mesh that was picked */
  54369. this.faceId = -1;
  54370. /** Id of the the submesh that was picked */
  54371. this.subMeshId = 0;
  54372. /** If a sprite was picked, this will be the sprite the pick collided with */
  54373. this.pickedSprite = null;
  54374. /**
  54375. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54376. */
  54377. this.originMesh = null;
  54378. /**
  54379. * The ray that was used to perform the picking.
  54380. */
  54381. this.ray = null;
  54382. }
  54383. /**
  54384. * Gets the normal correspodning to the face the pick collided with
  54385. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54386. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54387. * @returns The normal correspodning to the face the pick collided with
  54388. */
  54389. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54390. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54391. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54392. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54393. return null;
  54394. }
  54395. var indices = this.pickedMesh.getIndices();
  54396. if (!indices) {
  54397. return null;
  54398. }
  54399. var result;
  54400. if (useVerticesNormals) {
  54401. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54402. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54403. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54404. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54405. normal0 = normal0.scale(this.bu);
  54406. normal1 = normal1.scale(this.bv);
  54407. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54408. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54409. }
  54410. else {
  54411. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54412. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54413. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54414. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54415. var p1p2 = vertex1.subtract(vertex2);
  54416. var p3p2 = vertex3.subtract(vertex2);
  54417. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54418. }
  54419. if (useWorldCoordinates) {
  54420. var wm = this.pickedMesh.getWorldMatrix();
  54421. if (this.pickedMesh.nonUniformScaling) {
  54422. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54423. wm = BABYLON.Tmp.Matrix[0];
  54424. wm.setTranslationFromFloats(0, 0, 0);
  54425. wm.invert();
  54426. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54427. wm = BABYLON.Tmp.Matrix[1];
  54428. }
  54429. result = BABYLON.Vector3.TransformNormal(result, wm);
  54430. }
  54431. result.normalize();
  54432. return result;
  54433. };
  54434. /**
  54435. * Gets the texture coordinates of where the pick occured
  54436. * @returns the vector containing the coordnates of the texture
  54437. */
  54438. PickingInfo.prototype.getTextureCoordinates = function () {
  54439. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54440. return null;
  54441. }
  54442. var indices = this.pickedMesh.getIndices();
  54443. if (!indices) {
  54444. return null;
  54445. }
  54446. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54447. if (!uvs) {
  54448. return null;
  54449. }
  54450. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54451. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54452. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54453. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54454. uv1 = uv1.scale(this.bu);
  54455. uv2 = uv2.scale(this.bv);
  54456. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54457. };
  54458. return PickingInfo;
  54459. }());
  54460. BABYLON.PickingInfo = PickingInfo;
  54461. })(BABYLON || (BABYLON = {}));
  54462. //# sourceMappingURL=babylon.pickingInfo.js.map
  54463. var BABYLON;
  54464. (function (BABYLON) {
  54465. var Ray = /** @class */ (function () {
  54466. function Ray(origin, direction, length) {
  54467. if (length === void 0) { length = Number.MAX_VALUE; }
  54468. this.origin = origin;
  54469. this.direction = direction;
  54470. this.length = length;
  54471. }
  54472. // Methods
  54473. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54474. var d = 0.0;
  54475. var maxValue = Number.MAX_VALUE;
  54476. var inv;
  54477. var min;
  54478. var max;
  54479. var temp;
  54480. if (Math.abs(this.direction.x) < 0.0000001) {
  54481. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54482. return false;
  54483. }
  54484. }
  54485. else {
  54486. inv = 1.0 / this.direction.x;
  54487. min = (minimum.x - this.origin.x) * inv;
  54488. max = (maximum.x - this.origin.x) * inv;
  54489. if (max === -Infinity) {
  54490. max = Infinity;
  54491. }
  54492. if (min > max) {
  54493. temp = min;
  54494. min = max;
  54495. max = temp;
  54496. }
  54497. d = Math.max(min, d);
  54498. maxValue = Math.min(max, maxValue);
  54499. if (d > maxValue) {
  54500. return false;
  54501. }
  54502. }
  54503. if (Math.abs(this.direction.y) < 0.0000001) {
  54504. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54505. return false;
  54506. }
  54507. }
  54508. else {
  54509. inv = 1.0 / this.direction.y;
  54510. min = (minimum.y - this.origin.y) * inv;
  54511. max = (maximum.y - this.origin.y) * inv;
  54512. if (max === -Infinity) {
  54513. max = Infinity;
  54514. }
  54515. if (min > max) {
  54516. temp = min;
  54517. min = max;
  54518. max = temp;
  54519. }
  54520. d = Math.max(min, d);
  54521. maxValue = Math.min(max, maxValue);
  54522. if (d > maxValue) {
  54523. return false;
  54524. }
  54525. }
  54526. if (Math.abs(this.direction.z) < 0.0000001) {
  54527. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54528. return false;
  54529. }
  54530. }
  54531. else {
  54532. inv = 1.0 / this.direction.z;
  54533. min = (minimum.z - this.origin.z) * inv;
  54534. max = (maximum.z - this.origin.z) * inv;
  54535. if (max === -Infinity) {
  54536. max = Infinity;
  54537. }
  54538. if (min > max) {
  54539. temp = min;
  54540. min = max;
  54541. max = temp;
  54542. }
  54543. d = Math.max(min, d);
  54544. maxValue = Math.min(max, maxValue);
  54545. if (d > maxValue) {
  54546. return false;
  54547. }
  54548. }
  54549. return true;
  54550. };
  54551. Ray.prototype.intersectsBox = function (box) {
  54552. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54553. };
  54554. Ray.prototype.intersectsSphere = function (sphere) {
  54555. var x = sphere.center.x - this.origin.x;
  54556. var y = sphere.center.y - this.origin.y;
  54557. var z = sphere.center.z - this.origin.z;
  54558. var pyth = (x * x) + (y * y) + (z * z);
  54559. var rr = sphere.radius * sphere.radius;
  54560. if (pyth <= rr) {
  54561. return true;
  54562. }
  54563. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54564. if (dot < 0.0) {
  54565. return false;
  54566. }
  54567. var temp = pyth - (dot * dot);
  54568. return temp <= rr;
  54569. };
  54570. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54571. if (!this._edge1) {
  54572. this._edge1 = BABYLON.Vector3.Zero();
  54573. this._edge2 = BABYLON.Vector3.Zero();
  54574. this._pvec = BABYLON.Vector3.Zero();
  54575. this._tvec = BABYLON.Vector3.Zero();
  54576. this._qvec = BABYLON.Vector3.Zero();
  54577. }
  54578. vertex1.subtractToRef(vertex0, this._edge1);
  54579. vertex2.subtractToRef(vertex0, this._edge2);
  54580. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54581. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54582. if (det === 0) {
  54583. return null;
  54584. }
  54585. var invdet = 1 / det;
  54586. this.origin.subtractToRef(vertex0, this._tvec);
  54587. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54588. if (bu < 0 || bu > 1.0) {
  54589. return null;
  54590. }
  54591. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54592. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54593. if (bv < 0 || bu + bv > 1.0) {
  54594. return null;
  54595. }
  54596. //check if the distance is longer than the predefined length.
  54597. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54598. if (distance > this.length) {
  54599. return null;
  54600. }
  54601. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54602. };
  54603. Ray.prototype.intersectsPlane = function (plane) {
  54604. var distance;
  54605. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54606. if (Math.abs(result1) < 9.99999997475243E-07) {
  54607. return null;
  54608. }
  54609. else {
  54610. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54611. distance = (-plane.d - result2) / result1;
  54612. if (distance < 0.0) {
  54613. if (distance < -9.99999997475243E-07) {
  54614. return null;
  54615. }
  54616. else {
  54617. return 0;
  54618. }
  54619. }
  54620. return distance;
  54621. }
  54622. };
  54623. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54624. var tm = BABYLON.Tmp.Matrix[0];
  54625. mesh.getWorldMatrix().invertToRef(tm);
  54626. if (this._tmpRay) {
  54627. Ray.TransformToRef(this, tm, this._tmpRay);
  54628. }
  54629. else {
  54630. this._tmpRay = Ray.Transform(this, tm);
  54631. }
  54632. return mesh.intersects(this._tmpRay, fastCheck);
  54633. };
  54634. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54635. if (results) {
  54636. results.length = 0;
  54637. }
  54638. else {
  54639. results = [];
  54640. }
  54641. for (var i = 0; i < meshes.length; i++) {
  54642. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54643. if (pickInfo.hit) {
  54644. results.push(pickInfo);
  54645. }
  54646. }
  54647. results.sort(this._comparePickingInfo);
  54648. return results;
  54649. };
  54650. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54651. if (pickingInfoA.distance < pickingInfoB.distance) {
  54652. return -1;
  54653. }
  54654. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54655. return 1;
  54656. }
  54657. else {
  54658. return 0;
  54659. }
  54660. };
  54661. /**
  54662. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54663. * @param sega the first point of the segment to test the intersection against
  54664. * @param segb the second point of the segment to test the intersection against
  54665. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54666. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54667. */
  54668. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54669. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54670. var u = segb.subtract(sega);
  54671. var v = rsegb.subtract(this.origin);
  54672. var w = sega.subtract(this.origin);
  54673. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54674. var b = BABYLON.Vector3.Dot(u, v);
  54675. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54676. var d = BABYLON.Vector3.Dot(u, w);
  54677. var e = BABYLON.Vector3.Dot(v, w);
  54678. var D = a * c - b * b; // always >= 0
  54679. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54680. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54681. // compute the line parameters of the two closest points
  54682. if (D < Ray.smallnum) { // the lines are almost parallel
  54683. sN = 0.0; // force using point P0 on segment S1
  54684. sD = 1.0; // to prevent possible division by 0.0 later
  54685. tN = e;
  54686. tD = c;
  54687. }
  54688. else { // get the closest points on the infinite lines
  54689. sN = (b * e - c * d);
  54690. tN = (a * e - b * d);
  54691. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54692. sN = 0.0;
  54693. tN = e;
  54694. tD = c;
  54695. }
  54696. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54697. sN = sD;
  54698. tN = e + b;
  54699. tD = c;
  54700. }
  54701. }
  54702. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54703. tN = 0.0;
  54704. // recompute sc for this edge
  54705. if (-d < 0.0) {
  54706. sN = 0.0;
  54707. }
  54708. else if (-d > a)
  54709. sN = sD;
  54710. else {
  54711. sN = -d;
  54712. sD = a;
  54713. }
  54714. }
  54715. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54716. tN = tD;
  54717. // recompute sc for this edge
  54718. if ((-d + b) < 0.0) {
  54719. sN = 0;
  54720. }
  54721. else if ((-d + b) > a) {
  54722. sN = sD;
  54723. }
  54724. else {
  54725. sN = (-d + b);
  54726. sD = a;
  54727. }
  54728. }
  54729. // finally do the division to get sc and tc
  54730. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54731. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54732. // get the difference of the two closest points
  54733. var qtc = v.multiplyByFloats(tc, tc, tc);
  54734. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54735. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54736. if (isIntersected) {
  54737. return qtc.length();
  54738. }
  54739. return -1;
  54740. };
  54741. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54742. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54743. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54744. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54745. this.direction.normalize();
  54746. return this;
  54747. };
  54748. // Statics
  54749. Ray.Zero = function () {
  54750. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54751. };
  54752. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54753. var result = Ray.Zero();
  54754. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54755. };
  54756. /**
  54757. * 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
  54758. * transformed to the given world matrix.
  54759. * @param origin The origin point
  54760. * @param end The end point
  54761. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54762. */
  54763. Ray.CreateNewFromTo = function (origin, end, world) {
  54764. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54765. var direction = end.subtract(origin);
  54766. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54767. direction.normalize();
  54768. return Ray.Transform(new Ray(origin, direction, length), world);
  54769. };
  54770. Ray.Transform = function (ray, matrix) {
  54771. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54772. Ray.TransformToRef(ray, matrix, result);
  54773. return result;
  54774. };
  54775. Ray.TransformToRef = function (ray, matrix, result) {
  54776. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54777. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54778. result.length = ray.length;
  54779. var dir = result.direction;
  54780. var len = dir.length();
  54781. if (!(len === 0 || len === 1)) {
  54782. var num = 1.0 / len;
  54783. dir.x *= num;
  54784. dir.y *= num;
  54785. dir.z *= num;
  54786. result.length *= len;
  54787. }
  54788. };
  54789. Ray.smallnum = 0.00000001;
  54790. Ray.rayl = 10e8;
  54791. return Ray;
  54792. }());
  54793. BABYLON.Ray = Ray;
  54794. })(BABYLON || (BABYLON = {}));
  54795. //# sourceMappingURL=babylon.ray.js.map
  54796. var BABYLON;
  54797. (function (BABYLON) {
  54798. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54799. if (boxMin.x > sphereCenter.x + sphereRadius)
  54800. return false;
  54801. if (sphereCenter.x - sphereRadius > boxMax.x)
  54802. return false;
  54803. if (boxMin.y > sphereCenter.y + sphereRadius)
  54804. return false;
  54805. if (sphereCenter.y - sphereRadius > boxMax.y)
  54806. return false;
  54807. if (boxMin.z > sphereCenter.z + sphereRadius)
  54808. return false;
  54809. if (sphereCenter.z - sphereRadius > boxMax.z)
  54810. return false;
  54811. return true;
  54812. };
  54813. var getLowestRoot = (function () {
  54814. var result = { root: 0, found: false };
  54815. return function (a, b, c, maxR) {
  54816. result.root = 0;
  54817. result.found = false;
  54818. var determinant = b * b - 4.0 * a * c;
  54819. if (determinant < 0)
  54820. return result;
  54821. var sqrtD = Math.sqrt(determinant);
  54822. var r1 = (-b - sqrtD) / (2.0 * a);
  54823. var r2 = (-b + sqrtD) / (2.0 * a);
  54824. if (r1 > r2) {
  54825. var temp = r2;
  54826. r2 = r1;
  54827. r1 = temp;
  54828. }
  54829. if (r1 > 0 && r1 < maxR) {
  54830. result.root = r1;
  54831. result.found = true;
  54832. return result;
  54833. }
  54834. if (r2 > 0 && r2 < maxR) {
  54835. result.root = r2;
  54836. result.found = true;
  54837. return result;
  54838. }
  54839. return result;
  54840. };
  54841. })();
  54842. var Collider = /** @class */ (function () {
  54843. function Collider() {
  54844. this._collisionPoint = BABYLON.Vector3.Zero();
  54845. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54846. this._tempVector = BABYLON.Vector3.Zero();
  54847. this._tempVector2 = BABYLON.Vector3.Zero();
  54848. this._tempVector3 = BABYLON.Vector3.Zero();
  54849. this._tempVector4 = BABYLON.Vector3.Zero();
  54850. this._edge = BABYLON.Vector3.Zero();
  54851. this._baseToVertex = BABYLON.Vector3.Zero();
  54852. this._destinationPoint = BABYLON.Vector3.Zero();
  54853. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54854. this._displacementVector = BABYLON.Vector3.Zero();
  54855. /** @hidden */
  54856. this._radius = BABYLON.Vector3.One();
  54857. /** @hidden */
  54858. this._retry = 0;
  54859. /** @hidden */
  54860. this._basePointWorld = BABYLON.Vector3.Zero();
  54861. this._velocityWorld = BABYLON.Vector3.Zero();
  54862. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54863. this._collisionMask = -1;
  54864. }
  54865. Object.defineProperty(Collider.prototype, "collisionMask", {
  54866. get: function () {
  54867. return this._collisionMask;
  54868. },
  54869. set: function (mask) {
  54870. this._collisionMask = !isNaN(mask) ? mask : -1;
  54871. },
  54872. enumerable: true,
  54873. configurable: true
  54874. });
  54875. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54876. /**
  54877. * Gets the plane normal used to compute the sliding response (in local space)
  54878. */
  54879. get: function () {
  54880. return this._slidePlaneNormal;
  54881. },
  54882. enumerable: true,
  54883. configurable: true
  54884. });
  54885. // Methods
  54886. /** @hidden */
  54887. Collider.prototype._initialize = function (source, dir, e) {
  54888. this._velocity = dir;
  54889. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54890. this._basePoint = source;
  54891. source.multiplyToRef(this._radius, this._basePointWorld);
  54892. dir.multiplyToRef(this._radius, this._velocityWorld);
  54893. this._velocityWorldLength = this._velocityWorld.length();
  54894. this._epsilon = e;
  54895. this.collisionFound = false;
  54896. };
  54897. /** @hidden */
  54898. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54899. pa.subtractToRef(point, this._tempVector);
  54900. pb.subtractToRef(point, this._tempVector2);
  54901. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54902. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54903. if (d < 0)
  54904. return false;
  54905. pc.subtractToRef(point, this._tempVector3);
  54906. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54907. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54908. if (d < 0)
  54909. return false;
  54910. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54911. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54912. return d >= 0;
  54913. };
  54914. /** @hidden */
  54915. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54916. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54917. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54918. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54919. return false;
  54920. }
  54921. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54922. return false;
  54923. return true;
  54924. };
  54925. /** @hidden */
  54926. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54927. var t0;
  54928. var embeddedInPlane = false;
  54929. //defensive programming, actually not needed.
  54930. if (!trianglePlaneArray) {
  54931. trianglePlaneArray = [];
  54932. }
  54933. if (!trianglePlaneArray[faceIndex]) {
  54934. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54935. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54936. }
  54937. var trianglePlane = trianglePlaneArray[faceIndex];
  54938. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54939. return;
  54940. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54941. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54942. if (normalDotVelocity == 0) {
  54943. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54944. return;
  54945. embeddedInPlane = true;
  54946. t0 = 0;
  54947. }
  54948. else {
  54949. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54950. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54951. if (t0 > t1) {
  54952. var temp = t1;
  54953. t1 = t0;
  54954. t0 = temp;
  54955. }
  54956. if (t0 > 1.0 || t1 < 0.0)
  54957. return;
  54958. if (t0 < 0)
  54959. t0 = 0;
  54960. if (t0 > 1.0)
  54961. t0 = 1.0;
  54962. }
  54963. this._collisionPoint.copyFromFloats(0, 0, 0);
  54964. var found = false;
  54965. var t = 1.0;
  54966. if (!embeddedInPlane) {
  54967. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54968. this._velocity.scaleToRef(t0, this._tempVector);
  54969. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54970. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54971. found = true;
  54972. t = t0;
  54973. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54974. }
  54975. }
  54976. if (!found) {
  54977. var velocitySquaredLength = this._velocity.lengthSquared();
  54978. var a = velocitySquaredLength;
  54979. this._basePoint.subtractToRef(p1, this._tempVector);
  54980. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54981. var c = this._tempVector.lengthSquared() - 1.0;
  54982. var lowestRoot = getLowestRoot(a, b, c, t);
  54983. if (lowestRoot.found) {
  54984. t = lowestRoot.root;
  54985. found = true;
  54986. this._collisionPoint.copyFrom(p1);
  54987. }
  54988. this._basePoint.subtractToRef(p2, this._tempVector);
  54989. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54990. c = this._tempVector.lengthSquared() - 1.0;
  54991. lowestRoot = getLowestRoot(a, b, c, t);
  54992. if (lowestRoot.found) {
  54993. t = lowestRoot.root;
  54994. found = true;
  54995. this._collisionPoint.copyFrom(p2);
  54996. }
  54997. this._basePoint.subtractToRef(p3, this._tempVector);
  54998. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54999. c = this._tempVector.lengthSquared() - 1.0;
  55000. lowestRoot = getLowestRoot(a, b, c, t);
  55001. if (lowestRoot.found) {
  55002. t = lowestRoot.root;
  55003. found = true;
  55004. this._collisionPoint.copyFrom(p3);
  55005. }
  55006. p2.subtractToRef(p1, this._edge);
  55007. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55008. var edgeSquaredLength = this._edge.lengthSquared();
  55009. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55010. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55011. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55012. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55013. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55014. lowestRoot = getLowestRoot(a, b, c, t);
  55015. if (lowestRoot.found) {
  55016. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55017. if (f >= 0.0 && f <= 1.0) {
  55018. t = lowestRoot.root;
  55019. found = true;
  55020. this._edge.scaleInPlace(f);
  55021. p1.addToRef(this._edge, this._collisionPoint);
  55022. }
  55023. }
  55024. p3.subtractToRef(p2, this._edge);
  55025. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55026. edgeSquaredLength = this._edge.lengthSquared();
  55027. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55028. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55029. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55030. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55031. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55032. lowestRoot = getLowestRoot(a, b, c, t);
  55033. if (lowestRoot.found) {
  55034. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55035. if (f >= 0.0 && f <= 1.0) {
  55036. t = lowestRoot.root;
  55037. found = true;
  55038. this._edge.scaleInPlace(f);
  55039. p2.addToRef(this._edge, this._collisionPoint);
  55040. }
  55041. }
  55042. p1.subtractToRef(p3, this._edge);
  55043. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55044. edgeSquaredLength = this._edge.lengthSquared();
  55045. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55046. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55047. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55048. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55049. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55050. lowestRoot = getLowestRoot(a, b, c, t);
  55051. if (lowestRoot.found) {
  55052. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55053. if (f >= 0.0 && f <= 1.0) {
  55054. t = lowestRoot.root;
  55055. found = true;
  55056. this._edge.scaleInPlace(f);
  55057. p3.addToRef(this._edge, this._collisionPoint);
  55058. }
  55059. }
  55060. }
  55061. if (found) {
  55062. var distToCollision = t * this._velocity.length();
  55063. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55064. if (!this.intersectionPoint) {
  55065. this.intersectionPoint = this._collisionPoint.clone();
  55066. }
  55067. else {
  55068. this.intersectionPoint.copyFrom(this._collisionPoint);
  55069. }
  55070. this._nearestDistance = distToCollision;
  55071. this.collisionFound = true;
  55072. }
  55073. }
  55074. };
  55075. /** @hidden */
  55076. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55077. for (var i = indexStart; i < indexEnd; i += 3) {
  55078. var p1 = pts[indices[i] - decal];
  55079. var p2 = pts[indices[i + 1] - decal];
  55080. var p3 = pts[indices[i + 2] - decal];
  55081. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55082. }
  55083. };
  55084. /** @hidden */
  55085. Collider.prototype._getResponse = function (pos, vel) {
  55086. pos.addToRef(vel, this._destinationPoint);
  55087. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55088. this._basePoint.addToRef(vel, pos);
  55089. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55090. this._slidePlaneNormal.normalize();
  55091. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55092. pos.addInPlace(this._displacementVector);
  55093. this.intersectionPoint.addInPlace(this._displacementVector);
  55094. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55095. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55096. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55097. };
  55098. return Collider;
  55099. }());
  55100. BABYLON.Collider = Collider;
  55101. })(BABYLON || (BABYLON = {}));
  55102. //# sourceMappingURL=babylon.collider.js.map
  55103. var BABYLON;
  55104. (function (BABYLON) {
  55105. //WebWorker code will be inserted to this variable.
  55106. BABYLON.CollisionWorker = "";
  55107. /** Defines supported task for worker process */
  55108. var WorkerTaskType;
  55109. (function (WorkerTaskType) {
  55110. /** Initialization */
  55111. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55112. /** Update of geometry */
  55113. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55114. /** Evaluate collision */
  55115. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55116. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55117. /** Defines kind of replies returned by worker */
  55118. var WorkerReplyType;
  55119. (function (WorkerReplyType) {
  55120. /** Success */
  55121. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55122. /** Unkown error */
  55123. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55124. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55125. var CollisionCoordinatorWorker = /** @class */ (function () {
  55126. function CollisionCoordinatorWorker() {
  55127. var _this = this;
  55128. this._scaledPosition = BABYLON.Vector3.Zero();
  55129. this._scaledVelocity = BABYLON.Vector3.Zero();
  55130. this.onMeshUpdated = function (transformNode) {
  55131. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55132. };
  55133. this.onGeometryUpdated = function (geometry) {
  55134. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55135. };
  55136. this._afterRender = function () {
  55137. if (!_this._init)
  55138. return;
  55139. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55140. return;
  55141. }
  55142. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55143. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55144. if (_this._runningUpdated > 4) {
  55145. return;
  55146. }
  55147. ++_this._runningUpdated;
  55148. var payload = {
  55149. updatedMeshes: _this._addUpdateMeshesList,
  55150. updatedGeometries: _this._addUpdateGeometriesList,
  55151. removedGeometries: _this._toRemoveGeometryArray,
  55152. removedMeshes: _this._toRemoveMeshesArray
  55153. };
  55154. var message = {
  55155. payload: payload,
  55156. taskType: WorkerTaskType.UPDATE
  55157. };
  55158. var serializable = [];
  55159. for (var id in payload.updatedGeometries) {
  55160. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55161. //prepare transferables
  55162. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55163. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55164. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55165. }
  55166. }
  55167. _this._worker.postMessage(message, serializable);
  55168. _this._addUpdateMeshesList = {};
  55169. _this._addUpdateGeometriesList = {};
  55170. _this._toRemoveGeometryArray = [];
  55171. _this._toRemoveMeshesArray = [];
  55172. };
  55173. this._onMessageFromWorker = function (e) {
  55174. var returnData = e.data;
  55175. if (returnData.error != WorkerReplyType.SUCCESS) {
  55176. //TODO what errors can be returned from the worker?
  55177. BABYLON.Tools.Warn("error returned from worker!");
  55178. return;
  55179. }
  55180. switch (returnData.taskType) {
  55181. case WorkerTaskType.INIT:
  55182. _this._init = true;
  55183. //Update the worked with ALL of the scene's current state
  55184. _this._scene.meshes.forEach(function (mesh) {
  55185. _this.onMeshAdded(mesh);
  55186. });
  55187. _this._scene.getGeometries().forEach(function (geometry) {
  55188. _this.onGeometryAdded(geometry);
  55189. });
  55190. break;
  55191. case WorkerTaskType.UPDATE:
  55192. _this._runningUpdated--;
  55193. break;
  55194. case WorkerTaskType.COLLIDE:
  55195. var returnPayload = returnData.payload;
  55196. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55197. return;
  55198. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55199. if (callback) {
  55200. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55201. if (mesh) {
  55202. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55203. }
  55204. }
  55205. //cleanup
  55206. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55207. break;
  55208. }
  55209. };
  55210. this._collisionsCallbackArray = [];
  55211. this._init = false;
  55212. this._runningUpdated = 0;
  55213. this._addUpdateMeshesList = {};
  55214. this._addUpdateGeometriesList = {};
  55215. this._toRemoveGeometryArray = [];
  55216. this._toRemoveMeshesArray = [];
  55217. }
  55218. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55219. if (!this._init)
  55220. return;
  55221. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55222. return;
  55223. position.divideToRef(collider._radius, this._scaledPosition);
  55224. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55225. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55226. var payload = {
  55227. collider: {
  55228. position: this._scaledPosition.asArray(),
  55229. velocity: this._scaledVelocity.asArray(),
  55230. radius: collider._radius.asArray()
  55231. },
  55232. collisionId: collisionIndex,
  55233. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55234. maximumRetry: maximumRetry
  55235. };
  55236. var message = {
  55237. payload: payload,
  55238. taskType: WorkerTaskType.COLLIDE
  55239. };
  55240. this._worker.postMessage(message);
  55241. };
  55242. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55243. this._scene = scene;
  55244. this._scene.registerAfterRender(this._afterRender);
  55245. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55246. this._worker = new Worker(workerUrl);
  55247. this._worker.onmessage = this._onMessageFromWorker;
  55248. var message = {
  55249. payload: {},
  55250. taskType: WorkerTaskType.INIT
  55251. };
  55252. this._worker.postMessage(message);
  55253. };
  55254. CollisionCoordinatorWorker.prototype.destroy = function () {
  55255. this._scene.unregisterAfterRender(this._afterRender);
  55256. this._worker.terminate();
  55257. };
  55258. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55259. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55260. this.onMeshUpdated(mesh);
  55261. };
  55262. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55263. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55264. };
  55265. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55266. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55267. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55268. this.onGeometryUpdated(geometry);
  55269. };
  55270. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55271. this._toRemoveGeometryArray.push(geometry.id);
  55272. };
  55273. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55274. var submeshes = [];
  55275. if (mesh.subMeshes) {
  55276. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55277. var boundingInfo = sm.getBoundingInfo();
  55278. return {
  55279. position: idx,
  55280. verticesStart: sm.verticesStart,
  55281. verticesCount: sm.verticesCount,
  55282. indexStart: sm.indexStart,
  55283. indexCount: sm.indexCount,
  55284. hasMaterial: !!sm.getMaterial(),
  55285. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55286. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55287. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55288. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55289. };
  55290. });
  55291. }
  55292. var geometryId = null;
  55293. if (mesh instanceof BABYLON.Mesh) {
  55294. var geometry = mesh.geometry;
  55295. geometryId = geometry ? geometry.id : null;
  55296. }
  55297. else if (mesh instanceof BABYLON.InstancedMesh) {
  55298. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55299. geometryId = geometry ? geometry.id : null;
  55300. }
  55301. var boundingInfo = mesh.getBoundingInfo();
  55302. return {
  55303. uniqueId: mesh.uniqueId,
  55304. id: mesh.id,
  55305. name: mesh.name,
  55306. geometryId: geometryId,
  55307. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55308. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55309. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55310. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55311. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55312. subMeshes: submeshes,
  55313. checkCollisions: mesh.checkCollisions
  55314. };
  55315. };
  55316. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55317. return {
  55318. id: geometry.id,
  55319. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55320. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55321. indices: new Uint32Array(geometry.getIndices() || []),
  55322. };
  55323. };
  55324. return CollisionCoordinatorWorker;
  55325. }());
  55326. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55327. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55328. function CollisionCoordinatorLegacy() {
  55329. this._scaledPosition = BABYLON.Vector3.Zero();
  55330. this._scaledVelocity = BABYLON.Vector3.Zero();
  55331. this._finalPosition = BABYLON.Vector3.Zero();
  55332. }
  55333. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55334. position.divideToRef(collider._radius, this._scaledPosition);
  55335. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55336. collider.collidedMesh = null;
  55337. collider._retry = 0;
  55338. collider._initialVelocity = this._scaledVelocity;
  55339. collider._initialPosition = this._scaledPosition;
  55340. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55341. this._finalPosition.multiplyInPlace(collider._radius);
  55342. //run the callback
  55343. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55344. };
  55345. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55346. this._scene = scene;
  55347. };
  55348. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55349. //Legacy need no destruction method.
  55350. };
  55351. //No update in legacy mode
  55352. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55353. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55354. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55355. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55356. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55357. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55358. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55359. if (excludedMesh === void 0) { excludedMesh = null; }
  55360. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55361. if (collider._retry >= maximumRetry) {
  55362. finalPosition.copyFrom(position);
  55363. return;
  55364. }
  55365. // Check if this is a mesh else camera or -1
  55366. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55367. collider._initialize(position, velocity, closeDistance);
  55368. // Check all meshes
  55369. for (var index = 0; index < this._scene.meshes.length; index++) {
  55370. var mesh = this._scene.meshes[index];
  55371. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55372. mesh._checkCollision(collider);
  55373. }
  55374. }
  55375. if (!collider.collisionFound) {
  55376. position.addToRef(velocity, finalPosition);
  55377. return;
  55378. }
  55379. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55380. collider._getResponse(position, velocity);
  55381. }
  55382. if (velocity.length() <= closeDistance) {
  55383. finalPosition.copyFrom(position);
  55384. return;
  55385. }
  55386. collider._retry++;
  55387. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55388. };
  55389. return CollisionCoordinatorLegacy;
  55390. }());
  55391. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55392. })(BABYLON || (BABYLON = {}));
  55393. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55394. var BABYLON;
  55395. (function (BABYLON) {
  55396. /**
  55397. * A particle represents one of the element emitted by a particle system.
  55398. * This is mainly define by its coordinates, direction, velocity and age.
  55399. */
  55400. var Particle = /** @class */ (function () {
  55401. /**
  55402. * Creates a new instance Particle
  55403. * @param particleSystem the particle system the particle belongs to
  55404. */
  55405. function Particle(
  55406. /**
  55407. * particleSystem the particle system the particle belongs to.
  55408. */
  55409. particleSystem) {
  55410. this.particleSystem = particleSystem;
  55411. /**
  55412. * The world position of the particle in the scene.
  55413. */
  55414. this.position = BABYLON.Vector3.Zero();
  55415. /**
  55416. * The world direction of the particle in the scene.
  55417. */
  55418. this.direction = BABYLON.Vector3.Zero();
  55419. /**
  55420. * The color of the particle.
  55421. */
  55422. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55423. /**
  55424. * The color change of the particle per step.
  55425. */
  55426. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55427. /**
  55428. * Defines how long will the life of the particle be.
  55429. */
  55430. this.lifeTime = 1.0;
  55431. /**
  55432. * The current age of the particle.
  55433. */
  55434. this.age = 0;
  55435. /**
  55436. * The current size of the particle.
  55437. */
  55438. this.size = 0;
  55439. /**
  55440. * The current scale of the particle.
  55441. */
  55442. this.scale = new BABYLON.Vector2(1, 1);
  55443. /**
  55444. * The current angle of the particle.
  55445. */
  55446. this.angle = 0;
  55447. /**
  55448. * Defines how fast is the angle changing.
  55449. */
  55450. this.angularSpeed = 0;
  55451. /**
  55452. * Defines the cell index used by the particle to be rendered from a sprite.
  55453. */
  55454. this.cellIndex = 0;
  55455. /** @hidden */
  55456. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55457. /** @hidden */
  55458. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55459. /** @hidden */
  55460. this._currentSize1 = 0;
  55461. /** @hidden */
  55462. this._currentSize2 = 0;
  55463. /** @hidden */
  55464. this._currentAngularSpeed1 = 0;
  55465. /** @hidden */
  55466. this._currentAngularSpeed2 = 0;
  55467. /** @hidden */
  55468. this._currentVelocity1 = 0;
  55469. /** @hidden */
  55470. this._currentVelocity2 = 0;
  55471. /** @hidden */
  55472. this._currentLimitVelocity1 = 0;
  55473. /** @hidden */
  55474. this._currentLimitVelocity2 = 0;
  55475. /** @hidden */
  55476. this._currentDrag1 = 0;
  55477. /** @hidden */
  55478. this._currentDrag2 = 0;
  55479. if (!this.particleSystem.isAnimationSheetEnabled) {
  55480. return;
  55481. }
  55482. this.updateCellInfoFromSystem();
  55483. }
  55484. Particle.prototype.updateCellInfoFromSystem = function () {
  55485. this.cellIndex = this.particleSystem.startSpriteCellID;
  55486. };
  55487. /**
  55488. * Defines how the sprite cell index is updated for the particle
  55489. */
  55490. Particle.prototype.updateCellIndex = function () {
  55491. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55492. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55493. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55494. };
  55495. /**
  55496. * Copy the properties of particle to another one.
  55497. * @param other the particle to copy the information to.
  55498. */
  55499. Particle.prototype.copyTo = function (other) {
  55500. other.position.copyFrom(this.position);
  55501. if (this._initialDirection) {
  55502. if (other._initialDirection) {
  55503. other._initialDirection.copyFrom(this._initialDirection);
  55504. }
  55505. else {
  55506. other._initialDirection = this._initialDirection.clone();
  55507. }
  55508. }
  55509. else {
  55510. other._initialDirection = null;
  55511. }
  55512. other.direction.copyFrom(this.direction);
  55513. other.color.copyFrom(this.color);
  55514. other.colorStep.copyFrom(this.colorStep);
  55515. other.lifeTime = this.lifeTime;
  55516. other.age = this.age;
  55517. other.size = this.size;
  55518. other.scale.copyFrom(this.scale);
  55519. other.angle = this.angle;
  55520. other.angularSpeed = this.angularSpeed;
  55521. other.particleSystem = this.particleSystem;
  55522. other.cellIndex = this.cellIndex;
  55523. if (this._currentColorGradient) {
  55524. other._currentColorGradient = this._currentColorGradient;
  55525. other._currentColor1.copyFrom(this._currentColor1);
  55526. other._currentColor2.copyFrom(this._currentColor2);
  55527. }
  55528. if (this._currentSizeGradient) {
  55529. other._currentSizeGradient = this._currentSizeGradient;
  55530. other._currentSize1 = this._currentSize1;
  55531. other._currentSize2 = this._currentSize2;
  55532. }
  55533. if (this._currentAngularSpeedGradient) {
  55534. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55535. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55536. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55537. }
  55538. if (this._currentVelocityGradient) {
  55539. other._currentVelocityGradient = this._currentVelocityGradient;
  55540. other._currentVelocity1 = this._currentVelocity1;
  55541. other._currentVelocity2 = this._currentVelocity2;
  55542. }
  55543. if (this._currentLimitVelocityGradient) {
  55544. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55545. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55546. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55547. }
  55548. if (this._currentDragGradient) {
  55549. other._currentDragGradient = this._currentDragGradient;
  55550. other._currentDrag1 = this._currentDrag1;
  55551. other._currentDrag2 = this._currentDrag2;
  55552. }
  55553. if (this.particleSystem.isAnimationSheetEnabled) {
  55554. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55555. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55556. }
  55557. };
  55558. return Particle;
  55559. }());
  55560. BABYLON.Particle = Particle;
  55561. })(BABYLON || (BABYLON = {}));
  55562. //# sourceMappingURL=babylon.particle.js.map
  55563. var BABYLON;
  55564. (function (BABYLON) {
  55565. /**
  55566. * This represents the base class for particle system in Babylon.
  55567. * 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.
  55568. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55569. * @example https://doc.babylonjs.com/babylon101/particles
  55570. */
  55571. var BaseParticleSystem = /** @class */ (function () {
  55572. /**
  55573. * Instantiates a particle system.
  55574. * 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.
  55575. * @param name The name of the particle system
  55576. */
  55577. function BaseParticleSystem(name) {
  55578. /**
  55579. * List of animations used by the particle system.
  55580. */
  55581. this.animations = [];
  55582. /**
  55583. * The rendering group used by the Particle system to chose when to render.
  55584. */
  55585. this.renderingGroupId = 0;
  55586. /**
  55587. * The emitter represents the Mesh or position we are attaching the particle system to.
  55588. */
  55589. this.emitter = null;
  55590. /**
  55591. * The maximum number of particles to emit per frame
  55592. */
  55593. this.emitRate = 10;
  55594. /**
  55595. * If you want to launch only a few particles at once, that can be done, as well.
  55596. */
  55597. this.manualEmitCount = -1;
  55598. /**
  55599. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55600. */
  55601. this.updateSpeed = 0.01;
  55602. /**
  55603. * The amount of time the particle system is running (depends of the overall update speed).
  55604. */
  55605. this.targetStopDuration = 0;
  55606. /**
  55607. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55608. */
  55609. this.disposeOnStop = false;
  55610. /**
  55611. * Minimum power of emitting particles.
  55612. */
  55613. this.minEmitPower = 1;
  55614. /**
  55615. * Maximum power of emitting particles.
  55616. */
  55617. this.maxEmitPower = 1;
  55618. /**
  55619. * Minimum life time of emitting particles.
  55620. */
  55621. this.minLifeTime = 1;
  55622. /**
  55623. * Maximum life time of emitting particles.
  55624. */
  55625. this.maxLifeTime = 1;
  55626. /**
  55627. * Minimum Size of emitting particles.
  55628. */
  55629. this.minSize = 1;
  55630. /**
  55631. * Maximum Size of emitting particles.
  55632. */
  55633. this.maxSize = 1;
  55634. /**
  55635. * Minimum scale of emitting particles on X axis.
  55636. */
  55637. this.minScaleX = 1;
  55638. /**
  55639. * Maximum scale of emitting particles on X axis.
  55640. */
  55641. this.maxScaleX = 1;
  55642. /**
  55643. * Minimum scale of emitting particles on Y axis.
  55644. */
  55645. this.minScaleY = 1;
  55646. /**
  55647. * Maximum scale of emitting particles on Y axis.
  55648. */
  55649. this.maxScaleY = 1;
  55650. /**
  55651. * Gets or sets the minimal initial rotation in radians.
  55652. */
  55653. this.minInitialRotation = 0;
  55654. /**
  55655. * Gets or sets the maximal initial rotation in radians.
  55656. */
  55657. this.maxInitialRotation = 0;
  55658. /**
  55659. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55660. */
  55661. this.minAngularSpeed = 0;
  55662. /**
  55663. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55664. */
  55665. this.maxAngularSpeed = 0;
  55666. /**
  55667. * The layer mask we are rendering the particles through.
  55668. */
  55669. this.layerMask = 0x0FFFFFFF;
  55670. /**
  55671. * This can help using your own shader to render the particle system.
  55672. * The according effect will be created
  55673. */
  55674. this.customShader = null;
  55675. /**
  55676. * By default particle system starts as soon as they are created. This prevents the
  55677. * automatic start to happen and let you decide when to start emitting particles.
  55678. */
  55679. this.preventAutoStart = false;
  55680. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55681. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55682. /**
  55683. * Callback triggered when the particle animation is ending.
  55684. */
  55685. this.onAnimationEnd = null;
  55686. /**
  55687. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55688. */
  55689. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55690. /**
  55691. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55692. * to override the particles.
  55693. */
  55694. this.forceDepthWrite = false;
  55695. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55696. this.preWarmCycles = 0;
  55697. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55698. this.preWarmStepOffset = 1;
  55699. /**
  55700. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55701. */
  55702. this.spriteCellChangeSpeed = 1;
  55703. /**
  55704. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55705. */
  55706. this.startSpriteCellID = 0;
  55707. /**
  55708. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55709. */
  55710. this.endSpriteCellID = 0;
  55711. /**
  55712. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55713. */
  55714. this.spriteCellWidth = 0;
  55715. /**
  55716. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55717. */
  55718. this.spriteCellHeight = 0;
  55719. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55720. this.translationPivot = new BABYLON.Vector2(0, 0);
  55721. /**
  55722. * You can use gravity if you want to give an orientation to your particles.
  55723. */
  55724. this.gravity = BABYLON.Vector3.Zero();
  55725. this._colorGradients = null;
  55726. this._sizeGradients = null;
  55727. this._lifeTimeGradients = null;
  55728. this._angularSpeedGradients = null;
  55729. this._velocityGradients = null;
  55730. this._limitVelocityGradients = null;
  55731. this._dragGradients = null;
  55732. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55733. this.limitVelocityDamping = 0.4;
  55734. /**
  55735. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55736. */
  55737. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55738. /**
  55739. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55740. */
  55741. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55742. /**
  55743. * Color the particle will have at the end of its lifetime
  55744. */
  55745. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55746. /**
  55747. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55748. */
  55749. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55750. /**
  55751. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55752. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55753. */
  55754. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55755. this._isBillboardBased = true;
  55756. /**
  55757. * Local cache of defines for image processing.
  55758. */
  55759. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55760. this.id = name;
  55761. this.name = name;
  55762. }
  55763. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55764. /**
  55765. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55766. */
  55767. get: function () {
  55768. return this._isAnimationSheetEnabled;
  55769. },
  55770. set: function (value) {
  55771. if (this._isAnimationSheetEnabled == value) {
  55772. return;
  55773. }
  55774. this._isAnimationSheetEnabled = value;
  55775. this._reset();
  55776. },
  55777. enumerable: true,
  55778. configurable: true
  55779. });
  55780. /**
  55781. * Gets the current list of drag gradients.
  55782. * You must use addDragGradient and removeDragGradient to udpate this list
  55783. * @returns the list of drag gradients
  55784. */
  55785. BaseParticleSystem.prototype.getDragGradients = function () {
  55786. return this._dragGradients;
  55787. };
  55788. /**
  55789. * Gets the current list of limit velocity gradients.
  55790. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55791. * @returns the list of limit velocity gradients
  55792. */
  55793. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55794. return this._limitVelocityGradients;
  55795. };
  55796. /**
  55797. * Gets the current list of color gradients.
  55798. * You must use addColorGradient and removeColorGradient to udpate this list
  55799. * @returns the list of color gradients
  55800. */
  55801. BaseParticleSystem.prototype.getColorGradients = function () {
  55802. return this._colorGradients;
  55803. };
  55804. /**
  55805. * Gets the current list of size gradients.
  55806. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55807. * @returns the list of size gradients
  55808. */
  55809. BaseParticleSystem.prototype.getSizeGradients = function () {
  55810. return this._sizeGradients;
  55811. };
  55812. /**
  55813. * Gets the current list of life time gradients.
  55814. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55815. * @returns the list of life time gradients
  55816. */
  55817. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55818. return this._lifeTimeGradients;
  55819. };
  55820. /**
  55821. * Gets the current list of angular speed gradients.
  55822. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55823. * @returns the list of angular speed gradients
  55824. */
  55825. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55826. return this._angularSpeedGradients;
  55827. };
  55828. /**
  55829. * Gets the current list of velocity gradients.
  55830. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55831. * @returns the list of velocity gradients
  55832. */
  55833. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55834. return this._velocityGradients;
  55835. };
  55836. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55837. /**
  55838. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55839. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55840. */
  55841. get: function () {
  55842. if (this.particleEmitterType.direction1) {
  55843. return this.particleEmitterType.direction1;
  55844. }
  55845. return BABYLON.Vector3.Zero();
  55846. },
  55847. set: function (value) {
  55848. if (this.particleEmitterType.direction1) {
  55849. this.particleEmitterType.direction1 = value;
  55850. }
  55851. },
  55852. enumerable: true,
  55853. configurable: true
  55854. });
  55855. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55856. /**
  55857. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55858. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55859. */
  55860. get: function () {
  55861. if (this.particleEmitterType.direction2) {
  55862. return this.particleEmitterType.direction2;
  55863. }
  55864. return BABYLON.Vector3.Zero();
  55865. },
  55866. set: function (value) {
  55867. if (this.particleEmitterType.direction2) {
  55868. this.particleEmitterType.direction2 = value;
  55869. }
  55870. },
  55871. enumerable: true,
  55872. configurable: true
  55873. });
  55874. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55875. /**
  55876. * 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.
  55877. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55878. */
  55879. get: function () {
  55880. if (this.particleEmitterType.minEmitBox) {
  55881. return this.particleEmitterType.minEmitBox;
  55882. }
  55883. return BABYLON.Vector3.Zero();
  55884. },
  55885. set: function (value) {
  55886. if (this.particleEmitterType.minEmitBox) {
  55887. this.particleEmitterType.minEmitBox = value;
  55888. }
  55889. },
  55890. enumerable: true,
  55891. configurable: true
  55892. });
  55893. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55894. /**
  55895. * 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.
  55896. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55897. */
  55898. get: function () {
  55899. if (this.particleEmitterType.maxEmitBox) {
  55900. return this.particleEmitterType.maxEmitBox;
  55901. }
  55902. return BABYLON.Vector3.Zero();
  55903. },
  55904. set: function (value) {
  55905. if (this.particleEmitterType.maxEmitBox) {
  55906. this.particleEmitterType.maxEmitBox = value;
  55907. }
  55908. },
  55909. enumerable: true,
  55910. configurable: true
  55911. });
  55912. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55913. /**
  55914. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55915. */
  55916. get: function () {
  55917. return this._isBillboardBased;
  55918. },
  55919. set: function (value) {
  55920. if (this._isBillboardBased === value) {
  55921. return;
  55922. }
  55923. this._isBillboardBased = value;
  55924. this._reset();
  55925. },
  55926. enumerable: true,
  55927. configurable: true
  55928. });
  55929. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55930. /**
  55931. * Gets the image processing configuration used either in this material.
  55932. */
  55933. get: function () {
  55934. return this._imageProcessingConfiguration;
  55935. },
  55936. /**
  55937. * Sets the Default image processing configuration used either in the this material.
  55938. *
  55939. * If sets to null, the scene one is in use.
  55940. */
  55941. set: function (value) {
  55942. this._attachImageProcessingConfiguration(value);
  55943. },
  55944. enumerable: true,
  55945. configurable: true
  55946. });
  55947. /**
  55948. * Attaches a new image processing configuration to the Standard Material.
  55949. * @param configuration
  55950. */
  55951. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55952. if (configuration === this._imageProcessingConfiguration) {
  55953. return;
  55954. }
  55955. // Pick the scene configuration if needed.
  55956. if (!configuration) {
  55957. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55958. }
  55959. else {
  55960. this._imageProcessingConfiguration = configuration;
  55961. }
  55962. };
  55963. /** @hidden */
  55964. BaseParticleSystem.prototype._reset = function () {
  55965. };
  55966. /**
  55967. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55968. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55969. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55970. * @returns the emitter
  55971. */
  55972. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55973. var particleEmitter = new BABYLON.PointParticleEmitter();
  55974. particleEmitter.direction1 = direction1;
  55975. particleEmitter.direction2 = direction2;
  55976. this.particleEmitterType = particleEmitter;
  55977. return particleEmitter;
  55978. };
  55979. /**
  55980. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55981. * @param radius The radius of the hemisphere to emit from
  55982. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55983. * @returns the emitter
  55984. */
  55985. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55986. if (radius === void 0) { radius = 1; }
  55987. if (radiusRange === void 0) { radiusRange = 1; }
  55988. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55989. this.particleEmitterType = particleEmitter;
  55990. return particleEmitter;
  55991. };
  55992. /**
  55993. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55994. * @param radius The radius of the sphere to emit from
  55995. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55996. * @returns the emitter
  55997. */
  55998. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55999. if (radius === void 0) { radius = 1; }
  56000. if (radiusRange === void 0) { radiusRange = 1; }
  56001. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56002. this.particleEmitterType = particleEmitter;
  56003. return particleEmitter;
  56004. };
  56005. /**
  56006. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56007. * @param radius The radius of the sphere to emit from
  56008. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56009. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56010. * @returns the emitter
  56011. */
  56012. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56013. if (radius === void 0) { radius = 1; }
  56014. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56015. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56016. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56017. this.particleEmitterType = particleEmitter;
  56018. return particleEmitter;
  56019. };
  56020. /**
  56021. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56022. * @param radius The radius of the emission cylinder
  56023. * @param height The height of the emission cylinder
  56024. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56025. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56026. * @returns the emitter
  56027. */
  56028. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56029. if (radius === void 0) { radius = 1; }
  56030. if (height === void 0) { height = 1; }
  56031. if (radiusRange === void 0) { radiusRange = 1; }
  56032. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56033. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56034. this.particleEmitterType = particleEmitter;
  56035. return particleEmitter;
  56036. };
  56037. /**
  56038. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56039. * @param radius The radius of the cone to emit from
  56040. * @param angle The base angle of the cone
  56041. * @returns the emitter
  56042. */
  56043. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56044. if (radius === void 0) { radius = 1; }
  56045. if (angle === void 0) { angle = Math.PI / 4; }
  56046. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56047. this.particleEmitterType = particleEmitter;
  56048. return particleEmitter;
  56049. };
  56050. /**
  56051. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56052. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56053. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56054. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56055. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56056. * @returns the emitter
  56057. */
  56058. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56059. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56060. this.particleEmitterType = particleEmitter;
  56061. this.direction1 = direction1;
  56062. this.direction2 = direction2;
  56063. this.minEmitBox = minEmitBox;
  56064. this.maxEmitBox = maxEmitBox;
  56065. return particleEmitter;
  56066. };
  56067. /**
  56068. * Source color is added to the destination color without alpha affecting the result.
  56069. */
  56070. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56071. /**
  56072. * Blend current color and particle color using particle’s alpha.
  56073. */
  56074. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56075. /**
  56076. * Add current color and particle color multiplied by particle’s alpha.
  56077. */
  56078. BaseParticleSystem.BLENDMODE_ADD = 2;
  56079. return BaseParticleSystem;
  56080. }());
  56081. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56082. })(BABYLON || (BABYLON = {}));
  56083. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56084. var BABYLON;
  56085. (function (BABYLON) {
  56086. /**
  56087. * This represents a particle system in Babylon.
  56088. * 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.
  56089. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56090. * @example https://doc.babylonjs.com/babylon101/particles
  56091. */
  56092. var ParticleSystem = /** @class */ (function (_super) {
  56093. __extends(ParticleSystem, _super);
  56094. /**
  56095. * Instantiates a particle system.
  56096. * 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.
  56097. * @param name The name of the particle system
  56098. * @param capacity The max number of particles alive at the same time
  56099. * @param scene The scene the particle system belongs to
  56100. * @param customEffect a custom effect used to change the way particles are rendered by default
  56101. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56102. * @param epsilon Offset used to render the particles
  56103. */
  56104. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56105. if (customEffect === void 0) { customEffect = null; }
  56106. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56107. if (epsilon === void 0) { epsilon = 0.01; }
  56108. var _this = _super.call(this, name) || this;
  56109. /**
  56110. * An event triggered when the system is disposed
  56111. */
  56112. _this.onDisposeObservable = new BABYLON.Observable();
  56113. _this._particles = new Array();
  56114. _this._stockParticles = new Array();
  56115. _this._newPartsExcess = 0;
  56116. _this._vertexBuffers = {};
  56117. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56118. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56119. _this._scaledDirection = BABYLON.Vector3.Zero();
  56120. _this._scaledGravity = BABYLON.Vector3.Zero();
  56121. _this._currentRenderId = -1;
  56122. _this._useInstancing = false;
  56123. _this._started = false;
  56124. _this._stopped = false;
  56125. _this._actualFrame = 0;
  56126. // start of sub system methods
  56127. /**
  56128. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56129. * Its lifetime will start back at 0.
  56130. */
  56131. _this.recycleParticle = function (particle) {
  56132. var lastParticle = _this._particles.pop();
  56133. if (lastParticle !== particle) {
  56134. lastParticle.copyTo(particle);
  56135. }
  56136. _this._stockParticles.push(lastParticle);
  56137. };
  56138. _this._createParticle = function () {
  56139. var particle;
  56140. if (_this._stockParticles.length !== 0) {
  56141. particle = _this._stockParticles.pop();
  56142. particle.age = 0;
  56143. particle._currentColorGradient = null;
  56144. particle.cellIndex = _this.startSpriteCellID;
  56145. }
  56146. else {
  56147. particle = new BABYLON.Particle(_this);
  56148. }
  56149. return particle;
  56150. };
  56151. _this._emitFromParticle = function (particle) {
  56152. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56153. return;
  56154. }
  56155. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56156. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56157. subSystem._rootParticleSystem = _this;
  56158. _this.activeSubSystems.push(subSystem);
  56159. subSystem.start();
  56160. };
  56161. _this._capacity = capacity;
  56162. _this._epsilon = epsilon;
  56163. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56164. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56165. // Setup the default processing configuration to the scene.
  56166. _this._attachImageProcessingConfiguration(null);
  56167. _this._customEffect = customEffect;
  56168. _this._scene.particleSystems.push(_this);
  56169. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56170. _this._createIndexBuffer();
  56171. _this._createVertexBuffers();
  56172. // Default emitter type
  56173. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56174. _this.updateFunction = function (particles) {
  56175. var noiseTextureData = null;
  56176. var noiseTextureSize = null;
  56177. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56178. noiseTextureData = (_this.noiseTexture.readPixels());
  56179. noiseTextureSize = _this.noiseTexture.getSize();
  56180. }
  56181. var _loop_1 = function () {
  56182. particle = particles[index];
  56183. particle.age += _this._scaledUpdateSpeed;
  56184. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56185. _this._emitFromParticle(particle);
  56186. _this.recycleParticle(particle);
  56187. index--;
  56188. return "continue";
  56189. }
  56190. else {
  56191. var ratio = particle.age / particle.lifeTime;
  56192. // Color
  56193. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56194. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56195. if (currentGradient !== particle._currentColorGradient) {
  56196. particle._currentColor1.copyFrom(particle._currentColor2);
  56197. nextGradient.getColorToRef(particle._currentColor2);
  56198. particle._currentColorGradient = currentGradient;
  56199. }
  56200. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56201. });
  56202. }
  56203. else {
  56204. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56205. particle.color.addInPlace(_this._scaledColorStep);
  56206. if (particle.color.a < 0) {
  56207. particle.color.a = 0;
  56208. }
  56209. }
  56210. // Angular speed
  56211. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56212. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56213. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56214. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56215. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56216. particle._currentAngularSpeedGradient = currentGradient;
  56217. }
  56218. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56219. });
  56220. }
  56221. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56222. // Direction
  56223. var directionScale_1 = _this._scaledUpdateSpeed;
  56224. /// Velocity
  56225. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56226. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56227. if (currentGradient !== particle._currentVelocityGradient) {
  56228. particle._currentVelocity1 = particle._currentVelocity2;
  56229. particle._currentVelocity2 = nextGradient.getFactor();
  56230. particle._currentVelocityGradient = currentGradient;
  56231. }
  56232. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56233. });
  56234. }
  56235. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56236. /// Limit velocity
  56237. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56238. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56239. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56240. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56241. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56242. particle._currentLimitVelocityGradient = currentGradient;
  56243. }
  56244. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56245. var currentVelocity = particle.direction.length();
  56246. if (currentVelocity > limitVelocity) {
  56247. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56248. }
  56249. });
  56250. }
  56251. /// Drag
  56252. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56253. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56254. if (currentGradient !== particle._currentDragGradient) {
  56255. particle._currentDrag1 = particle._currentDrag2;
  56256. particle._currentDrag2 = nextGradient.getFactor();
  56257. particle._currentDragGradient = currentGradient;
  56258. }
  56259. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56260. _this._scaledDirection.scaleInPlace(drag);
  56261. });
  56262. }
  56263. particle.position.addInPlace(_this._scaledDirection);
  56264. // Noise
  56265. if (noiseTextureData && noiseTextureSize) {
  56266. var localPosition = BABYLON.Tmp.Vector3[0];
  56267. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56268. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56269. particle.position.subtractToRef(emitterPosition, localPosition);
  56270. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56271. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56272. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56273. var force = BABYLON.Tmp.Vector3[0];
  56274. var scaledForce = BABYLON.Tmp.Vector3[1];
  56275. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56276. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56277. particle.direction.addInPlace(scaledForce);
  56278. }
  56279. // Gravity
  56280. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56281. particle.direction.addInPlace(_this._scaledGravity);
  56282. // Size
  56283. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56284. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56285. if (currentGradient !== particle._currentSizeGradient) {
  56286. particle._currentSize1 = particle._currentSize2;
  56287. particle._currentSize2 = nextGradient.getFactor();
  56288. particle._currentSizeGradient = currentGradient;
  56289. }
  56290. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56291. });
  56292. }
  56293. if (_this._isAnimationSheetEnabled) {
  56294. particle.updateCellIndex();
  56295. }
  56296. }
  56297. };
  56298. var particle;
  56299. for (var index = 0; index < particles.length; index++) {
  56300. _loop_1();
  56301. }
  56302. };
  56303. return _this;
  56304. }
  56305. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56306. /**
  56307. * Sets a callback that will be triggered when the system is disposed
  56308. */
  56309. set: function (callback) {
  56310. if (this._onDisposeObserver) {
  56311. this.onDisposeObservable.remove(this._onDisposeObserver);
  56312. }
  56313. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56314. },
  56315. enumerable: true,
  56316. configurable: true
  56317. });
  56318. /**
  56319. * Get hosting scene
  56320. * @returns the scene
  56321. */
  56322. ParticleSystem.prototype.getScene = function () {
  56323. return this._scene;
  56324. };
  56325. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56326. //end of Sub-emitter
  56327. /**
  56328. * Gets the current list of active particles
  56329. */
  56330. get: function () {
  56331. return this._particles;
  56332. },
  56333. enumerable: true,
  56334. configurable: true
  56335. });
  56336. /**
  56337. * Returns the string "ParticleSystem"
  56338. * @returns a string containing the class name
  56339. */
  56340. ParticleSystem.prototype.getClassName = function () {
  56341. return "ParticleSystem";
  56342. };
  56343. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56344. var newGradient = new BABYLON.FactorGradient();
  56345. newGradient.gradient = gradient;
  56346. newGradient.factor1 = factor;
  56347. newGradient.factor2 = factor2;
  56348. factorGradients.push(newGradient);
  56349. factorGradients.sort(function (a, b) {
  56350. if (a.gradient < b.gradient) {
  56351. return -1;
  56352. }
  56353. else if (a.gradient > b.gradient) {
  56354. return 1;
  56355. }
  56356. return 0;
  56357. });
  56358. };
  56359. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56360. if (!factorGradients) {
  56361. return;
  56362. }
  56363. var index = 0;
  56364. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56365. var factorGradient = factorGradients_1[_i];
  56366. if (factorGradient.gradient === gradient) {
  56367. factorGradients.splice(index, 1);
  56368. break;
  56369. }
  56370. index++;
  56371. }
  56372. };
  56373. /**
  56374. * Adds a new life time gradient
  56375. * @param gradient defines the gradient to use (between 0 and 1)
  56376. * @param factor defines the life time factor to affect to the specified gradient
  56377. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56378. * @returns the current particle system
  56379. */
  56380. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56381. if (!this._lifeTimeGradients) {
  56382. this._lifeTimeGradients = [];
  56383. }
  56384. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56385. return this;
  56386. };
  56387. /**
  56388. * Remove a specific life time gradient
  56389. * @param gradient defines the gradient to remove
  56390. * @returns the current particle system
  56391. */
  56392. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56393. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56394. return this;
  56395. };
  56396. /**
  56397. * Adds a new size gradient
  56398. * @param gradient defines the gradient to use (between 0 and 1)
  56399. * @param factor defines the size factor to affect to the specified gradient
  56400. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56401. * @returns the current particle system
  56402. */
  56403. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56404. if (!this._sizeGradients) {
  56405. this._sizeGradients = [];
  56406. }
  56407. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56408. return this;
  56409. };
  56410. /**
  56411. * Remove a specific size gradient
  56412. * @param gradient defines the gradient to remove
  56413. * @returns the current particle system
  56414. */
  56415. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56416. this._removeFactorGradient(this._sizeGradients, gradient);
  56417. return this;
  56418. };
  56419. /**
  56420. * Adds a new angular speed gradient
  56421. * @param gradient defines the gradient to use (between 0 and 1)
  56422. * @param factor defines the angular speed to affect to the specified gradient
  56423. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56424. * @returns the current particle system
  56425. */
  56426. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56427. if (!this._angularSpeedGradients) {
  56428. this._angularSpeedGradients = [];
  56429. }
  56430. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56431. return this;
  56432. };
  56433. /**
  56434. * Remove a specific angular speed gradient
  56435. * @param gradient defines the gradient to remove
  56436. * @returns the current particle system
  56437. */
  56438. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56439. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56440. return this;
  56441. };
  56442. /**
  56443. * Adds a new velocity gradient
  56444. * @param gradient defines the gradient to use (between 0 and 1)
  56445. * @param factor defines the velocity to affect to the specified gradient
  56446. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56447. * @returns the current particle system
  56448. */
  56449. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56450. if (!this._velocityGradients) {
  56451. this._velocityGradients = [];
  56452. }
  56453. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56454. return this;
  56455. };
  56456. /**
  56457. * Remove a specific velocity gradient
  56458. * @param gradient defines the gradient to remove
  56459. * @returns the current particle system
  56460. */
  56461. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56462. this._removeFactorGradient(this._velocityGradients, gradient);
  56463. return this;
  56464. };
  56465. /**
  56466. * Adds a new limit velocity gradient
  56467. * @param gradient defines the gradient to use (between 0 and 1)
  56468. * @param factor defines the limit velocity value to affect to the specified gradient
  56469. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56470. * @returns the current particle system
  56471. */
  56472. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56473. if (!this._limitVelocityGradients) {
  56474. this._limitVelocityGradients = [];
  56475. }
  56476. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56477. return this;
  56478. };
  56479. /**
  56480. * Remove a specific limit velocity gradient
  56481. * @param gradient defines the gradient to remove
  56482. * @returns the current particle system
  56483. */
  56484. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56485. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56486. return this;
  56487. };
  56488. /**
  56489. * Adds a new drag gradient
  56490. * @param gradient defines the gradient to use (between 0 and 1)
  56491. * @param factor defines the drag value to affect to the specified gradient
  56492. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56493. * @returns the current particle system
  56494. */
  56495. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56496. if (!this._dragGradients) {
  56497. this._dragGradients = [];
  56498. }
  56499. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56500. return this;
  56501. };
  56502. /**
  56503. * Remove a specific drag gradient
  56504. * @param gradient defines the gradient to remove
  56505. * @returns the current particle system
  56506. */
  56507. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56508. this._removeFactorGradient(this._dragGradients, gradient);
  56509. return this;
  56510. };
  56511. /**
  56512. * Adds a new color gradient
  56513. * @param gradient defines the gradient to use (between 0 and 1)
  56514. * @param color defines the color to affect to the specified gradient
  56515. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56516. */
  56517. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56518. if (!this._colorGradients) {
  56519. this._colorGradients = [];
  56520. }
  56521. var colorGradient = new BABYLON.ColorGradient();
  56522. colorGradient.gradient = gradient;
  56523. colorGradient.color1 = color;
  56524. colorGradient.color2 = color2;
  56525. this._colorGradients.push(colorGradient);
  56526. this._colorGradients.sort(function (a, b) {
  56527. if (a.gradient < b.gradient) {
  56528. return -1;
  56529. }
  56530. else if (a.gradient > b.gradient) {
  56531. return 1;
  56532. }
  56533. return 0;
  56534. });
  56535. return this;
  56536. };
  56537. /**
  56538. * Remove a specific color gradient
  56539. * @param gradient defines the gradient to remove
  56540. */
  56541. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56542. if (!this._colorGradients) {
  56543. return this;
  56544. }
  56545. var index = 0;
  56546. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56547. var colorGradient = _a[_i];
  56548. if (colorGradient.gradient === gradient) {
  56549. this._colorGradients.splice(index, 1);
  56550. break;
  56551. }
  56552. index++;
  56553. }
  56554. return this;
  56555. };
  56556. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56557. u = Math.abs(u) * 0.5 + 0.5;
  56558. v = Math.abs(v) * 0.5 + 0.5;
  56559. var wrappedU = ((u * width) % width) | 0;
  56560. var wrappedV = ((v * height) % height) | 0;
  56561. var position = (wrappedU + wrappedV * width) * 4;
  56562. return pixels[position] / 255;
  56563. };
  56564. ParticleSystem.prototype._reset = function () {
  56565. this._resetEffect();
  56566. };
  56567. ParticleSystem.prototype._resetEffect = function () {
  56568. if (this._vertexBuffer) {
  56569. this._vertexBuffer.dispose();
  56570. this._vertexBuffer = null;
  56571. }
  56572. if (this._spriteBuffer) {
  56573. this._spriteBuffer.dispose();
  56574. this._spriteBuffer = null;
  56575. }
  56576. this._createVertexBuffers();
  56577. };
  56578. ParticleSystem.prototype._createVertexBuffers = function () {
  56579. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56580. if (this._isAnimationSheetEnabled) {
  56581. this._vertexBufferSize += 1;
  56582. }
  56583. if (!this._isBillboardBased) {
  56584. this._vertexBufferSize += 3;
  56585. }
  56586. var engine = this._scene.getEngine();
  56587. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56588. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56589. var dataOffset = 0;
  56590. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56591. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56592. dataOffset += 3;
  56593. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56594. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56595. dataOffset += 4;
  56596. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56597. this._vertexBuffers["angle"] = options;
  56598. dataOffset += 1;
  56599. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56600. this._vertexBuffers["size"] = size;
  56601. dataOffset += 2;
  56602. if (this._isAnimationSheetEnabled) {
  56603. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56604. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56605. dataOffset += 1;
  56606. }
  56607. if (!this._isBillboardBased) {
  56608. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56609. this._vertexBuffers["direction"] = directionBuffer;
  56610. dataOffset += 3;
  56611. }
  56612. var offsets;
  56613. if (this._useInstancing) {
  56614. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56615. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56616. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56617. }
  56618. else {
  56619. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56620. dataOffset += 2;
  56621. }
  56622. this._vertexBuffers["offset"] = offsets;
  56623. };
  56624. ParticleSystem.prototype._createIndexBuffer = function () {
  56625. if (this._useInstancing) {
  56626. return;
  56627. }
  56628. var indices = [];
  56629. var index = 0;
  56630. for (var count = 0; count < this._capacity; count++) {
  56631. indices.push(index);
  56632. indices.push(index + 1);
  56633. indices.push(index + 2);
  56634. indices.push(index);
  56635. indices.push(index + 2);
  56636. indices.push(index + 3);
  56637. index += 4;
  56638. }
  56639. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56640. };
  56641. /**
  56642. * Gets the maximum number of particles active at the same time.
  56643. * @returns The max number of active particles.
  56644. */
  56645. ParticleSystem.prototype.getCapacity = function () {
  56646. return this._capacity;
  56647. };
  56648. /**
  56649. * Gets whether there are still active particles in the system.
  56650. * @returns True if it is alive, otherwise false.
  56651. */
  56652. ParticleSystem.prototype.isAlive = function () {
  56653. return this._alive;
  56654. };
  56655. /**
  56656. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56657. * @returns True if it has been started, otherwise false.
  56658. */
  56659. ParticleSystem.prototype.isStarted = function () {
  56660. return this._started;
  56661. };
  56662. /**
  56663. * Starts the particle system and begins to emit
  56664. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56665. */
  56666. ParticleSystem.prototype.start = function (delay) {
  56667. var _this = this;
  56668. if (delay === void 0) { delay = 0; }
  56669. if (delay) {
  56670. setTimeout(function () {
  56671. _this.start(0);
  56672. }, delay);
  56673. return;
  56674. }
  56675. this._started = true;
  56676. this._stopped = false;
  56677. this._actualFrame = 0;
  56678. if (this.subEmitters && this.subEmitters.length != 0) {
  56679. this.activeSubSystems = new Array();
  56680. }
  56681. if (this.preWarmCycles) {
  56682. for (var index = 0; index < this.preWarmCycles; index++) {
  56683. this.animate(true);
  56684. }
  56685. }
  56686. };
  56687. /**
  56688. * Stops the particle system.
  56689. * @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.
  56690. */
  56691. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56692. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56693. this._stopped = true;
  56694. if (stopSubEmitters) {
  56695. this._stopSubEmitters();
  56696. }
  56697. };
  56698. // animation sheet
  56699. /**
  56700. * Remove all active particles
  56701. */
  56702. ParticleSystem.prototype.reset = function () {
  56703. this._stockParticles = [];
  56704. this._particles = [];
  56705. };
  56706. /**
  56707. * @hidden (for internal use only)
  56708. */
  56709. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56710. var offset = index * this._vertexBufferSize;
  56711. this._vertexData[offset++] = particle.position.x;
  56712. this._vertexData[offset++] = particle.position.y;
  56713. this._vertexData[offset++] = particle.position.z;
  56714. this._vertexData[offset++] = particle.color.r;
  56715. this._vertexData[offset++] = particle.color.g;
  56716. this._vertexData[offset++] = particle.color.b;
  56717. this._vertexData[offset++] = particle.color.a;
  56718. this._vertexData[offset++] = particle.angle;
  56719. this._vertexData[offset++] = particle.scale.x * particle.size;
  56720. this._vertexData[offset++] = particle.scale.y * particle.size;
  56721. if (this._isAnimationSheetEnabled) {
  56722. this._vertexData[offset++] = particle.cellIndex;
  56723. }
  56724. if (!this._isBillboardBased) {
  56725. if (particle._initialDirection) {
  56726. this._vertexData[offset++] = particle._initialDirection.x;
  56727. this._vertexData[offset++] = particle._initialDirection.y;
  56728. this._vertexData[offset++] = particle._initialDirection.z;
  56729. }
  56730. else {
  56731. this._vertexData[offset++] = particle.direction.x;
  56732. this._vertexData[offset++] = particle.direction.y;
  56733. this._vertexData[offset++] = particle.direction.z;
  56734. }
  56735. }
  56736. if (!this._useInstancing) {
  56737. if (this._isAnimationSheetEnabled) {
  56738. if (offsetX === 0)
  56739. offsetX = this._epsilon;
  56740. else if (offsetX === 1)
  56741. offsetX = 1 - this._epsilon;
  56742. if (offsetY === 0)
  56743. offsetY = this._epsilon;
  56744. else if (offsetY === 1)
  56745. offsetY = 1 - this._epsilon;
  56746. }
  56747. this._vertexData[offset++] = offsetX;
  56748. this._vertexData[offset++] = offsetY;
  56749. }
  56750. };
  56751. ParticleSystem.prototype._stopSubEmitters = function () {
  56752. if (!this.activeSubSystems) {
  56753. return;
  56754. }
  56755. this.activeSubSystems.forEach(function (subSystem) {
  56756. subSystem.stop(true);
  56757. });
  56758. this.activeSubSystems = new Array();
  56759. };
  56760. ParticleSystem.prototype._removeFromRoot = function () {
  56761. if (!this._rootParticleSystem) {
  56762. return;
  56763. }
  56764. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56765. if (index !== -1) {
  56766. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56767. }
  56768. };
  56769. // End of sub system methods
  56770. ParticleSystem.prototype._update = function (newParticles) {
  56771. // Update current
  56772. this._alive = this._particles.length > 0;
  56773. if (this.emitter.position) {
  56774. var emitterMesh = this.emitter;
  56775. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56776. }
  56777. else {
  56778. var emitterPosition = this.emitter;
  56779. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56780. }
  56781. this.updateFunction(this._particles);
  56782. // Add new ones
  56783. var particle;
  56784. var _loop_2 = function () {
  56785. if (this_1._particles.length === this_1._capacity) {
  56786. return "break";
  56787. }
  56788. particle = this_1._createParticle();
  56789. this_1._particles.push(particle);
  56790. // Emitter
  56791. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56792. if (this_1.startPositionFunction) {
  56793. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56794. }
  56795. else {
  56796. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56797. }
  56798. if (this_1.startDirectionFunction) {
  56799. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56800. }
  56801. else {
  56802. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56803. }
  56804. if (emitPower === 0) {
  56805. if (!particle._initialDirection) {
  56806. particle._initialDirection = particle.direction.clone();
  56807. }
  56808. else {
  56809. particle._initialDirection.copyFrom(particle.direction);
  56810. }
  56811. }
  56812. else {
  56813. particle._initialDirection = null;
  56814. }
  56815. particle.direction.scaleInPlace(emitPower);
  56816. // Life time
  56817. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56818. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56819. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56820. var factorGradient1 = currentGradient;
  56821. var factorGradient2 = nextGradient;
  56822. var lifeTime1 = factorGradient1.getFactor();
  56823. var lifeTime2 = factorGradient2.getFactor();
  56824. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56825. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56826. });
  56827. }
  56828. else {
  56829. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56830. }
  56831. // Size
  56832. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56833. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56834. }
  56835. else {
  56836. particle._currentSizeGradient = this_1._sizeGradients[0];
  56837. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56838. particle.size = particle._currentSize1;
  56839. if (this_1._sizeGradients.length > 1) {
  56840. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56841. }
  56842. else {
  56843. particle._currentSize2 = particle._currentSize1;
  56844. }
  56845. }
  56846. // Size and scale
  56847. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56848. // Angle
  56849. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56850. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56851. }
  56852. else {
  56853. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56854. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56855. particle._currentAngularSpeed1 = particle.angularSpeed;
  56856. if (this_1._angularSpeedGradients.length > 1) {
  56857. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56858. }
  56859. else {
  56860. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56861. }
  56862. }
  56863. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56864. // Velocity
  56865. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56866. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56867. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56868. if (this_1._velocityGradients.length > 1) {
  56869. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56870. }
  56871. else {
  56872. particle._currentVelocity2 = particle._currentVelocity1;
  56873. }
  56874. }
  56875. // Limit velocity
  56876. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56877. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56878. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56879. if (this_1._limitVelocityGradients.length > 1) {
  56880. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56881. }
  56882. else {
  56883. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56884. }
  56885. }
  56886. // Drag
  56887. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  56888. particle._currentDragGradient = this_1._dragGradients[0];
  56889. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  56890. if (this_1._dragGradients.length > 1) {
  56891. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  56892. }
  56893. else {
  56894. particle._currentDrag2 = particle._currentDrag1;
  56895. }
  56896. }
  56897. // Color
  56898. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56899. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56900. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56901. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56902. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56903. }
  56904. else {
  56905. particle._currentColorGradient = this_1._colorGradients[0];
  56906. particle._currentColorGradient.getColorToRef(particle.color);
  56907. particle._currentColor1.copyFrom(particle.color);
  56908. if (this_1._colorGradients.length > 1) {
  56909. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56910. }
  56911. else {
  56912. particle._currentColor2.copyFrom(particle.color);
  56913. }
  56914. }
  56915. // Sheet
  56916. if (this_1._isAnimationSheetEnabled) {
  56917. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56918. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56919. }
  56920. };
  56921. var this_1 = this, step;
  56922. for (var index = 0; index < newParticles; index++) {
  56923. var state_1 = _loop_2();
  56924. if (state_1 === "break")
  56925. break;
  56926. }
  56927. };
  56928. /** @hidden */
  56929. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56930. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56931. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56932. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56933. if (isAnimationSheetEnabled) {
  56934. attributeNamesOrOptions.push("cellIndex");
  56935. }
  56936. if (!isBillboardBased) {
  56937. attributeNamesOrOptions.push("direction");
  56938. }
  56939. return attributeNamesOrOptions;
  56940. };
  56941. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56942. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56943. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  56944. if (isAnimationSheetEnabled) {
  56945. effectCreationOption.push("particlesInfos");
  56946. }
  56947. return effectCreationOption;
  56948. };
  56949. ParticleSystem.prototype._getEffect = function () {
  56950. if (this._customEffect) {
  56951. return this._customEffect;
  56952. }
  56953. ;
  56954. var defines = [];
  56955. if (this._scene.clipPlane) {
  56956. defines.push("#define CLIPPLANE");
  56957. }
  56958. if (this._scene.clipPlane2) {
  56959. defines.push("#define CLIPPLANE2");
  56960. }
  56961. if (this._scene.clipPlane3) {
  56962. defines.push("#define CLIPPLANE3");
  56963. }
  56964. if (this._scene.clipPlane4) {
  56965. defines.push("#define CLIPPLANE4");
  56966. }
  56967. if (this._isAnimationSheetEnabled) {
  56968. defines.push("#define ANIMATESHEET");
  56969. }
  56970. if (this._isBillboardBased) {
  56971. defines.push("#define BILLBOARD");
  56972. switch (this.billboardMode) {
  56973. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56974. defines.push("#define BILLBOARDY");
  56975. break;
  56976. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56977. default:
  56978. break;
  56979. }
  56980. }
  56981. if (this._imageProcessingConfiguration) {
  56982. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  56983. defines.push(this._imageProcessingConfigurationDefines.toString());
  56984. }
  56985. // Effect
  56986. var join = defines.join("\n");
  56987. if (this._cachedDefines !== join) {
  56988. this._cachedDefines = join;
  56989. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56990. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56991. var samplers = ["diffuseSampler"];
  56992. if (BABYLON.ImageProcessingConfiguration) {
  56993. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  56994. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  56995. }
  56996. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56997. }
  56998. return this._effect;
  56999. };
  57000. /**
  57001. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57002. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57003. */
  57004. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57005. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57006. if (!this._started)
  57007. return;
  57008. if (!preWarmOnly) {
  57009. var effect = this._getEffect();
  57010. // Check
  57011. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57012. return;
  57013. if (this._currentRenderId === this._scene.getRenderId()) {
  57014. return;
  57015. }
  57016. this._currentRenderId = this._scene.getRenderId();
  57017. }
  57018. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57019. // determine the number of particles we need to create
  57020. var newParticles;
  57021. if (this.manualEmitCount > -1) {
  57022. newParticles = this.manualEmitCount;
  57023. this._newPartsExcess = 0;
  57024. this.manualEmitCount = 0;
  57025. }
  57026. else {
  57027. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  57028. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  57029. }
  57030. if (this._newPartsExcess > 1.0) {
  57031. newParticles += this._newPartsExcess >> 0;
  57032. this._newPartsExcess -= this._newPartsExcess >> 0;
  57033. }
  57034. this._alive = false;
  57035. if (!this._stopped) {
  57036. this._actualFrame += this._scaledUpdateSpeed;
  57037. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57038. this.stop();
  57039. }
  57040. else {
  57041. newParticles = 0;
  57042. }
  57043. this._update(newParticles);
  57044. // Stopped?
  57045. if (this._stopped) {
  57046. if (!this._alive) {
  57047. this._started = false;
  57048. if (this.onAnimationEnd) {
  57049. this.onAnimationEnd();
  57050. }
  57051. if (this.disposeOnStop) {
  57052. this._scene._toBeDisposed.push(this);
  57053. }
  57054. }
  57055. }
  57056. if (!preWarmOnly) {
  57057. // Update VBO
  57058. var offset = 0;
  57059. for (var index = 0; index < this._particles.length; index++) {
  57060. var particle = this._particles[index];
  57061. this._appendParticleVertices(offset, particle);
  57062. offset += this._useInstancing ? 1 : 4;
  57063. }
  57064. if (this._vertexBuffer) {
  57065. this._vertexBuffer.update(this._vertexData);
  57066. }
  57067. }
  57068. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57069. this.stop();
  57070. }
  57071. };
  57072. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57073. this._appendParticleVertex(offset++, particle, 0, 0);
  57074. if (!this._useInstancing) {
  57075. this._appendParticleVertex(offset++, particle, 1, 0);
  57076. this._appendParticleVertex(offset++, particle, 1, 1);
  57077. this._appendParticleVertex(offset++, particle, 0, 1);
  57078. }
  57079. };
  57080. /**
  57081. * Rebuilds the particle system.
  57082. */
  57083. ParticleSystem.prototype.rebuild = function () {
  57084. this._createIndexBuffer();
  57085. if (this._vertexBuffer) {
  57086. this._vertexBuffer._rebuild();
  57087. }
  57088. };
  57089. /**
  57090. * Is this system ready to be used/rendered
  57091. * @return true if the system is ready
  57092. */
  57093. ParticleSystem.prototype.isReady = function () {
  57094. var effect = this._getEffect();
  57095. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57096. return false;
  57097. }
  57098. return true;
  57099. };
  57100. /**
  57101. * Renders the particle system in its current state.
  57102. * @returns the current number of particles
  57103. */
  57104. ParticleSystem.prototype.render = function () {
  57105. var effect = this._getEffect();
  57106. // Check
  57107. if (!this.isReady() || !this._particles.length) {
  57108. return 0;
  57109. }
  57110. var engine = this._scene.getEngine();
  57111. // Render
  57112. engine.enableEffect(effect);
  57113. engine.setState(false);
  57114. var viewMatrix = this._scene.getViewMatrix();
  57115. effect.setTexture("diffuseSampler", this.particleTexture);
  57116. effect.setMatrix("view", viewMatrix);
  57117. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57118. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57119. var baseSize = this.particleTexture.getBaseSize();
  57120. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57121. }
  57122. effect.setVector2("translationPivot", this.translationPivot);
  57123. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57124. if (this._isBillboardBased) {
  57125. var camera = this._scene.activeCamera;
  57126. effect.setVector3("eyePosition", camera.globalPosition);
  57127. }
  57128. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57129. var invView = viewMatrix.clone();
  57130. invView.invert();
  57131. effect.setMatrix("invView", invView);
  57132. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57133. }
  57134. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57135. // image processing
  57136. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57137. this._imageProcessingConfiguration.bind(effect);
  57138. }
  57139. // Draw order
  57140. switch (this.blendMode) {
  57141. case ParticleSystem.BLENDMODE_ADD:
  57142. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57143. break;
  57144. case ParticleSystem.BLENDMODE_ONEONE:
  57145. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57146. break;
  57147. case ParticleSystem.BLENDMODE_STANDARD:
  57148. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57149. break;
  57150. }
  57151. if (this.forceDepthWrite) {
  57152. engine.setDepthWrite(true);
  57153. }
  57154. if (this._useInstancing) {
  57155. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57156. engine.unbindInstanceAttributes();
  57157. }
  57158. else {
  57159. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57160. }
  57161. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57162. return this._particles.length;
  57163. };
  57164. /**
  57165. * Disposes the particle system and free the associated resources
  57166. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57167. */
  57168. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57169. if (disposeTexture === void 0) { disposeTexture = true; }
  57170. if (this._vertexBuffer) {
  57171. this._vertexBuffer.dispose();
  57172. this._vertexBuffer = null;
  57173. }
  57174. if (this._spriteBuffer) {
  57175. this._spriteBuffer.dispose();
  57176. this._spriteBuffer = null;
  57177. }
  57178. if (this._indexBuffer) {
  57179. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57180. this._indexBuffer = null;
  57181. }
  57182. if (disposeTexture && this.particleTexture) {
  57183. this.particleTexture.dispose();
  57184. this.particleTexture = null;
  57185. }
  57186. if (disposeTexture && this.noiseTexture) {
  57187. this.noiseTexture.dispose();
  57188. this.noiseTexture = null;
  57189. }
  57190. this._removeFromRoot();
  57191. // Remove from scene
  57192. var index = this._scene.particleSystems.indexOf(this);
  57193. if (index > -1) {
  57194. this._scene.particleSystems.splice(index, 1);
  57195. }
  57196. // Callback
  57197. this.onDisposeObservable.notifyObservers(this);
  57198. this.onDisposeObservable.clear();
  57199. };
  57200. // Clone
  57201. /**
  57202. * Clones the particle system.
  57203. * @param name The name of the cloned object
  57204. * @param newEmitter The new emitter to use
  57205. * @returns the cloned particle system
  57206. */
  57207. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57208. var custom = null;
  57209. var program = null;
  57210. if (this.customShader != null) {
  57211. program = this.customShader;
  57212. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57213. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57214. }
  57215. else if (this._customEffect) {
  57216. custom = this._customEffect;
  57217. }
  57218. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57219. result.customShader = program;
  57220. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57221. if (newEmitter === undefined) {
  57222. newEmitter = this.emitter;
  57223. }
  57224. result.emitter = newEmitter;
  57225. if (this.particleTexture) {
  57226. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57227. }
  57228. if (!this.preventAutoStart) {
  57229. result.start();
  57230. }
  57231. return result;
  57232. };
  57233. /**
  57234. * Serializes the particle system to a JSON object.
  57235. * @returns the JSON object
  57236. */
  57237. ParticleSystem.prototype.serialize = function () {
  57238. var serializationObject = {};
  57239. ParticleSystem._Serialize(serializationObject, this);
  57240. serializationObject.textureMask = this.textureMask.asArray();
  57241. serializationObject.customShader = this.customShader;
  57242. serializationObject.preventAutoStart = this.preventAutoStart;
  57243. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57244. return serializationObject;
  57245. };
  57246. /** @hidden */
  57247. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57248. serializationObject.name = particleSystem.name;
  57249. serializationObject.id = particleSystem.id;
  57250. serializationObject.capacity = particleSystem.getCapacity();
  57251. // Emitter
  57252. if (particleSystem.emitter.position) {
  57253. var emitterMesh = particleSystem.emitter;
  57254. serializationObject.emitterId = emitterMesh.id;
  57255. }
  57256. else {
  57257. var emitterPosition = particleSystem.emitter;
  57258. serializationObject.emitter = emitterPosition.asArray();
  57259. }
  57260. // Emitter
  57261. if (particleSystem.particleEmitterType) {
  57262. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57263. }
  57264. if (particleSystem.particleTexture) {
  57265. serializationObject.textureName = particleSystem.particleTexture.name;
  57266. }
  57267. // Animations
  57268. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57269. // Particle system
  57270. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57271. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57272. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57273. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57274. serializationObject.minSize = particleSystem.minSize;
  57275. serializationObject.maxSize = particleSystem.maxSize;
  57276. serializationObject.minScaleX = particleSystem.minScaleX;
  57277. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57278. serializationObject.minScaleY = particleSystem.minScaleY;
  57279. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57280. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57281. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57282. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57283. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57284. serializationObject.emitRate = particleSystem.emitRate;
  57285. serializationObject.gravity = particleSystem.gravity.asArray();
  57286. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57287. serializationObject.color1 = particleSystem.color1.asArray();
  57288. serializationObject.color2 = particleSystem.color2.asArray();
  57289. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57290. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57291. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57292. serializationObject.blendMode = particleSystem.blendMode;
  57293. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57294. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57295. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57296. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57297. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57298. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57299. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57300. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57301. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57302. var colorGradients = particleSystem.getColorGradients();
  57303. if (colorGradients) {
  57304. serializationObject.colorGradients = [];
  57305. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57306. var colorGradient = colorGradients_1[_i];
  57307. var serializedGradient = {
  57308. gradient: colorGradient.gradient,
  57309. color1: colorGradient.color1.asArray()
  57310. };
  57311. if (colorGradient.color2) {
  57312. serializedGradient.color2 = colorGradient.color2.asArray();
  57313. }
  57314. serializationObject.colorGradients.push(serializedGradient);
  57315. }
  57316. }
  57317. var sizeGradients = particleSystem.getSizeGradients();
  57318. if (sizeGradients) {
  57319. serializationObject.sizeGradients = [];
  57320. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57321. var sizeGradient = sizeGradients_1[_a];
  57322. var serializedGradient = {
  57323. gradient: sizeGradient.gradient,
  57324. factor1: sizeGradient.factor1
  57325. };
  57326. if (sizeGradient.factor2 !== undefined) {
  57327. serializedGradient.factor2 = sizeGradient.factor2;
  57328. }
  57329. serializationObject.sizeGradients.push(serializedGradient);
  57330. }
  57331. }
  57332. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57333. if (angularSpeedGradients) {
  57334. serializationObject.angularSpeedGradients = [];
  57335. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57336. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57337. var serializedGradient = {
  57338. gradient: angularSpeedGradient.gradient,
  57339. factor1: angularSpeedGradient.factor1
  57340. };
  57341. if (angularSpeedGradient.factor2 !== undefined) {
  57342. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57343. }
  57344. serializationObject.angularSpeedGradients.push(serializedGradient);
  57345. }
  57346. }
  57347. var velocityGradients = particleSystem.getVelocityGradients();
  57348. if (velocityGradients) {
  57349. serializationObject.velocityGradients = [];
  57350. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57351. var velocityGradient = velocityGradients_1[_c];
  57352. var serializedGradient = {
  57353. gradient: velocityGradient.gradient,
  57354. factor1: velocityGradient.factor1
  57355. };
  57356. if (velocityGradient.factor2 !== undefined) {
  57357. serializedGradient.factor2 = velocityGradient.factor2;
  57358. }
  57359. serializationObject.velocityGradients.push(serializedGradient);
  57360. }
  57361. }
  57362. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57363. if (limitVelocityGradients) {
  57364. serializationObject.limitVelocityGradients = [];
  57365. for (var _d = 0, limitVelocityGradients_1 = limitVelocityGradients; _d < limitVelocityGradients_1.length; _d++) {
  57366. var limitVelocityGradient = limitVelocityGradients_1[_d];
  57367. var serializedGradient = {
  57368. gradient: limitVelocityGradient.gradient,
  57369. factor1: limitVelocityGradient.factor1
  57370. };
  57371. if (limitVelocityGradient.factor2 !== undefined) {
  57372. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57373. }
  57374. serializationObject.limitVelocityGradients.push(serializedGradient);
  57375. }
  57376. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57377. }
  57378. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57379. var noiseTexture = particleSystem.noiseTexture;
  57380. serializationObject.noiseTexture = noiseTexture.serialize();
  57381. }
  57382. };
  57383. /** @hidden */
  57384. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57385. // Texture
  57386. if (parsedParticleSystem.textureName) {
  57387. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57388. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57389. }
  57390. // Emitter
  57391. if (parsedParticleSystem.emitterId === undefined) {
  57392. particleSystem.emitter = BABYLON.Vector3.Zero();
  57393. }
  57394. else if (parsedParticleSystem.emitterId) {
  57395. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57396. }
  57397. else {
  57398. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57399. }
  57400. // Misc.
  57401. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57402. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57403. }
  57404. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57405. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57406. }
  57407. // Animations
  57408. if (parsedParticleSystem.animations) {
  57409. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57410. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57411. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57412. }
  57413. }
  57414. if (parsedParticleSystem.autoAnimate) {
  57415. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57416. }
  57417. // Particle system
  57418. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57419. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57420. particleSystem.minSize = parsedParticleSystem.minSize;
  57421. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57422. if (parsedParticleSystem.minScaleX) {
  57423. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57424. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57425. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57426. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57427. }
  57428. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57429. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57430. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57431. }
  57432. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57433. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57434. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57435. }
  57436. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57437. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57438. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57439. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57440. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57441. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57442. if (parsedParticleSystem.noiseStrength) {
  57443. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57444. }
  57445. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57446. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57447. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57448. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57449. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57450. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57451. if (parsedParticleSystem.colorGradients) {
  57452. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57453. var colorGradient = _a[_i];
  57454. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57455. }
  57456. }
  57457. if (parsedParticleSystem.sizeGradients) {
  57458. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57459. var sizeGradient = _c[_b];
  57460. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57461. }
  57462. }
  57463. if (parsedParticleSystem.angularSpeedGradients) {
  57464. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57465. var angularSpeedGradient = _e[_d];
  57466. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57467. }
  57468. }
  57469. if (parsedParticleSystem.velocityGradients) {
  57470. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57471. var velocityGradient = _g[_f];
  57472. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57473. }
  57474. }
  57475. if (parsedParticleSystem.limitVelocityGradients) {
  57476. for (var _h = 0, _j = parsedParticleSystem.limitVelocityGradients; _h < _j.length; _h++) {
  57477. var limitVelocityGradient = _j[_h];
  57478. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57479. }
  57480. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57481. }
  57482. if (parsedParticleSystem.noiseTexture) {
  57483. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57484. }
  57485. // Emitter
  57486. var emitterType;
  57487. if (parsedParticleSystem.particleEmitterType) {
  57488. switch (parsedParticleSystem.particleEmitterType.type) {
  57489. case "SphereParticleEmitter":
  57490. emitterType = new BABYLON.SphereParticleEmitter();
  57491. break;
  57492. case "SphereDirectedParticleEmitter":
  57493. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57494. break;
  57495. case "ConeEmitter":
  57496. case "ConeParticleEmitter":
  57497. emitterType = new BABYLON.ConeParticleEmitter();
  57498. break;
  57499. case "BoxEmitter":
  57500. case "BoxParticleEmitter":
  57501. default:
  57502. emitterType = new BABYLON.BoxParticleEmitter();
  57503. break;
  57504. }
  57505. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57506. }
  57507. else {
  57508. emitterType = new BABYLON.BoxParticleEmitter();
  57509. emitterType.parse(parsedParticleSystem);
  57510. }
  57511. particleSystem.particleEmitterType = emitterType;
  57512. // Animation sheet
  57513. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57514. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57515. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57516. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57517. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57518. };
  57519. /**
  57520. * Parses a JSON object to create a particle system.
  57521. * @param parsedParticleSystem The JSON object to parse
  57522. * @param scene The scene to create the particle system in
  57523. * @param rootUrl The root url to use to load external dependencies like texture
  57524. * @returns the Parsed particle system
  57525. */
  57526. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57527. var name = parsedParticleSystem.name;
  57528. var custom = null;
  57529. var program = null;
  57530. if (parsedParticleSystem.customShader) {
  57531. program = parsedParticleSystem.customShader;
  57532. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57533. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57534. }
  57535. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57536. particleSystem.customShader = program;
  57537. if (parsedParticleSystem.id) {
  57538. particleSystem.id = parsedParticleSystem.id;
  57539. }
  57540. // Auto start
  57541. if (parsedParticleSystem.preventAutoStart) {
  57542. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57543. }
  57544. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57545. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57546. if (!particleSystem.preventAutoStart) {
  57547. particleSystem.start();
  57548. }
  57549. return particleSystem;
  57550. };
  57551. return ParticleSystem;
  57552. }(BABYLON.BaseParticleSystem));
  57553. BABYLON.ParticleSystem = ParticleSystem;
  57554. })(BABYLON || (BABYLON = {}));
  57555. //# sourceMappingURL=babylon.particleSystem.js.map
  57556. var BABYLON;
  57557. (function (BABYLON) {
  57558. /**
  57559. * Particle emitter emitting particles from the inside of a box.
  57560. * It emits the particles randomly between 2 given directions.
  57561. */
  57562. var BoxParticleEmitter = /** @class */ (function () {
  57563. /**
  57564. * Creates a new instance BoxParticleEmitter
  57565. */
  57566. function BoxParticleEmitter() {
  57567. /**
  57568. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57569. */
  57570. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57571. /**
  57572. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57573. */
  57574. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57575. /**
  57576. * 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.
  57577. */
  57578. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57579. /**
  57580. * 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.
  57581. */
  57582. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57583. }
  57584. /**
  57585. * Called by the particle System when the direction is computed for the created particle.
  57586. * @param worldMatrix is the world matrix of the particle system
  57587. * @param directionToUpdate is the direction vector to update with the result
  57588. * @param particle is the particle we are computed the direction for
  57589. */
  57590. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57591. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57592. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57593. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57594. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57595. };
  57596. /**
  57597. * Called by the particle System when the position is computed for the created particle.
  57598. * @param worldMatrix is the world matrix of the particle system
  57599. * @param positionToUpdate is the position vector to update with the result
  57600. * @param particle is the particle we are computed the position for
  57601. */
  57602. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57603. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57604. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57605. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57606. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57607. };
  57608. /**
  57609. * Clones the current emitter and returns a copy of it
  57610. * @returns the new emitter
  57611. */
  57612. BoxParticleEmitter.prototype.clone = function () {
  57613. var newOne = new BoxParticleEmitter();
  57614. BABYLON.Tools.DeepCopy(this, newOne);
  57615. return newOne;
  57616. };
  57617. /**
  57618. * Called by the GPUParticleSystem to setup the update shader
  57619. * @param effect defines the update shader
  57620. */
  57621. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57622. effect.setVector3("direction1", this.direction1);
  57623. effect.setVector3("direction2", this.direction2);
  57624. effect.setVector3("minEmitBox", this.minEmitBox);
  57625. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57626. };
  57627. /**
  57628. * Returns a string to use to update the GPU particles update shader
  57629. * @returns a string containng the defines string
  57630. */
  57631. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57632. return "#define BOXEMITTER";
  57633. };
  57634. /**
  57635. * Returns the string "BoxParticleEmitter"
  57636. * @returns a string containing the class name
  57637. */
  57638. BoxParticleEmitter.prototype.getClassName = function () {
  57639. return "BoxParticleEmitter";
  57640. };
  57641. /**
  57642. * Serializes the particle system to a JSON object.
  57643. * @returns the JSON object
  57644. */
  57645. BoxParticleEmitter.prototype.serialize = function () {
  57646. var serializationObject = {};
  57647. serializationObject.type = this.getClassName();
  57648. serializationObject.direction1 = this.direction1.asArray();
  57649. serializationObject.direction2 = this.direction2.asArray();
  57650. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57651. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57652. return serializationObject;
  57653. };
  57654. /**
  57655. * Parse properties from a JSON object
  57656. * @param serializationObject defines the JSON object
  57657. */
  57658. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57659. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57660. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57661. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57662. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57663. };
  57664. return BoxParticleEmitter;
  57665. }());
  57666. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57667. })(BABYLON || (BABYLON = {}));
  57668. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57669. var BABYLON;
  57670. (function (BABYLON) {
  57671. /**
  57672. * Particle emitter emitting particles from the inside of a cylinder.
  57673. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  57674. */
  57675. var CylinderParticleEmitter = /** @class */ (function () {
  57676. /**
  57677. * Creates a new instance CylinderParticleEmitter
  57678. * @param radius the radius of the emission cylinder (1 by default)
  57679. * @param height the height of the emission cylinder (1 by default)
  57680. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57681. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57682. */
  57683. function CylinderParticleEmitter(
  57684. /**
  57685. * The radius of the emission cylinder.
  57686. */
  57687. radius,
  57688. /**
  57689. * The height of the emission cylinder.
  57690. */
  57691. height,
  57692. /**
  57693. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57694. */
  57695. radiusRange,
  57696. /**
  57697. * How much to randomize the particle direction [0-1].
  57698. */
  57699. directionRandomizer) {
  57700. if (radius === void 0) { radius = 1; }
  57701. if (height === void 0) { height = 1; }
  57702. if (radiusRange === void 0) { radiusRange = 1; }
  57703. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57704. this.radius = radius;
  57705. this.height = height;
  57706. this.radiusRange = radiusRange;
  57707. this.directionRandomizer = directionRandomizer;
  57708. }
  57709. /**
  57710. * Called by the particle System when the direction is computed for the created particle.
  57711. * @param worldMatrix is the world matrix of the particle system
  57712. * @param directionToUpdate is the direction vector to update with the result
  57713. * @param particle is the particle we are computed the direction for
  57714. */
  57715. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57716. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57717. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  57718. var angle = Math.atan2(direction.x, direction.z);
  57719. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  57720. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  57721. direction.x = Math.sin(angle);
  57722. direction.z = Math.cos(angle);
  57723. direction.normalize();
  57724. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57725. };
  57726. /**
  57727. * Called by the particle System when the position is computed for the created particle.
  57728. * @param worldMatrix is the world matrix of the particle system
  57729. * @param positionToUpdate is the position vector to update with the result
  57730. * @param particle is the particle we are computed the position for
  57731. */
  57732. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57733. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  57734. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57735. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  57736. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  57737. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  57738. var xPos = positionRadius * Math.cos(angle);
  57739. var zPos = positionRadius * Math.sin(angle);
  57740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  57741. };
  57742. /**
  57743. * Clones the current emitter and returns a copy of it
  57744. * @returns the new emitter
  57745. */
  57746. CylinderParticleEmitter.prototype.clone = function () {
  57747. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  57748. BABYLON.Tools.DeepCopy(this, newOne);
  57749. return newOne;
  57750. };
  57751. /**
  57752. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57753. * @param effect defines the update shader
  57754. */
  57755. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  57756. effect.setFloat("radius", this.radius);
  57757. effect.setFloat("height", this.height);
  57758. effect.setFloat("radiusRange", this.radiusRange);
  57759. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57760. };
  57761. /**
  57762. * Returns a string to use to update the GPU particles update shader
  57763. * @returns a string containng the defines string
  57764. */
  57765. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  57766. return "#define CYLINDEREMITTER";
  57767. };
  57768. /**
  57769. * Returns the string "CylinderParticleEmitter"
  57770. * @returns a string containing the class name
  57771. */
  57772. CylinderParticleEmitter.prototype.getClassName = function () {
  57773. return "CylinderParticleEmitter";
  57774. };
  57775. /**
  57776. * Serializes the particle system to a JSON object.
  57777. * @returns the JSON object
  57778. */
  57779. CylinderParticleEmitter.prototype.serialize = function () {
  57780. var serializationObject = {};
  57781. serializationObject.type = this.getClassName();
  57782. serializationObject.radius = this.radius;
  57783. serializationObject.height = this.height;
  57784. serializationObject.radiusRange = this.radiusRange;
  57785. serializationObject.directionRandomizer = this.directionRandomizer;
  57786. return serializationObject;
  57787. };
  57788. /**
  57789. * Parse properties from a JSON object
  57790. * @param serializationObject defines the JSON object
  57791. */
  57792. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  57793. this.radius = serializationObject.radius;
  57794. this.height = serializationObject.height;
  57795. this.radiusRange = serializationObject.radiusRange;
  57796. this.directionRandomizer = serializationObject.directionRandomizer;
  57797. };
  57798. return CylinderParticleEmitter;
  57799. }());
  57800. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  57801. })(BABYLON || (BABYLON = {}));
  57802. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  57803. var BABYLON;
  57804. (function (BABYLON) {
  57805. /**
  57806. * Particle emitter emitting particles from the inside of a cone.
  57807. * It emits the particles alongside the cone volume from the base to the particle.
  57808. * The emission direction might be randomized.
  57809. */
  57810. var ConeParticleEmitter = /** @class */ (function () {
  57811. /**
  57812. * Creates a new instance ConeParticleEmitter
  57813. * @param radius the radius of the emission cone (1 by default)
  57814. * @param angles the cone base angle (PI by default)
  57815. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57816. */
  57817. function ConeParticleEmitter(radius, angle,
  57818. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57819. directionRandomizer) {
  57820. if (radius === void 0) { radius = 1; }
  57821. if (angle === void 0) { angle = Math.PI; }
  57822. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57823. this.directionRandomizer = directionRandomizer;
  57824. /**
  57825. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57826. */
  57827. this.radiusRange = 1;
  57828. /**
  57829. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57830. */
  57831. this.heightRange = 1;
  57832. /**
  57833. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57834. */
  57835. this.emitFromSpawnPointOnly = false;
  57836. this.angle = angle;
  57837. this.radius = radius;
  57838. }
  57839. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57840. /**
  57841. * Gets or sets the radius of the emission cone
  57842. */
  57843. get: function () {
  57844. return this._radius;
  57845. },
  57846. set: function (value) {
  57847. this._radius = value;
  57848. this._buildHeight();
  57849. },
  57850. enumerable: true,
  57851. configurable: true
  57852. });
  57853. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57854. /**
  57855. * Gets or sets the angle of the emission cone
  57856. */
  57857. get: function () {
  57858. return this._angle;
  57859. },
  57860. set: function (value) {
  57861. this._angle = value;
  57862. this._buildHeight();
  57863. },
  57864. enumerable: true,
  57865. configurable: true
  57866. });
  57867. ConeParticleEmitter.prototype._buildHeight = function () {
  57868. if (this._angle !== 0) {
  57869. this._height = this._radius / Math.tan(this._angle / 2);
  57870. }
  57871. else {
  57872. this._height = 1;
  57873. }
  57874. };
  57875. /**
  57876. * Called by the particle System when the direction is computed for the created particle.
  57877. * @param worldMatrix is the world matrix of the particle system
  57878. * @param directionToUpdate is the direction vector to update with the result
  57879. * @param particle is the particle we are computed the direction for
  57880. */
  57881. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57882. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57883. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57884. }
  57885. else {
  57886. // measure the direction Vector from the emitter to the particle.
  57887. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57888. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57889. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57890. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57891. direction.x += randX;
  57892. direction.y += randY;
  57893. direction.z += randZ;
  57894. direction.normalize();
  57895. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57896. }
  57897. };
  57898. /**
  57899. * Called by the particle System when the position is computed for the created particle.
  57900. * @param worldMatrix is the world matrix of the particle system
  57901. * @param positionToUpdate is the position vector to update with the result
  57902. * @param particle is the particle we are computed the position for
  57903. */
  57904. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57905. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57906. var h;
  57907. if (!this.emitFromSpawnPointOnly) {
  57908. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57909. // Better distribution in a cone at normal angles.
  57910. h = 1 - h * h;
  57911. }
  57912. else {
  57913. h = 0.0001;
  57914. }
  57915. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57916. radius = radius * h;
  57917. var randX = radius * Math.sin(s);
  57918. var randZ = radius * Math.cos(s);
  57919. var randY = h * this._height;
  57920. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57921. };
  57922. /**
  57923. * Clones the current emitter and returns a copy of it
  57924. * @returns the new emitter
  57925. */
  57926. ConeParticleEmitter.prototype.clone = function () {
  57927. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57928. BABYLON.Tools.DeepCopy(this, newOne);
  57929. return newOne;
  57930. };
  57931. /**
  57932. * Called by the GPUParticleSystem to setup the update shader
  57933. * @param effect defines the update shader
  57934. */
  57935. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57936. effect.setFloat2("radius", this._radius, this.radiusRange);
  57937. effect.setFloat("coneAngle", this._angle);
  57938. effect.setFloat2("height", this._height, this.heightRange);
  57939. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57940. };
  57941. /**
  57942. * Returns a string to use to update the GPU particles update shader
  57943. * @returns a string containng the defines string
  57944. */
  57945. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57946. var defines = "#define CONEEMITTER";
  57947. if (this.emitFromSpawnPointOnly) {
  57948. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57949. }
  57950. return defines;
  57951. };
  57952. /**
  57953. * Returns the string "ConeParticleEmitter"
  57954. * @returns a string containing the class name
  57955. */
  57956. ConeParticleEmitter.prototype.getClassName = function () {
  57957. return "ConeParticleEmitter";
  57958. };
  57959. /**
  57960. * Serializes the particle system to a JSON object.
  57961. * @returns the JSON object
  57962. */
  57963. ConeParticleEmitter.prototype.serialize = function () {
  57964. var serializationObject = {};
  57965. serializationObject.type = this.getClassName();
  57966. serializationObject.radius = this._radius;
  57967. serializationObject.angle = this._angle;
  57968. serializationObject.directionRandomizer = this.directionRandomizer;
  57969. return serializationObject;
  57970. };
  57971. /**
  57972. * Parse properties from a JSON object
  57973. * @param serializationObject defines the JSON object
  57974. */
  57975. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57976. this.radius = serializationObject.radius;
  57977. this.angle = serializationObject.angle;
  57978. this.directionRandomizer = serializationObject.directionRandomizer;
  57979. };
  57980. return ConeParticleEmitter;
  57981. }());
  57982. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57983. })(BABYLON || (BABYLON = {}));
  57984. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57985. var BABYLON;
  57986. (function (BABYLON) {
  57987. /**
  57988. * Particle emitter emitting particles from the inside of a sphere.
  57989. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57990. */
  57991. var SphereParticleEmitter = /** @class */ (function () {
  57992. /**
  57993. * Creates a new instance SphereParticleEmitter
  57994. * @param radius the radius of the emission sphere (1 by default)
  57995. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57996. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57997. */
  57998. function SphereParticleEmitter(
  57999. /**
  58000. * The radius of the emission sphere.
  58001. */
  58002. radius,
  58003. /**
  58004. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58005. */
  58006. radiusRange,
  58007. /**
  58008. * How much to randomize the particle direction [0-1].
  58009. */
  58010. directionRandomizer) {
  58011. if (radius === void 0) { radius = 1; }
  58012. if (radiusRange === void 0) { radiusRange = 1; }
  58013. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58014. this.radius = radius;
  58015. this.radiusRange = radiusRange;
  58016. this.directionRandomizer = directionRandomizer;
  58017. }
  58018. /**
  58019. * Called by the particle System when the direction is computed for the created particle.
  58020. * @param worldMatrix is the world matrix of the particle system
  58021. * @param directionToUpdate is the direction vector to update with the result
  58022. * @param particle is the particle we are computed the direction for
  58023. */
  58024. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58025. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58026. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58027. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58028. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58029. direction.x += randX;
  58030. direction.y += randY;
  58031. direction.z += randZ;
  58032. direction.normalize();
  58033. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58034. };
  58035. /**
  58036. * Called by the particle System when the position is computed for the created particle.
  58037. * @param worldMatrix is the world matrix of the particle system
  58038. * @param positionToUpdate is the position vector to update with the result
  58039. * @param particle is the particle we are computed the position for
  58040. */
  58041. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58042. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58043. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58044. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58045. var theta = Math.acos(2 * v - 1);
  58046. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58047. var randY = randRadius * Math.cos(theta);
  58048. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58049. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58050. };
  58051. /**
  58052. * Clones the current emitter and returns a copy of it
  58053. * @returns the new emitter
  58054. */
  58055. SphereParticleEmitter.prototype.clone = function () {
  58056. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58057. BABYLON.Tools.DeepCopy(this, newOne);
  58058. return newOne;
  58059. };
  58060. /**
  58061. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58062. * @param effect defines the update shader
  58063. */
  58064. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58065. effect.setFloat("radius", this.radius);
  58066. effect.setFloat("radiusRange", this.radiusRange);
  58067. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58068. };
  58069. /**
  58070. * Returns a string to use to update the GPU particles update shader
  58071. * @returns a string containng the defines string
  58072. */
  58073. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58074. return "#define SPHEREEMITTER";
  58075. };
  58076. /**
  58077. * Returns the string "SphereParticleEmitter"
  58078. * @returns a string containing the class name
  58079. */
  58080. SphereParticleEmitter.prototype.getClassName = function () {
  58081. return "SphereParticleEmitter";
  58082. };
  58083. /**
  58084. * Serializes the particle system to a JSON object.
  58085. * @returns the JSON object
  58086. */
  58087. SphereParticleEmitter.prototype.serialize = function () {
  58088. var serializationObject = {};
  58089. serializationObject.type = this.getClassName();
  58090. serializationObject.radius = this.radius;
  58091. serializationObject.radiusRange = this.radiusRange;
  58092. serializationObject.directionRandomizer = this.directionRandomizer;
  58093. return serializationObject;
  58094. };
  58095. /**
  58096. * Parse properties from a JSON object
  58097. * @param serializationObject defines the JSON object
  58098. */
  58099. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58100. this.radius = serializationObject.radius;
  58101. this.radiusRange = serializationObject.radiusRange;
  58102. this.directionRandomizer = serializationObject.directionRandomizer;
  58103. };
  58104. return SphereParticleEmitter;
  58105. }());
  58106. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58107. /**
  58108. * Particle emitter emitting particles from the inside of a sphere.
  58109. * It emits the particles randomly between two vectors.
  58110. */
  58111. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58112. __extends(SphereDirectedParticleEmitter, _super);
  58113. /**
  58114. * Creates a new instance SphereDirectedParticleEmitter
  58115. * @param radius the radius of the emission sphere (1 by default)
  58116. * @param direction1 the min limit of the emission direction (up vector by default)
  58117. * @param direction2 the max limit of the emission direction (up vector by default)
  58118. */
  58119. function SphereDirectedParticleEmitter(radius,
  58120. /**
  58121. * The min limit of the emission direction.
  58122. */
  58123. direction1,
  58124. /**
  58125. * The max limit of the emission direction.
  58126. */
  58127. direction2) {
  58128. if (radius === void 0) { radius = 1; }
  58129. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58130. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58131. var _this = _super.call(this, radius) || this;
  58132. _this.direction1 = direction1;
  58133. _this.direction2 = direction2;
  58134. return _this;
  58135. }
  58136. /**
  58137. * Called by the particle System when the direction is computed for the created particle.
  58138. * @param worldMatrix is the world matrix of the particle system
  58139. * @param directionToUpdate is the direction vector to update with the result
  58140. * @param particle is the particle we are computed the direction for
  58141. */
  58142. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58143. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58144. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58145. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58146. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58147. };
  58148. /**
  58149. * Clones the current emitter and returns a copy of it
  58150. * @returns the new emitter
  58151. */
  58152. SphereDirectedParticleEmitter.prototype.clone = function () {
  58153. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58154. BABYLON.Tools.DeepCopy(this, newOne);
  58155. return newOne;
  58156. };
  58157. /**
  58158. * Called by the GPUParticleSystem to setup the update shader
  58159. * @param effect defines the update shader
  58160. */
  58161. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58162. effect.setFloat("radius", this.radius);
  58163. effect.setFloat("radiusRange", this.radiusRange);
  58164. effect.setVector3("direction1", this.direction1);
  58165. effect.setVector3("direction2", this.direction2);
  58166. };
  58167. /**
  58168. * Returns a string to use to update the GPU particles update shader
  58169. * @returns a string containng the defines string
  58170. */
  58171. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58172. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58173. };
  58174. /**
  58175. * Returns the string "SphereDirectedParticleEmitter"
  58176. * @returns a string containing the class name
  58177. */
  58178. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58179. return "SphereDirectedParticleEmitter";
  58180. };
  58181. /**
  58182. * Serializes the particle system to a JSON object.
  58183. * @returns the JSON object
  58184. */
  58185. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58186. var serializationObject = _super.prototype.serialize.call(this);
  58187. serializationObject.direction1 = this.direction1.asArray();
  58188. serializationObject.direction2 = this.direction2.asArray();
  58189. return serializationObject;
  58190. };
  58191. /**
  58192. * Parse properties from a JSON object
  58193. * @param serializationObject defines the JSON object
  58194. */
  58195. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58196. _super.prototype.parse.call(this, serializationObject);
  58197. this.direction1.copyFrom(serializationObject.direction1);
  58198. this.direction2.copyFrom(serializationObject.direction2);
  58199. };
  58200. return SphereDirectedParticleEmitter;
  58201. }(SphereParticleEmitter));
  58202. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58203. })(BABYLON || (BABYLON = {}));
  58204. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58205. var BABYLON;
  58206. (function (BABYLON) {
  58207. /**
  58208. * Particle emitter emitting particles from the inside of a hemisphere.
  58209. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58210. */
  58211. var HemisphericParticleEmitter = /** @class */ (function () {
  58212. /**
  58213. * Creates a new instance HemisphericParticleEmitter
  58214. * @param radius the radius of the emission hemisphere (1 by default)
  58215. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58216. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58217. */
  58218. function HemisphericParticleEmitter(
  58219. /**
  58220. * The radius of the emission hemisphere.
  58221. */
  58222. radius,
  58223. /**
  58224. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58225. */
  58226. radiusRange,
  58227. /**
  58228. * How much to randomize the particle direction [0-1].
  58229. */
  58230. directionRandomizer) {
  58231. if (radius === void 0) { radius = 1; }
  58232. if (radiusRange === void 0) { radiusRange = 1; }
  58233. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58234. this.radius = radius;
  58235. this.radiusRange = radiusRange;
  58236. this.directionRandomizer = directionRandomizer;
  58237. }
  58238. /**
  58239. * Called by the particle System when the direction is computed for the created particle.
  58240. * @param worldMatrix is the world matrix of the particle system
  58241. * @param directionToUpdate is the direction vector to update with the result
  58242. * @param particle is the particle we are computed the direction for
  58243. */
  58244. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58245. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58246. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58247. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58248. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58249. direction.x += randX;
  58250. direction.y += randY;
  58251. direction.z += randZ;
  58252. direction.normalize();
  58253. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58254. };
  58255. /**
  58256. * Called by the particle System when the position is computed for the created particle.
  58257. * @param worldMatrix is the world matrix of the particle system
  58258. * @param positionToUpdate is the position vector to update with the result
  58259. * @param particle is the particle we are computed the position for
  58260. */
  58261. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58262. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58263. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58264. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58265. var theta = Math.acos(2 * v - 1);
  58266. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58267. var randY = randRadius * Math.cos(theta);
  58268. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58270. };
  58271. /**
  58272. * Clones the current emitter and returns a copy of it
  58273. * @returns the new emitter
  58274. */
  58275. HemisphericParticleEmitter.prototype.clone = function () {
  58276. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58277. BABYLON.Tools.DeepCopy(this, newOne);
  58278. return newOne;
  58279. };
  58280. /**
  58281. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58282. * @param effect defines the update shader
  58283. */
  58284. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58285. effect.setFloat("radius", this.radius);
  58286. effect.setFloat("radiusRange", this.radiusRange);
  58287. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58288. };
  58289. /**
  58290. * Returns a string to use to update the GPU particles update shader
  58291. * @returns a string containng the defines string
  58292. */
  58293. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58294. return "#define HEMISPHERICEMITTER";
  58295. };
  58296. /**
  58297. * Returns the string "HemisphericParticleEmitter"
  58298. * @returns a string containing the class name
  58299. */
  58300. HemisphericParticleEmitter.prototype.getClassName = function () {
  58301. return "HemisphericParticleEmitter";
  58302. };
  58303. /**
  58304. * Serializes the particle system to a JSON object.
  58305. * @returns the JSON object
  58306. */
  58307. HemisphericParticleEmitter.prototype.serialize = function () {
  58308. var serializationObject = {};
  58309. serializationObject.type = this.getClassName();
  58310. serializationObject.radius = this.radius;
  58311. serializationObject.radiusRange = this.radiusRange;
  58312. serializationObject.directionRandomizer = this.directionRandomizer;
  58313. return serializationObject;
  58314. };
  58315. /**
  58316. * Parse properties from a JSON object
  58317. * @param serializationObject defines the JSON object
  58318. */
  58319. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58320. this.radius = serializationObject.radius;
  58321. this.radiusRange = serializationObject.radiusRange;
  58322. this.directionRandomizer = serializationObject.directionRandomizer;
  58323. };
  58324. return HemisphericParticleEmitter;
  58325. }());
  58326. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58327. })(BABYLON || (BABYLON = {}));
  58328. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58329. var BABYLON;
  58330. (function (BABYLON) {
  58331. /**
  58332. * Particle emitter emitting particles from a point.
  58333. * It emits the particles randomly between 2 given directions.
  58334. */
  58335. var PointParticleEmitter = /** @class */ (function () {
  58336. /**
  58337. * Creates a new instance PointParticleEmitter
  58338. */
  58339. function PointParticleEmitter() {
  58340. /**
  58341. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58342. */
  58343. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58344. /**
  58345. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58346. */
  58347. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58348. }
  58349. /**
  58350. * Called by the particle System when the direction is computed for the created particle.
  58351. * @param worldMatrix is the world matrix of the particle system
  58352. * @param directionToUpdate is the direction vector to update with the result
  58353. * @param particle is the particle we are computed the direction for
  58354. */
  58355. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58356. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58357. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58358. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58359. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58360. };
  58361. /**
  58362. * Called by the particle System when the position is computed for the created particle.
  58363. * @param worldMatrix is the world matrix of the particle system
  58364. * @param positionToUpdate is the position vector to update with the result
  58365. * @param particle is the particle we are computed the position for
  58366. */
  58367. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58368. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58369. };
  58370. /**
  58371. * Clones the current emitter and returns a copy of it
  58372. * @returns the new emitter
  58373. */
  58374. PointParticleEmitter.prototype.clone = function () {
  58375. var newOne = new PointParticleEmitter();
  58376. BABYLON.Tools.DeepCopy(this, newOne);
  58377. return newOne;
  58378. };
  58379. /**
  58380. * Called by the GPUParticleSystem to setup the update shader
  58381. * @param effect defines the update shader
  58382. */
  58383. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58384. effect.setVector3("direction1", this.direction1);
  58385. effect.setVector3("direction2", this.direction2);
  58386. };
  58387. /**
  58388. * Returns a string to use to update the GPU particles update shader
  58389. * @returns a string containng the defines string
  58390. */
  58391. PointParticleEmitter.prototype.getEffectDefines = function () {
  58392. return "#define POINTEMITTER";
  58393. };
  58394. /**
  58395. * Returns the string "PointParticleEmitter"
  58396. * @returns a string containing the class name
  58397. */
  58398. PointParticleEmitter.prototype.getClassName = function () {
  58399. return "PointParticleEmitter";
  58400. };
  58401. /**
  58402. * Serializes the particle system to a JSON object.
  58403. * @returns the JSON object
  58404. */
  58405. PointParticleEmitter.prototype.serialize = function () {
  58406. var serializationObject = {};
  58407. serializationObject.type = this.getClassName();
  58408. serializationObject.direction1 = this.direction1.asArray();
  58409. serializationObject.direction2 = this.direction2.asArray();
  58410. return serializationObject;
  58411. };
  58412. /**
  58413. * Parse properties from a JSON object
  58414. * @param serializationObject defines the JSON object
  58415. */
  58416. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58417. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58418. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58419. };
  58420. return PointParticleEmitter;
  58421. }());
  58422. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58423. })(BABYLON || (BABYLON = {}));
  58424. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58425. var BABYLON;
  58426. (function (BABYLON) {
  58427. // Adds the parsers to the scene parsers.
  58428. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58429. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58430. if (!individualParser) {
  58431. return;
  58432. }
  58433. // Particles Systems
  58434. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58435. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58436. var parsedParticleSystem = parsedData.particleSystems[index];
  58437. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58438. }
  58439. }
  58440. });
  58441. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58442. if (parsedParticleSystem.activeParticleCount) {
  58443. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58444. return ps;
  58445. }
  58446. else {
  58447. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58448. return ps;
  58449. }
  58450. });
  58451. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58452. if (uniformsNames === void 0) { uniformsNames = []; }
  58453. if (samplers === void 0) { samplers = []; }
  58454. if (defines === void 0) { defines = ""; }
  58455. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58456. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58457. if (defines.indexOf(" BILLBOARD") === -1) {
  58458. defines += "\n#define BILLBOARD\n";
  58459. }
  58460. if (samplers.indexOf("diffuseSampler") === -1) {
  58461. samplers.push("diffuseSampler");
  58462. }
  58463. return this.createEffect({
  58464. vertex: "particles",
  58465. fragmentElement: fragmentName
  58466. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58467. };
  58468. })(BABYLON || (BABYLON = {}));
  58469. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58470. var BABYLON;
  58471. (function (BABYLON) {
  58472. var ShaderMaterial = /** @class */ (function (_super) {
  58473. __extends(ShaderMaterial, _super);
  58474. function ShaderMaterial(name, scene, shaderPath, options) {
  58475. var _this = _super.call(this, name, scene) || this;
  58476. _this._textures = {};
  58477. _this._textureArrays = {};
  58478. _this._floats = {};
  58479. _this._ints = {};
  58480. _this._floatsArrays = {};
  58481. _this._colors3 = {};
  58482. _this._colors3Arrays = {};
  58483. _this._colors4 = {};
  58484. _this._vectors2 = {};
  58485. _this._vectors3 = {};
  58486. _this._vectors4 = {};
  58487. _this._matrices = {};
  58488. _this._matrices3x3 = {};
  58489. _this._matrices2x2 = {};
  58490. _this._vectors2Arrays = {};
  58491. _this._vectors3Arrays = {};
  58492. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58493. _this._shaderPath = shaderPath;
  58494. options.needAlphaBlending = options.needAlphaBlending || false;
  58495. options.needAlphaTesting = options.needAlphaTesting || false;
  58496. options.attributes = options.attributes || ["position", "normal", "uv"];
  58497. options.uniforms = options.uniforms || ["worldViewProjection"];
  58498. options.uniformBuffers = options.uniformBuffers || [];
  58499. options.samplers = options.samplers || [];
  58500. options.defines = options.defines || [];
  58501. _this._options = options;
  58502. return _this;
  58503. }
  58504. ShaderMaterial.prototype.getClassName = function () {
  58505. return "ShaderMaterial";
  58506. };
  58507. ShaderMaterial.prototype.needAlphaBlending = function () {
  58508. return this._options.needAlphaBlending;
  58509. };
  58510. ShaderMaterial.prototype.needAlphaTesting = function () {
  58511. return this._options.needAlphaTesting;
  58512. };
  58513. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58514. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58515. this._options.uniforms.push(uniformName);
  58516. }
  58517. };
  58518. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58519. if (this._options.samplers.indexOf(name) === -1) {
  58520. this._options.samplers.push(name);
  58521. }
  58522. this._textures[name] = texture;
  58523. return this;
  58524. };
  58525. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58526. if (this._options.samplers.indexOf(name) === -1) {
  58527. this._options.samplers.push(name);
  58528. }
  58529. this._checkUniform(name);
  58530. this._textureArrays[name] = textures;
  58531. return this;
  58532. };
  58533. ShaderMaterial.prototype.setFloat = function (name, value) {
  58534. this._checkUniform(name);
  58535. this._floats[name] = value;
  58536. return this;
  58537. };
  58538. ShaderMaterial.prototype.setInt = function (name, value) {
  58539. this._checkUniform(name);
  58540. this._ints[name] = value;
  58541. return this;
  58542. };
  58543. ShaderMaterial.prototype.setFloats = function (name, value) {
  58544. this._checkUniform(name);
  58545. this._floatsArrays[name] = value;
  58546. return this;
  58547. };
  58548. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58549. this._checkUniform(name);
  58550. this._colors3[name] = value;
  58551. return this;
  58552. };
  58553. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58554. this._checkUniform(name);
  58555. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58556. color.toArray(arr, arr.length);
  58557. return arr;
  58558. }, []);
  58559. return this;
  58560. };
  58561. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58562. this._checkUniform(name);
  58563. this._colors4[name] = value;
  58564. return this;
  58565. };
  58566. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58567. this._checkUniform(name);
  58568. this._vectors2[name] = value;
  58569. return this;
  58570. };
  58571. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58572. this._checkUniform(name);
  58573. this._vectors3[name] = value;
  58574. return this;
  58575. };
  58576. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58577. this._checkUniform(name);
  58578. this._vectors4[name] = value;
  58579. return this;
  58580. };
  58581. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58582. this._checkUniform(name);
  58583. this._matrices[name] = value;
  58584. return this;
  58585. };
  58586. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58587. this._checkUniform(name);
  58588. this._matrices3x3[name] = value;
  58589. return this;
  58590. };
  58591. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58592. this._checkUniform(name);
  58593. this._matrices2x2[name] = value;
  58594. return this;
  58595. };
  58596. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58597. this._checkUniform(name);
  58598. this._vectors2Arrays[name] = value;
  58599. return this;
  58600. };
  58601. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58602. this._checkUniform(name);
  58603. this._vectors3Arrays[name] = value;
  58604. return this;
  58605. };
  58606. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58607. if (!mesh) {
  58608. return true;
  58609. }
  58610. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58611. return false;
  58612. }
  58613. return false;
  58614. };
  58615. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58616. var scene = this.getScene();
  58617. var engine = scene.getEngine();
  58618. if (!this.checkReadyOnEveryCall) {
  58619. if (this._renderId === scene.getRenderId()) {
  58620. if (this._checkCache(scene, mesh, useInstances)) {
  58621. return true;
  58622. }
  58623. }
  58624. }
  58625. // Instances
  58626. var defines = [];
  58627. var attribs = [];
  58628. var fallbacks = new BABYLON.EffectFallbacks();
  58629. if (useInstances) {
  58630. defines.push("#define INSTANCES");
  58631. }
  58632. for (var index = 0; index < this._options.defines.length; index++) {
  58633. defines.push(this._options.defines[index]);
  58634. }
  58635. for (var index = 0; index < this._options.attributes.length; index++) {
  58636. attribs.push(this._options.attributes[index]);
  58637. }
  58638. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58639. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58640. defines.push("#define VERTEXCOLOR");
  58641. }
  58642. // Bones
  58643. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58646. if (mesh.numBoneInfluencers > 4) {
  58647. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58648. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58649. }
  58650. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58651. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58652. fallbacks.addCPUSkinningFallback(0, mesh);
  58653. if (this._options.uniforms.indexOf("mBones") === -1) {
  58654. this._options.uniforms.push("mBones");
  58655. }
  58656. }
  58657. else {
  58658. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58659. }
  58660. // Textures
  58661. for (var name in this._textures) {
  58662. if (!this._textures[name].isReady()) {
  58663. return false;
  58664. }
  58665. }
  58666. // Alpha test
  58667. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58668. defines.push("#define ALPHATEST");
  58669. }
  58670. var previousEffect = this._effect;
  58671. var join = defines.join("\n");
  58672. this._effect = engine.createEffect(this._shaderPath, {
  58673. attributes: attribs,
  58674. uniformsNames: this._options.uniforms,
  58675. uniformBuffersNames: this._options.uniformBuffers,
  58676. samplers: this._options.samplers,
  58677. defines: join,
  58678. fallbacks: fallbacks,
  58679. onCompiled: this.onCompiled,
  58680. onError: this.onError
  58681. }, engine);
  58682. if (!this._effect.isReady()) {
  58683. return false;
  58684. }
  58685. if (previousEffect !== this._effect) {
  58686. scene.resetCachedMaterial();
  58687. }
  58688. this._renderId = scene.getRenderId();
  58689. return true;
  58690. };
  58691. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58692. var scene = this.getScene();
  58693. if (!this._effect) {
  58694. return;
  58695. }
  58696. if (this._options.uniforms.indexOf("world") !== -1) {
  58697. this._effect.setMatrix("world", world);
  58698. }
  58699. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58700. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58701. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58702. }
  58703. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58704. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58705. }
  58706. };
  58707. ShaderMaterial.prototype.bind = function (world, mesh) {
  58708. // Std values
  58709. this.bindOnlyWorldMatrix(world);
  58710. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58711. if (this._options.uniforms.indexOf("view") !== -1) {
  58712. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58713. }
  58714. if (this._options.uniforms.indexOf("projection") !== -1) {
  58715. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58716. }
  58717. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58718. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58719. }
  58720. // Bones
  58721. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58722. var name;
  58723. // Texture
  58724. for (name in this._textures) {
  58725. this._effect.setTexture(name, this._textures[name]);
  58726. }
  58727. // Texture arrays
  58728. for (name in this._textureArrays) {
  58729. this._effect.setTextureArray(name, this._textureArrays[name]);
  58730. }
  58731. // Int
  58732. for (name in this._ints) {
  58733. this._effect.setInt(name, this._ints[name]);
  58734. }
  58735. // Float
  58736. for (name in this._floats) {
  58737. this._effect.setFloat(name, this._floats[name]);
  58738. }
  58739. // Floats
  58740. for (name in this._floatsArrays) {
  58741. this._effect.setArray(name, this._floatsArrays[name]);
  58742. }
  58743. // Color3
  58744. for (name in this._colors3) {
  58745. this._effect.setColor3(name, this._colors3[name]);
  58746. }
  58747. for (name in this._colors3Arrays) {
  58748. this._effect.setArray3(name, this._colors3Arrays[name]);
  58749. }
  58750. // Color4
  58751. for (name in this._colors4) {
  58752. var color = this._colors4[name];
  58753. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58754. }
  58755. // Vector2
  58756. for (name in this._vectors2) {
  58757. this._effect.setVector2(name, this._vectors2[name]);
  58758. }
  58759. // Vector3
  58760. for (name in this._vectors3) {
  58761. this._effect.setVector3(name, this._vectors3[name]);
  58762. }
  58763. // Vector4
  58764. for (name in this._vectors4) {
  58765. this._effect.setVector4(name, this._vectors4[name]);
  58766. }
  58767. // Matrix
  58768. for (name in this._matrices) {
  58769. this._effect.setMatrix(name, this._matrices[name]);
  58770. }
  58771. // Matrix 3x3
  58772. for (name in this._matrices3x3) {
  58773. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58774. }
  58775. // Matrix 2x2
  58776. for (name in this._matrices2x2) {
  58777. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58778. }
  58779. // Vector2Array
  58780. for (name in this._vectors2Arrays) {
  58781. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58782. }
  58783. // Vector3Array
  58784. for (name in this._vectors3Arrays) {
  58785. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58786. }
  58787. }
  58788. this._afterBind(mesh);
  58789. };
  58790. ShaderMaterial.prototype.getActiveTextures = function () {
  58791. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58792. for (var name in this._textures) {
  58793. activeTextures.push(this._textures[name]);
  58794. }
  58795. for (var name in this._textureArrays) {
  58796. var array = this._textureArrays[name];
  58797. for (var index = 0; index < array.length; index++) {
  58798. activeTextures.push(array[index]);
  58799. }
  58800. }
  58801. return activeTextures;
  58802. };
  58803. ShaderMaterial.prototype.hasTexture = function (texture) {
  58804. if (_super.prototype.hasTexture.call(this, texture)) {
  58805. return true;
  58806. }
  58807. for (var name in this._textures) {
  58808. if (this._textures[name] === texture) {
  58809. return true;
  58810. }
  58811. }
  58812. for (var name in this._textureArrays) {
  58813. var array = this._textureArrays[name];
  58814. for (var index = 0; index < array.length; index++) {
  58815. if (array[index] === texture) {
  58816. return true;
  58817. }
  58818. }
  58819. }
  58820. return false;
  58821. };
  58822. ShaderMaterial.prototype.clone = function (name) {
  58823. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58824. return newShaderMaterial;
  58825. };
  58826. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58827. if (forceDisposeTextures) {
  58828. var name;
  58829. for (name in this._textures) {
  58830. this._textures[name].dispose();
  58831. }
  58832. for (name in this._textureArrays) {
  58833. var array = this._textureArrays[name];
  58834. for (var index = 0; index < array.length; index++) {
  58835. array[index].dispose();
  58836. }
  58837. }
  58838. }
  58839. this._textures = {};
  58840. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58841. };
  58842. ShaderMaterial.prototype.serialize = function () {
  58843. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58844. serializationObject.customType = "BABYLON.ShaderMaterial";
  58845. serializationObject.options = this._options;
  58846. serializationObject.shaderPath = this._shaderPath;
  58847. var name;
  58848. // Texture
  58849. serializationObject.textures = {};
  58850. for (name in this._textures) {
  58851. serializationObject.textures[name] = this._textures[name].serialize();
  58852. }
  58853. // Texture arrays
  58854. serializationObject.textureArrays = {};
  58855. for (name in this._textureArrays) {
  58856. serializationObject.textureArrays[name] = [];
  58857. var array = this._textureArrays[name];
  58858. for (var index = 0; index < array.length; index++) {
  58859. serializationObject.textureArrays[name].push(array[index].serialize());
  58860. }
  58861. }
  58862. // Float
  58863. serializationObject.floats = {};
  58864. for (name in this._floats) {
  58865. serializationObject.floats[name] = this._floats[name];
  58866. }
  58867. // Float s
  58868. serializationObject.FloatArrays = {};
  58869. for (name in this._floatsArrays) {
  58870. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58871. }
  58872. // Color3
  58873. serializationObject.colors3 = {};
  58874. for (name in this._colors3) {
  58875. serializationObject.colors3[name] = this._colors3[name].asArray();
  58876. }
  58877. // Color3 array
  58878. serializationObject.colors3Arrays = {};
  58879. for (name in this._colors3Arrays) {
  58880. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58881. }
  58882. // Color4
  58883. serializationObject.colors4 = {};
  58884. for (name in this._colors4) {
  58885. serializationObject.colors4[name] = this._colors4[name].asArray();
  58886. }
  58887. // Vector2
  58888. serializationObject.vectors2 = {};
  58889. for (name in this._vectors2) {
  58890. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58891. }
  58892. // Vector3
  58893. serializationObject.vectors3 = {};
  58894. for (name in this._vectors3) {
  58895. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58896. }
  58897. // Vector4
  58898. serializationObject.vectors4 = {};
  58899. for (name in this._vectors4) {
  58900. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58901. }
  58902. // Matrix
  58903. serializationObject.matrices = {};
  58904. for (name in this._matrices) {
  58905. serializationObject.matrices[name] = this._matrices[name].asArray();
  58906. }
  58907. // Matrix 3x3
  58908. serializationObject.matrices3x3 = {};
  58909. for (name in this._matrices3x3) {
  58910. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58911. }
  58912. // Matrix 2x2
  58913. serializationObject.matrices2x2 = {};
  58914. for (name in this._matrices2x2) {
  58915. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58916. }
  58917. // Vector2Array
  58918. serializationObject.vectors2Arrays = {};
  58919. for (name in this._vectors2Arrays) {
  58920. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58921. }
  58922. // Vector3Array
  58923. serializationObject.vectors3Arrays = {};
  58924. for (name in this._vectors3Arrays) {
  58925. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58926. }
  58927. return serializationObject;
  58928. };
  58929. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58930. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58931. var name;
  58932. // Texture
  58933. for (name in source.textures) {
  58934. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58935. }
  58936. // Texture arrays
  58937. for (name in source.textureArrays) {
  58938. var array = source.textureArrays[name];
  58939. var textureArray = new Array();
  58940. for (var index = 0; index < array.length; index++) {
  58941. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58942. }
  58943. material.setTextureArray(name, textureArray);
  58944. }
  58945. // Float
  58946. for (name in source.floats) {
  58947. material.setFloat(name, source.floats[name]);
  58948. }
  58949. // Float s
  58950. for (name in source.floatsArrays) {
  58951. material.setFloats(name, source.floatsArrays[name]);
  58952. }
  58953. // Color3
  58954. for (name in source.colors3) {
  58955. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58956. }
  58957. // Color3 arrays
  58958. for (name in source.colors3Arrays) {
  58959. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58960. if (i % 3 === 0) {
  58961. arr.push([num]);
  58962. }
  58963. else {
  58964. arr[arr.length - 1].push(num);
  58965. }
  58966. return arr;
  58967. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58968. material.setColor3Array(name, colors);
  58969. }
  58970. // Color4
  58971. for (name in source.colors4) {
  58972. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58973. }
  58974. // Vector2
  58975. for (name in source.vectors2) {
  58976. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58977. }
  58978. // Vector3
  58979. for (name in source.vectors3) {
  58980. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58981. }
  58982. // Vector4
  58983. for (name in source.vectors4) {
  58984. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58985. }
  58986. // Matrix
  58987. for (name in source.matrices) {
  58988. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58989. }
  58990. // Matrix 3x3
  58991. for (name in source.matrices3x3) {
  58992. material.setMatrix3x3(name, source.matrices3x3[name]);
  58993. }
  58994. // Matrix 2x2
  58995. for (name in source.matrices2x2) {
  58996. material.setMatrix2x2(name, source.matrices2x2[name]);
  58997. }
  58998. // Vector2Array
  58999. for (name in source.vectors2Arrays) {
  59000. material.setArray2(name, source.vectors2Arrays[name]);
  59001. }
  59002. // Vector3Array
  59003. for (name in source.vectors3Arrays) {
  59004. material.setArray3(name, source.vectors3Arrays[name]);
  59005. }
  59006. return material;
  59007. };
  59008. return ShaderMaterial;
  59009. }(BABYLON.Material));
  59010. BABYLON.ShaderMaterial = ShaderMaterial;
  59011. })(BABYLON || (BABYLON = {}));
  59012. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59013. var BABYLON;
  59014. (function (BABYLON) {
  59015. var GroundMesh = /** @class */ (function (_super) {
  59016. __extends(GroundMesh, _super);
  59017. function GroundMesh(name, scene) {
  59018. var _this = _super.call(this, name, scene) || this;
  59019. _this.generateOctree = false;
  59020. return _this;
  59021. }
  59022. GroundMesh.prototype.getClassName = function () {
  59023. return "GroundMesh";
  59024. };
  59025. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59026. get: function () {
  59027. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59028. },
  59029. enumerable: true,
  59030. configurable: true
  59031. });
  59032. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59033. get: function () {
  59034. return this._subdivisionsX;
  59035. },
  59036. enumerable: true,
  59037. configurable: true
  59038. });
  59039. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59040. get: function () {
  59041. return this._subdivisionsY;
  59042. },
  59043. enumerable: true,
  59044. configurable: true
  59045. });
  59046. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59047. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59048. this._subdivisionsX = chunksCount;
  59049. this._subdivisionsY = chunksCount;
  59050. this.subdivide(chunksCount);
  59051. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59052. };
  59053. /**
  59054. * Returns a height (y) value in the Worl system :
  59055. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59056. * Returns the ground y position if (x, z) are outside the ground surface.
  59057. */
  59058. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59059. var world = this.getWorldMatrix();
  59060. var invMat = BABYLON.Tmp.Matrix[5];
  59061. world.invertToRef(invMat);
  59062. var tmpVect = BABYLON.Tmp.Vector3[8];
  59063. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59064. x = tmpVect.x;
  59065. z = tmpVect.z;
  59066. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59067. return this.position.y;
  59068. }
  59069. if (!this._heightQuads || this._heightQuads.length == 0) {
  59070. this._initHeightQuads();
  59071. this._computeHeightQuads();
  59072. }
  59073. var facet = this._getFacetAt(x, z);
  59074. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59075. // return y in the World system
  59076. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59077. return tmpVect.y;
  59078. };
  59079. /**
  59080. * Returns a normalized vector (Vector3) orthogonal to the ground
  59081. * at the ground coordinates (x, z) expressed in the World system.
  59082. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59083. */
  59084. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59085. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59086. this.getNormalAtCoordinatesToRef(x, z, normal);
  59087. return normal;
  59088. };
  59089. /**
  59090. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59091. * at the ground coordinates (x, z) expressed in the World system.
  59092. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59093. * Returns the GroundMesh.
  59094. */
  59095. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59096. var world = this.getWorldMatrix();
  59097. var tmpMat = BABYLON.Tmp.Matrix[5];
  59098. world.invertToRef(tmpMat);
  59099. var tmpVect = BABYLON.Tmp.Vector3[8];
  59100. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59101. x = tmpVect.x;
  59102. z = tmpVect.z;
  59103. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59104. return this;
  59105. }
  59106. if (!this._heightQuads || this._heightQuads.length == 0) {
  59107. this._initHeightQuads();
  59108. this._computeHeightQuads();
  59109. }
  59110. var facet = this._getFacetAt(x, z);
  59111. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59112. return this;
  59113. };
  59114. /**
  59115. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59116. * if the ground has been updated.
  59117. * This can be used in the render loop.
  59118. * Returns the GroundMesh.
  59119. */
  59120. GroundMesh.prototype.updateCoordinateHeights = function () {
  59121. if (!this._heightQuads || this._heightQuads.length == 0) {
  59122. this._initHeightQuads();
  59123. }
  59124. this._computeHeightQuads();
  59125. return this;
  59126. };
  59127. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59128. GroundMesh.prototype._getFacetAt = function (x, z) {
  59129. // retrieve col and row from x, z coordinates in the ground local system
  59130. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59131. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59132. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59133. var facet;
  59134. if (z < quad.slope.x * x + quad.slope.y) {
  59135. facet = quad.facet1;
  59136. }
  59137. else {
  59138. facet = quad.facet2;
  59139. }
  59140. return facet;
  59141. };
  59142. // Creates and populates the heightMap array with "facet" elements :
  59143. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59144. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59145. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59146. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59147. // Returns the GroundMesh.
  59148. GroundMesh.prototype._initHeightQuads = function () {
  59149. var subdivisionsX = this._subdivisionsX;
  59150. var subdivisionsY = this._subdivisionsY;
  59151. this._heightQuads = new Array();
  59152. for (var row = 0; row < subdivisionsY; row++) {
  59153. for (var col = 0; col < subdivisionsX; col++) {
  59154. 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) };
  59155. this._heightQuads[row * subdivisionsX + col] = quad;
  59156. }
  59157. }
  59158. return this;
  59159. };
  59160. // Compute each quad element values and update the the heightMap array :
  59161. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59162. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59163. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59164. // Returns the GroundMesh.
  59165. GroundMesh.prototype._computeHeightQuads = function () {
  59166. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59167. if (!positions) {
  59168. return this;
  59169. }
  59170. var v1 = BABYLON.Tmp.Vector3[3];
  59171. var v2 = BABYLON.Tmp.Vector3[2];
  59172. var v3 = BABYLON.Tmp.Vector3[1];
  59173. var v4 = BABYLON.Tmp.Vector3[0];
  59174. var v1v2 = BABYLON.Tmp.Vector3[4];
  59175. var v1v3 = BABYLON.Tmp.Vector3[5];
  59176. var v1v4 = BABYLON.Tmp.Vector3[6];
  59177. var norm1 = BABYLON.Tmp.Vector3[7];
  59178. var norm2 = BABYLON.Tmp.Vector3[8];
  59179. var i = 0;
  59180. var j = 0;
  59181. var k = 0;
  59182. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59183. var h = 0;
  59184. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59185. var d2 = 0;
  59186. var subdivisionsX = this._subdivisionsX;
  59187. var subdivisionsY = this._subdivisionsY;
  59188. for (var row = 0; row < subdivisionsY; row++) {
  59189. for (var col = 0; col < subdivisionsX; col++) {
  59190. i = col * 3;
  59191. j = row * (subdivisionsX + 1) * 3;
  59192. k = (row + 1) * (subdivisionsX + 1) * 3;
  59193. v1.x = positions[j + i];
  59194. v1.y = positions[j + i + 1];
  59195. v1.z = positions[j + i + 2];
  59196. v2.x = positions[j + i + 3];
  59197. v2.y = positions[j + i + 4];
  59198. v2.z = positions[j + i + 5];
  59199. v3.x = positions[k + i];
  59200. v3.y = positions[k + i + 1];
  59201. v3.z = positions[k + i + 2];
  59202. v4.x = positions[k + i + 3];
  59203. v4.y = positions[k + i + 4];
  59204. v4.z = positions[k + i + 5];
  59205. // 2D slope V1V4
  59206. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59207. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59208. // facet equations :
  59209. // we compute each facet normal vector
  59210. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59211. // we compute the value d by applying the equation to v1 which belongs to the plane
  59212. // then we store the facet equation in a Vector4
  59213. v2.subtractToRef(v1, v1v2);
  59214. v3.subtractToRef(v1, v1v3);
  59215. v4.subtractToRef(v1, v1v4);
  59216. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59217. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59218. norm1.normalize();
  59219. norm2.normalize();
  59220. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59221. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59222. var quad = this._heightQuads[row * subdivisionsX + col];
  59223. quad.slope.copyFromFloats(cd, h);
  59224. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59225. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59226. }
  59227. }
  59228. return this;
  59229. };
  59230. GroundMesh.prototype.serialize = function (serializationObject) {
  59231. _super.prototype.serialize.call(this, serializationObject);
  59232. serializationObject.subdivisionsX = this._subdivisionsX;
  59233. serializationObject.subdivisionsY = this._subdivisionsY;
  59234. serializationObject.minX = this._minX;
  59235. serializationObject.maxX = this._maxX;
  59236. serializationObject.minZ = this._minZ;
  59237. serializationObject.maxZ = this._maxZ;
  59238. serializationObject.width = this._width;
  59239. serializationObject.height = this._height;
  59240. };
  59241. GroundMesh.Parse = function (parsedMesh, scene) {
  59242. var result = new GroundMesh(parsedMesh.name, scene);
  59243. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59244. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59245. result._minX = parsedMesh.minX;
  59246. result._maxX = parsedMesh.maxX;
  59247. result._minZ = parsedMesh.minZ;
  59248. result._maxZ = parsedMesh.maxZ;
  59249. result._width = parsedMesh.width;
  59250. result._height = parsedMesh.height;
  59251. return result;
  59252. };
  59253. return GroundMesh;
  59254. }(BABYLON.Mesh));
  59255. BABYLON.GroundMesh = GroundMesh;
  59256. })(BABYLON || (BABYLON = {}));
  59257. //# sourceMappingURL=babylon.groundMesh.js.map
  59258. var BABYLON;
  59259. (function (BABYLON) {
  59260. /**
  59261. * Creates an instance based on a source mesh.
  59262. */
  59263. var InstancedMesh = /** @class */ (function (_super) {
  59264. __extends(InstancedMesh, _super);
  59265. function InstancedMesh(name, source) {
  59266. var _this = _super.call(this, name, source.getScene()) || this;
  59267. source.instances.push(_this);
  59268. _this._sourceMesh = source;
  59269. _this.position.copyFrom(source.position);
  59270. _this.rotation.copyFrom(source.rotation);
  59271. _this.scaling.copyFrom(source.scaling);
  59272. if (source.rotationQuaternion) {
  59273. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59274. }
  59275. _this.infiniteDistance = source.infiniteDistance;
  59276. _this.setPivotMatrix(source.getPivotMatrix());
  59277. _this.refreshBoundingInfo();
  59278. _this._syncSubMeshes();
  59279. return _this;
  59280. }
  59281. /**
  59282. * Returns the string "InstancedMesh".
  59283. */
  59284. InstancedMesh.prototype.getClassName = function () {
  59285. return "InstancedMesh";
  59286. };
  59287. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59288. // Methods
  59289. get: function () {
  59290. return this._sourceMesh.receiveShadows;
  59291. },
  59292. enumerable: true,
  59293. configurable: true
  59294. });
  59295. Object.defineProperty(InstancedMesh.prototype, "material", {
  59296. get: function () {
  59297. return this._sourceMesh.material;
  59298. },
  59299. enumerable: true,
  59300. configurable: true
  59301. });
  59302. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59303. get: function () {
  59304. return this._sourceMesh.visibility;
  59305. },
  59306. enumerable: true,
  59307. configurable: true
  59308. });
  59309. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59310. get: function () {
  59311. return this._sourceMesh.skeleton;
  59312. },
  59313. enumerable: true,
  59314. configurable: true
  59315. });
  59316. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59317. get: function () {
  59318. return this._sourceMesh.renderingGroupId;
  59319. },
  59320. set: function (value) {
  59321. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59322. return;
  59323. }
  59324. //no-op with warning
  59325. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59326. },
  59327. enumerable: true,
  59328. configurable: true
  59329. });
  59330. /**
  59331. * Returns the total number of vertices (integer).
  59332. */
  59333. InstancedMesh.prototype.getTotalVertices = function () {
  59334. return this._sourceMesh.getTotalVertices();
  59335. };
  59336. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59337. get: function () {
  59338. return this._sourceMesh;
  59339. },
  59340. enumerable: true,
  59341. configurable: true
  59342. });
  59343. /**
  59344. * Is this node ready to be used/rendered
  59345. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59346. * @return {boolean} is it ready
  59347. */
  59348. InstancedMesh.prototype.isReady = function (completeCheck) {
  59349. if (completeCheck === void 0) { completeCheck = false; }
  59350. return this._sourceMesh.isReady(completeCheck, true);
  59351. };
  59352. /**
  59353. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59354. */
  59355. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59356. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59357. };
  59358. /**
  59359. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59360. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59361. * The `data` are either a numeric array either a Float32Array.
  59362. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59363. * 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).
  59364. * Note that a new underlying VertexBuffer object is created each call.
  59365. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59366. *
  59367. * Possible `kind` values :
  59368. * - BABYLON.VertexBuffer.PositionKind
  59369. * - BABYLON.VertexBuffer.UVKind
  59370. * - BABYLON.VertexBuffer.UV2Kind
  59371. * - BABYLON.VertexBuffer.UV3Kind
  59372. * - BABYLON.VertexBuffer.UV4Kind
  59373. * - BABYLON.VertexBuffer.UV5Kind
  59374. * - BABYLON.VertexBuffer.UV6Kind
  59375. * - BABYLON.VertexBuffer.ColorKind
  59376. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59377. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59378. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59379. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59380. *
  59381. * Returns the Mesh.
  59382. */
  59383. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59384. if (this.sourceMesh) {
  59385. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59386. }
  59387. return this.sourceMesh;
  59388. };
  59389. /**
  59390. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59391. * If the mesh has no geometry, it is simply returned as it is.
  59392. * The `data` are either a numeric array either a Float32Array.
  59393. * No new underlying VertexBuffer object is created.
  59394. * 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.
  59395. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59396. *
  59397. * Possible `kind` values :
  59398. * - BABYLON.VertexBuffer.PositionKind
  59399. * - BABYLON.VertexBuffer.UVKind
  59400. * - BABYLON.VertexBuffer.UV2Kind
  59401. * - BABYLON.VertexBuffer.UV3Kind
  59402. * - BABYLON.VertexBuffer.UV4Kind
  59403. * - BABYLON.VertexBuffer.UV5Kind
  59404. * - BABYLON.VertexBuffer.UV6Kind
  59405. * - BABYLON.VertexBuffer.ColorKind
  59406. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59407. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59408. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59409. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59410. *
  59411. * Returns the Mesh.
  59412. */
  59413. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59414. if (this.sourceMesh) {
  59415. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59416. }
  59417. return this.sourceMesh;
  59418. };
  59419. /**
  59420. * Sets the mesh indices.
  59421. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59422. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59423. * This method creates a new index buffer each call.
  59424. * Returns the Mesh.
  59425. */
  59426. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59427. if (totalVertices === void 0) { totalVertices = null; }
  59428. if (this.sourceMesh) {
  59429. this.sourceMesh.setIndices(indices, totalVertices);
  59430. }
  59431. return this.sourceMesh;
  59432. };
  59433. /**
  59434. * Boolean : True if the mesh owns the requested kind of data.
  59435. */
  59436. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59437. return this._sourceMesh.isVerticesDataPresent(kind);
  59438. };
  59439. /**
  59440. * Returns an array of indices (IndicesArray).
  59441. */
  59442. InstancedMesh.prototype.getIndices = function () {
  59443. return this._sourceMesh.getIndices();
  59444. };
  59445. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59446. get: function () {
  59447. return this._sourceMesh._positions;
  59448. },
  59449. enumerable: true,
  59450. configurable: true
  59451. });
  59452. /**
  59453. * Sets a new updated BoundingInfo to the mesh.
  59454. * Returns the mesh.
  59455. */
  59456. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59457. var meshBB = this._sourceMesh.getBoundingInfo();
  59458. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59459. this._updateBoundingInfo();
  59460. return this;
  59461. };
  59462. /** @hidden */
  59463. InstancedMesh.prototype._preActivate = function () {
  59464. if (this._currentLOD) {
  59465. this._currentLOD._preActivate();
  59466. }
  59467. return this;
  59468. };
  59469. /** @hidden */
  59470. InstancedMesh.prototype._activate = function (renderId) {
  59471. if (this._currentLOD) {
  59472. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59473. }
  59474. return this;
  59475. };
  59476. /**
  59477. * Returns the current associated LOD AbstractMesh.
  59478. */
  59479. InstancedMesh.prototype.getLOD = function (camera) {
  59480. if (!camera) {
  59481. return this;
  59482. }
  59483. var boundingInfo = this.getBoundingInfo();
  59484. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59485. if (this._currentLOD === this.sourceMesh) {
  59486. return this;
  59487. }
  59488. return this._currentLOD;
  59489. };
  59490. /** @hidden */
  59491. InstancedMesh.prototype._syncSubMeshes = function () {
  59492. this.releaseSubMeshes();
  59493. if (this._sourceMesh.subMeshes) {
  59494. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59495. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59496. }
  59497. }
  59498. return this;
  59499. };
  59500. /** @hidden */
  59501. InstancedMesh.prototype._generatePointsArray = function () {
  59502. return this._sourceMesh._generatePointsArray();
  59503. };
  59504. /**
  59505. * Creates a new InstancedMesh from the current mesh.
  59506. * - name (string) : the cloned mesh name
  59507. * - newParent (optional Node) : the optional Node to parent the clone to.
  59508. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59509. *
  59510. * Returns the clone.
  59511. */
  59512. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59513. var result = this._sourceMesh.createInstance(name);
  59514. // Deep copy
  59515. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59516. // Bounding info
  59517. this.refreshBoundingInfo();
  59518. // Parent
  59519. if (newParent) {
  59520. result.parent = newParent;
  59521. }
  59522. if (!doNotCloneChildren) {
  59523. // Children
  59524. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59525. var mesh = this.getScene().meshes[index];
  59526. if (mesh.parent === this) {
  59527. mesh.clone(mesh.name, result);
  59528. }
  59529. }
  59530. }
  59531. result.computeWorldMatrix(true);
  59532. return result;
  59533. };
  59534. /**
  59535. * Disposes the InstancedMesh.
  59536. * Returns nothing.
  59537. */
  59538. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59539. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59540. // Remove from mesh
  59541. var index = this._sourceMesh.instances.indexOf(this);
  59542. this._sourceMesh.instances.splice(index, 1);
  59543. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59544. };
  59545. return InstancedMesh;
  59546. }(BABYLON.AbstractMesh));
  59547. BABYLON.InstancedMesh = InstancedMesh;
  59548. })(BABYLON || (BABYLON = {}));
  59549. //# sourceMappingURL=babylon.instancedMesh.js.map
  59550. var BABYLON;
  59551. (function (BABYLON) {
  59552. var LinesMesh = /** @class */ (function (_super) {
  59553. __extends(LinesMesh, _super);
  59554. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59555. if (scene === void 0) { scene = null; }
  59556. if (parent === void 0) { parent = null; }
  59557. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59558. _this.useVertexColor = useVertexColor;
  59559. _this.useVertexAlpha = useVertexAlpha;
  59560. _this.color = new BABYLON.Color3(1, 1, 1);
  59561. _this.alpha = 1;
  59562. if (source) {
  59563. _this.color = source.color.clone();
  59564. _this.alpha = source.alpha;
  59565. _this.useVertexColor = source.useVertexColor;
  59566. _this.useVertexAlpha = source.useVertexAlpha;
  59567. }
  59568. _this._intersectionThreshold = 0.1;
  59569. var defines = [];
  59570. var options = {
  59571. attributes: [BABYLON.VertexBuffer.PositionKind],
  59572. uniforms: ["world", "viewProjection"],
  59573. needAlphaBlending: true,
  59574. defines: defines
  59575. };
  59576. if (useVertexAlpha === false) {
  59577. options.needAlphaBlending = false;
  59578. }
  59579. if (!useVertexColor) {
  59580. options.uniforms.push("color");
  59581. }
  59582. else {
  59583. options.defines.push("#define VERTEXCOLOR");
  59584. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59585. }
  59586. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59587. return _this;
  59588. }
  59589. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59590. /**
  59591. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59592. * This margin is expressed in world space coordinates, so its value may vary.
  59593. * Default value is 0.1
  59594. * @returns the intersection Threshold value.
  59595. */
  59596. get: function () {
  59597. return this._intersectionThreshold;
  59598. },
  59599. /**
  59600. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59601. * This margin is expressed in world space coordinates, so its value may vary.
  59602. * @param value the new threshold to apply
  59603. */
  59604. set: function (value) {
  59605. if (this._intersectionThreshold === value) {
  59606. return;
  59607. }
  59608. this._intersectionThreshold = value;
  59609. if (this.geometry) {
  59610. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59611. }
  59612. },
  59613. enumerable: true,
  59614. configurable: true
  59615. });
  59616. /**
  59617. * Returns the string "LineMesh"
  59618. */
  59619. LinesMesh.prototype.getClassName = function () {
  59620. return "LinesMesh";
  59621. };
  59622. Object.defineProperty(LinesMesh.prototype, "material", {
  59623. /**
  59624. * @hidden
  59625. */
  59626. get: function () {
  59627. return this._colorShader;
  59628. },
  59629. /**
  59630. * @hidden
  59631. */
  59632. set: function (value) {
  59633. // Do nothing
  59634. },
  59635. enumerable: true,
  59636. configurable: true
  59637. });
  59638. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59639. /**
  59640. * @hidden
  59641. */
  59642. get: function () {
  59643. return false;
  59644. },
  59645. enumerable: true,
  59646. configurable: true
  59647. });
  59648. LinesMesh.prototype.createInstance = function (name) {
  59649. throw new Error("LinesMeshes do not support createInstance.");
  59650. };
  59651. /** @hidden */
  59652. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59653. if (!this._geometry) {
  59654. return this;
  59655. }
  59656. // VBOs
  59657. this._geometry._bind(this._colorShader.getEffect());
  59658. // Color
  59659. if (!this.useVertexColor) {
  59660. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59661. }
  59662. return this;
  59663. };
  59664. /** @hidden */
  59665. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59666. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59667. return this;
  59668. }
  59669. var engine = this.getScene().getEngine();
  59670. // Draw order
  59671. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59672. return this;
  59673. };
  59674. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59675. this._colorShader.dispose();
  59676. _super.prototype.dispose.call(this, doNotRecurse);
  59677. };
  59678. /**
  59679. * Returns a new LineMesh object cloned from the current one.
  59680. */
  59681. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59682. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59683. };
  59684. /**
  59685. * Enables the edge rendering mode on the mesh.
  59686. * This mode makes the mesh edges visible
  59687. * @param epsilon defines the maximal distance between two angles to detect a face
  59688. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  59689. * @returns the currentAbstractMesh
  59690. * @see https://www.babylonjs-playground.com/#19O9TU#0
  59691. */
  59692. LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  59693. if (epsilon === void 0) { epsilon = 0.95; }
  59694. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59695. this.disableEdgesRendering();
  59696. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  59697. return this;
  59698. };
  59699. return LinesMesh;
  59700. }(BABYLON.Mesh));
  59701. BABYLON.LinesMesh = LinesMesh;
  59702. })(BABYLON || (BABYLON = {}));
  59703. //# sourceMappingURL=babylon.linesMesh.js.map
  59704. var BABYLON;
  59705. (function (BABYLON) {
  59706. /**
  59707. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59708. * The underlying implementation relies on an associative array to ensure the best performances.
  59709. * The value can be anything including 'null' but except 'undefined'
  59710. */
  59711. var StringDictionary = /** @class */ (function () {
  59712. function StringDictionary() {
  59713. this._count = 0;
  59714. this._data = {};
  59715. }
  59716. /**
  59717. * This will clear this dictionary and copy the content from the 'source' one.
  59718. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59719. * @param source the dictionary to take the content from and copy to this dictionary
  59720. */
  59721. StringDictionary.prototype.copyFrom = function (source) {
  59722. var _this = this;
  59723. this.clear();
  59724. source.forEach(function (t, v) { return _this.add(t, v); });
  59725. };
  59726. /**
  59727. * Get a value based from its key
  59728. * @param key the given key to get the matching value from
  59729. * @return the value if found, otherwise undefined is returned
  59730. */
  59731. StringDictionary.prototype.get = function (key) {
  59732. var val = this._data[key];
  59733. if (val !== undefined) {
  59734. return val;
  59735. }
  59736. return undefined;
  59737. };
  59738. /**
  59739. * Get a value from its key or add it if it doesn't exist.
  59740. * This method will ensure you that a given key/data will be present in the dictionary.
  59741. * @param key the given key to get the matching value from
  59742. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59743. * The factory will only be invoked if there's no data for the given key.
  59744. * @return the value corresponding to the key.
  59745. */
  59746. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59747. var val = this.get(key);
  59748. if (val !== undefined) {
  59749. return val;
  59750. }
  59751. val = factory(key);
  59752. if (val) {
  59753. this.add(key, val);
  59754. }
  59755. return val;
  59756. };
  59757. /**
  59758. * Get a value from its key if present in the dictionary otherwise add it
  59759. * @param key the key to get the value from
  59760. * @param val if there's no such key/value pair in the dictionary add it with this value
  59761. * @return the value corresponding to the key
  59762. */
  59763. StringDictionary.prototype.getOrAdd = function (key, val) {
  59764. var curVal = this.get(key);
  59765. if (curVal !== undefined) {
  59766. return curVal;
  59767. }
  59768. this.add(key, val);
  59769. return val;
  59770. };
  59771. /**
  59772. * Check if there's a given key in the dictionary
  59773. * @param key the key to check for
  59774. * @return true if the key is present, false otherwise
  59775. */
  59776. StringDictionary.prototype.contains = function (key) {
  59777. return this._data[key] !== undefined;
  59778. };
  59779. /**
  59780. * Add a new key and its corresponding value
  59781. * @param key the key to add
  59782. * @param value the value corresponding to the key
  59783. * @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
  59784. */
  59785. StringDictionary.prototype.add = function (key, value) {
  59786. if (this._data[key] !== undefined) {
  59787. return false;
  59788. }
  59789. this._data[key] = value;
  59790. ++this._count;
  59791. return true;
  59792. };
  59793. StringDictionary.prototype.set = function (key, value) {
  59794. if (this._data[key] === undefined) {
  59795. return false;
  59796. }
  59797. this._data[key] = value;
  59798. return true;
  59799. };
  59800. /**
  59801. * Get the element of the given key and remove it from the dictionary
  59802. * @param key
  59803. */
  59804. StringDictionary.prototype.getAndRemove = function (key) {
  59805. var val = this.get(key);
  59806. if (val !== undefined) {
  59807. delete this._data[key];
  59808. --this._count;
  59809. return val;
  59810. }
  59811. return null;
  59812. };
  59813. /**
  59814. * Remove a key/value from the dictionary.
  59815. * @param key the key to remove
  59816. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59817. */
  59818. StringDictionary.prototype.remove = function (key) {
  59819. if (this.contains(key)) {
  59820. delete this._data[key];
  59821. --this._count;
  59822. return true;
  59823. }
  59824. return false;
  59825. };
  59826. /**
  59827. * Clear the whole content of the dictionary
  59828. */
  59829. StringDictionary.prototype.clear = function () {
  59830. this._data = {};
  59831. this._count = 0;
  59832. };
  59833. Object.defineProperty(StringDictionary.prototype, "count", {
  59834. get: function () {
  59835. return this._count;
  59836. },
  59837. enumerable: true,
  59838. configurable: true
  59839. });
  59840. /**
  59841. * Execute a callback on each key/val of the dictionary.
  59842. * Note that you can remove any element in this dictionary in the callback implementation
  59843. * @param callback the callback to execute on a given key/value pair
  59844. */
  59845. StringDictionary.prototype.forEach = function (callback) {
  59846. for (var cur in this._data) {
  59847. var val = this._data[cur];
  59848. callback(cur, val);
  59849. }
  59850. };
  59851. /**
  59852. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59853. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59854. * Note that you can remove any element in this dictionary in the callback implementation
  59855. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59856. */
  59857. StringDictionary.prototype.first = function (callback) {
  59858. for (var cur in this._data) {
  59859. var val = this._data[cur];
  59860. var res = callback(cur, val);
  59861. if (res) {
  59862. return res;
  59863. }
  59864. }
  59865. return null;
  59866. };
  59867. return StringDictionary;
  59868. }());
  59869. BABYLON.StringDictionary = StringDictionary;
  59870. })(BABYLON || (BABYLON = {}));
  59871. //# sourceMappingURL=babylon.stringDictionary.js.map
  59872. var BABYLON;
  59873. (function (BABYLON) {
  59874. var Debug;
  59875. (function (Debug) {
  59876. /**
  59877. * Class used to render a debug view of a given skeleton
  59878. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59879. */
  59880. var SkeletonViewer = /** @class */ (function () {
  59881. /**
  59882. * Creates a new SkeletonViewer
  59883. * @param skeleton defines the skeleton to render
  59884. * @param mesh defines the mesh attached to the skeleton
  59885. * @param scene defines the hosting scene
  59886. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59887. * @param renderingGroupId defines the rendering group id to use with the viewer
  59888. */
  59889. function SkeletonViewer(
  59890. /** defines the skeleton to render */
  59891. skeleton,
  59892. /** defines the mesh attached to the skeleton */
  59893. mesh, scene,
  59894. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59895. autoUpdateBonesMatrices,
  59896. /** defines the rendering group id to use with the viewer */
  59897. renderingGroupId) {
  59898. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59899. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59900. this.skeleton = skeleton;
  59901. this.mesh = mesh;
  59902. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59903. this.renderingGroupId = renderingGroupId;
  59904. /** Gets or sets the color used to render the skeleton */
  59905. this.color = BABYLON.Color3.White();
  59906. this._debugLines = new Array();
  59907. this._isEnabled = false;
  59908. this._scene = scene;
  59909. this.update();
  59910. this._renderFunction = this.update.bind(this);
  59911. }
  59912. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59913. get: function () {
  59914. return this._isEnabled;
  59915. },
  59916. /** Gets or sets a boolean indicating if the viewer is enabled */
  59917. set: function (value) {
  59918. if (this._isEnabled === value) {
  59919. return;
  59920. }
  59921. this._isEnabled = value;
  59922. if (value) {
  59923. this._scene.registerBeforeRender(this._renderFunction);
  59924. }
  59925. else {
  59926. this._scene.unregisterBeforeRender(this._renderFunction);
  59927. }
  59928. },
  59929. enumerable: true,
  59930. configurable: true
  59931. });
  59932. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59933. if (x === void 0) { x = 0; }
  59934. if (y === void 0) { y = 0; }
  59935. if (z === void 0) { z = 0; }
  59936. var tmat = BABYLON.Tmp.Matrix[0];
  59937. var parentBone = bone.getParent();
  59938. tmat.copyFrom(bone.getLocalMatrix());
  59939. if (x !== 0 || y !== 0 || z !== 0) {
  59940. var tmat2 = BABYLON.Tmp.Matrix[1];
  59941. BABYLON.Matrix.IdentityToRef(tmat2);
  59942. tmat2.m[12] = x;
  59943. tmat2.m[13] = y;
  59944. tmat2.m[14] = z;
  59945. tmat2.multiplyToRef(tmat, tmat);
  59946. }
  59947. if (parentBone) {
  59948. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59949. }
  59950. tmat.multiplyToRef(meshMat, tmat);
  59951. position.x = tmat.m[12];
  59952. position.y = tmat.m[13];
  59953. position.z = tmat.m[14];
  59954. };
  59955. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59956. var len = bones.length;
  59957. var meshPos = this.mesh.position;
  59958. for (var i = 0; i < len; i++) {
  59959. var bone = bones[i];
  59960. var points = this._debugLines[i];
  59961. if (!points) {
  59962. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59963. this._debugLines[i] = points;
  59964. }
  59965. this._getBonePosition(points[0], bone, meshMat);
  59966. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59967. points[0].subtractInPlace(meshPos);
  59968. points[1].subtractInPlace(meshPos);
  59969. }
  59970. };
  59971. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59972. var len = bones.length;
  59973. var boneNum = 0;
  59974. var meshPos = this.mesh.position;
  59975. for (var i = len - 1; i >= 0; i--) {
  59976. var childBone = bones[i];
  59977. var parentBone = childBone.getParent();
  59978. if (!parentBone) {
  59979. continue;
  59980. }
  59981. var points = this._debugLines[boneNum];
  59982. if (!points) {
  59983. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59984. this._debugLines[boneNum] = points;
  59985. }
  59986. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59987. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59988. points[0].subtractInPlace(meshPos);
  59989. points[1].subtractInPlace(meshPos);
  59990. boneNum++;
  59991. }
  59992. };
  59993. /** Update the viewer to sync with current skeleton state */
  59994. SkeletonViewer.prototype.update = function () {
  59995. if (this.autoUpdateBonesMatrices) {
  59996. this.skeleton.computeAbsoluteTransforms();
  59997. }
  59998. if (this.skeleton.bones[0].length === undefined) {
  59999. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60000. }
  60001. else {
  60002. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60003. }
  60004. if (!this._debugMesh) {
  60005. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60006. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60007. }
  60008. else {
  60009. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60010. }
  60011. this._debugMesh.position.copyFrom(this.mesh.position);
  60012. this._debugMesh.color = this.color;
  60013. };
  60014. /** Release associated resources */
  60015. SkeletonViewer.prototype.dispose = function () {
  60016. if (this._debugMesh) {
  60017. this.isEnabled = false;
  60018. this._debugMesh.dispose();
  60019. this._debugMesh = null;
  60020. }
  60021. };
  60022. return SkeletonViewer;
  60023. }());
  60024. Debug.SkeletonViewer = SkeletonViewer;
  60025. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60026. })(BABYLON || (BABYLON = {}));
  60027. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60028. /**
  60029. * Module Debug contains the (visual) components to debug a scene correctly
  60030. */
  60031. var BABYLON;
  60032. (function (BABYLON) {
  60033. var Debug;
  60034. (function (Debug) {
  60035. /**
  60036. * The Axes viewer will show 3 axes in a specific point in space
  60037. */
  60038. var AxesViewer = /** @class */ (function () {
  60039. /**
  60040. * Creates a new AxesViewer
  60041. * @param scene defines the hosting scene
  60042. * @param scaleLines defines a number used to scale line length (1 by default)
  60043. */
  60044. function AxesViewer(scene, scaleLines) {
  60045. if (scaleLines === void 0) { scaleLines = 1; }
  60046. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60047. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60048. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60049. /**
  60050. * Gets or sets a number used to scale line length
  60051. */
  60052. this.scaleLines = 1;
  60053. this.scaleLines = scaleLines;
  60054. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60055. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60056. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60057. this._xmesh.renderingGroupId = 2;
  60058. this._ymesh.renderingGroupId = 2;
  60059. this._zmesh.renderingGroupId = 2;
  60060. this._xmesh.material.checkReadyOnlyOnce = true;
  60061. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60062. this._ymesh.material.checkReadyOnlyOnce = true;
  60063. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60064. this._zmesh.material.checkReadyOnlyOnce = true;
  60065. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60066. this.scene = scene;
  60067. }
  60068. /**
  60069. * Force the viewer to update
  60070. * @param position defines the position of the viewer
  60071. * @param xaxis defines the x axis of the viewer
  60072. * @param yaxis defines the y axis of the viewer
  60073. * @param zaxis defines the z axis of the viewer
  60074. */
  60075. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60076. var scaleLines = this.scaleLines;
  60077. if (this._xmesh) {
  60078. this._xmesh.position.copyFrom(position);
  60079. }
  60080. if (this._ymesh) {
  60081. this._ymesh.position.copyFrom(position);
  60082. }
  60083. if (this._zmesh) {
  60084. this._zmesh.position.copyFrom(position);
  60085. }
  60086. var point2 = this._xline[1];
  60087. point2.x = xaxis.x * scaleLines;
  60088. point2.y = xaxis.y * scaleLines;
  60089. point2.z = xaxis.z * scaleLines;
  60090. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60091. point2 = this._yline[1];
  60092. point2.x = yaxis.x * scaleLines;
  60093. point2.y = yaxis.y * scaleLines;
  60094. point2.z = yaxis.z * scaleLines;
  60095. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60096. point2 = this._zline[1];
  60097. point2.x = zaxis.x * scaleLines;
  60098. point2.y = zaxis.y * scaleLines;
  60099. point2.z = zaxis.z * scaleLines;
  60100. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60101. };
  60102. /** Releases resources */
  60103. AxesViewer.prototype.dispose = function () {
  60104. if (this._xmesh) {
  60105. this._xmesh.dispose();
  60106. }
  60107. if (this._ymesh) {
  60108. this._ymesh.dispose();
  60109. }
  60110. if (this._zmesh) {
  60111. this._zmesh.dispose();
  60112. }
  60113. this._xmesh = null;
  60114. this._ymesh = null;
  60115. this._zmesh = null;
  60116. this.scene = null;
  60117. };
  60118. return AxesViewer;
  60119. }());
  60120. Debug.AxesViewer = AxesViewer;
  60121. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60122. })(BABYLON || (BABYLON = {}));
  60123. //# sourceMappingURL=babylon.axesViewer.js.map
  60124. var BABYLON;
  60125. (function (BABYLON) {
  60126. var Debug;
  60127. (function (Debug) {
  60128. /**
  60129. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60130. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60131. */
  60132. var BoneAxesViewer = /** @class */ (function (_super) {
  60133. __extends(BoneAxesViewer, _super);
  60134. /**
  60135. * Creates a new BoneAxesViewer
  60136. * @param scene defines the hosting scene
  60137. * @param bone defines the target bone
  60138. * @param mesh defines the target mesh
  60139. * @param scaleLines defines a scaling factor for line length (1 by default)
  60140. */
  60141. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60142. if (scaleLines === void 0) { scaleLines = 1; }
  60143. var _this = _super.call(this, scene, scaleLines) || this;
  60144. /** Gets current position */
  60145. _this.pos = BABYLON.Vector3.Zero();
  60146. /** Gets direction of X axis */
  60147. _this.xaxis = BABYLON.Vector3.Zero();
  60148. /** Gets direction of Y axis */
  60149. _this.yaxis = BABYLON.Vector3.Zero();
  60150. /** Gets direction of Z axis */
  60151. _this.zaxis = BABYLON.Vector3.Zero();
  60152. _this.mesh = mesh;
  60153. _this.bone = bone;
  60154. return _this;
  60155. }
  60156. /**
  60157. * Force the viewer to update
  60158. */
  60159. BoneAxesViewer.prototype.update = function () {
  60160. if (!this.mesh || !this.bone) {
  60161. return;
  60162. }
  60163. var bone = this.bone;
  60164. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60165. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60166. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60167. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60168. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60169. };
  60170. /** Releases resources */
  60171. BoneAxesViewer.prototype.dispose = function () {
  60172. if (this.mesh) {
  60173. this.mesh = null;
  60174. this.bone = null;
  60175. _super.prototype.dispose.call(this);
  60176. }
  60177. };
  60178. return BoneAxesViewer;
  60179. }(Debug.AxesViewer));
  60180. Debug.BoneAxesViewer = BoneAxesViewer;
  60181. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60182. })(BABYLON || (BABYLON = {}));
  60183. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60184. var BABYLON;
  60185. (function (BABYLON) {
  60186. var RayHelper = /** @class */ (function () {
  60187. function RayHelper(ray) {
  60188. this.ray = ray;
  60189. }
  60190. RayHelper.CreateAndShow = function (ray, scene, color) {
  60191. var helper = new RayHelper(ray);
  60192. helper.show(scene, color);
  60193. return helper;
  60194. };
  60195. RayHelper.prototype.show = function (scene, color) {
  60196. if (!this._renderFunction && this.ray) {
  60197. var ray = this.ray;
  60198. this._renderFunction = this._render.bind(this);
  60199. this._scene = scene;
  60200. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60201. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60202. if (this._renderFunction) {
  60203. this._scene.registerBeforeRender(this._renderFunction);
  60204. }
  60205. }
  60206. if (color && this._renderLine) {
  60207. this._renderLine.color.copyFrom(color);
  60208. }
  60209. };
  60210. RayHelper.prototype.hide = function () {
  60211. if (this._renderFunction && this._scene) {
  60212. this._scene.unregisterBeforeRender(this._renderFunction);
  60213. this._scene = null;
  60214. this._renderFunction = null;
  60215. if (this._renderLine) {
  60216. this._renderLine.dispose();
  60217. this._renderLine = null;
  60218. }
  60219. this._renderPoints = [];
  60220. }
  60221. };
  60222. RayHelper.prototype._render = function () {
  60223. var ray = this.ray;
  60224. if (!ray) {
  60225. return;
  60226. }
  60227. var point = this._renderPoints[1];
  60228. var len = Math.min(ray.length, 1000000);
  60229. point.copyFrom(ray.direction);
  60230. point.scaleInPlace(len);
  60231. point.addInPlace(ray.origin);
  60232. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60233. };
  60234. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60235. this._attachedToMesh = mesh;
  60236. var ray = this.ray;
  60237. if (!ray) {
  60238. return;
  60239. }
  60240. if (!ray.direction) {
  60241. ray.direction = BABYLON.Vector3.Zero();
  60242. }
  60243. if (!ray.origin) {
  60244. ray.origin = BABYLON.Vector3.Zero();
  60245. }
  60246. if (length) {
  60247. ray.length = length;
  60248. }
  60249. if (!meshSpaceOrigin) {
  60250. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60251. }
  60252. if (!meshSpaceDirection) {
  60253. // -1 so that this will work with Mesh.lookAt
  60254. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60255. }
  60256. if (!this._meshSpaceDirection) {
  60257. this._meshSpaceDirection = meshSpaceDirection.clone();
  60258. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60259. }
  60260. else {
  60261. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60262. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60263. }
  60264. if (!this._updateToMeshFunction) {
  60265. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60266. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60267. }
  60268. this._updateToMesh();
  60269. };
  60270. RayHelper.prototype.detachFromMesh = function () {
  60271. if (this._attachedToMesh) {
  60272. if (this._updateToMeshFunction) {
  60273. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60274. }
  60275. this._attachedToMesh = null;
  60276. this._updateToMeshFunction = null;
  60277. }
  60278. };
  60279. RayHelper.prototype._updateToMesh = function () {
  60280. var ray = this.ray;
  60281. if (!this._attachedToMesh || !ray) {
  60282. return;
  60283. }
  60284. if (this._attachedToMesh._isDisposed) {
  60285. this.detachFromMesh();
  60286. return;
  60287. }
  60288. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60289. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60290. };
  60291. RayHelper.prototype.dispose = function () {
  60292. this.hide();
  60293. this.detachFromMesh();
  60294. this.ray = null;
  60295. };
  60296. return RayHelper;
  60297. }());
  60298. BABYLON.RayHelper = RayHelper;
  60299. })(BABYLON || (BABYLON = {}));
  60300. //# sourceMappingURL=babylon.rayHelper.js.map
  60301. var BABYLON;
  60302. (function (BABYLON) {
  60303. // load the inspector using require, if not present in the global namespace.
  60304. var DebugLayer = /** @class */ (function () {
  60305. function DebugLayer(scene) {
  60306. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60307. this.onPropertyChangedObservable = new BABYLON.Observable();
  60308. this._scene = scene;
  60309. }
  60310. /** Creates the inspector window. */
  60311. DebugLayer.prototype._createInspector = function (config) {
  60312. if (config === void 0) { config = {}; }
  60313. var popup = config.popup || false;
  60314. var initialTab = config.initialTab || 0;
  60315. var parentElement = config.parentElement || null;
  60316. if (!this._inspector) {
  60317. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60318. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60319. } // else nothing to do as instance is already created
  60320. };
  60321. DebugLayer.prototype.isVisible = function () {
  60322. if (!this._inspector) {
  60323. return false;
  60324. }
  60325. return true;
  60326. };
  60327. DebugLayer.prototype.hide = function () {
  60328. if (this._inspector) {
  60329. try {
  60330. this._inspector.dispose();
  60331. }
  60332. catch (e) {
  60333. // If the inspector has been removed directly from the inspector tool
  60334. }
  60335. this.onPropertyChangedObservable.clear();
  60336. this._inspector = null;
  60337. }
  60338. };
  60339. /**
  60340. *
  60341. * Launch the debugLayer.
  60342. *
  60343. * initialTab:
  60344. * | Value | Tab Name |
  60345. * | --- | --- |
  60346. * | 0 | Scene |
  60347. * | 1 | Console |
  60348. * | 2 | Stats |
  60349. * | 3 | Textures |
  60350. * | 4 | Mesh |
  60351. * | 5 | Light |
  60352. * | 6 | Material |
  60353. * | 7 | GLTF |
  60354. * | 8 | GUI |
  60355. * | 9 | Physics |
  60356. * | 10 | Camera |
  60357. * | 11 | Audio |
  60358. *
  60359. */
  60360. DebugLayer.prototype.show = function (config) {
  60361. if (config === void 0) { config = {}; }
  60362. if (typeof this.BJSINSPECTOR == 'undefined') {
  60363. // Load inspector and add it to the DOM
  60364. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60365. }
  60366. else {
  60367. // Otherwise creates the inspector
  60368. this._createInspector(config);
  60369. }
  60370. };
  60371. /**
  60372. * Gets the active tab
  60373. * @return the index of the active tab or -1 if the inspector is hidden
  60374. */
  60375. DebugLayer.prototype.getActiveTab = function () {
  60376. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60377. };
  60378. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60379. return DebugLayer;
  60380. }());
  60381. BABYLON.DebugLayer = DebugLayer;
  60382. })(BABYLON || (BABYLON = {}));
  60383. //# sourceMappingURL=babylon.debugLayer.js.map
  60384. var BABYLON;
  60385. (function (BABYLON) {
  60386. var Debug;
  60387. (function (Debug) {
  60388. /**
  60389. * Used to show the physics impostor around the specific mesh
  60390. */
  60391. var PhysicsViewer = /** @class */ (function () {
  60392. /**
  60393. * Creates a new PhysicsViewer
  60394. * @param scene defines the hosting scene
  60395. */
  60396. function PhysicsViewer(scene) {
  60397. /** @hidden */
  60398. this._impostors = [];
  60399. /** @hidden */
  60400. this._meshes = [];
  60401. /** @hidden */
  60402. this._numMeshes = 0;
  60403. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60404. var physicEngine = this._scene.getPhysicsEngine();
  60405. if (physicEngine) {
  60406. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60407. }
  60408. }
  60409. /** @hidden */
  60410. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60411. var plugin = this._physicsEnginePlugin;
  60412. for (var i = 0; i < this._numMeshes; i++) {
  60413. var impostor = this._impostors[i];
  60414. if (!impostor) {
  60415. continue;
  60416. }
  60417. if (impostor.isDisposed) {
  60418. this.hideImpostor(this._impostors[i--]);
  60419. }
  60420. else {
  60421. var mesh = this._meshes[i];
  60422. if (mesh && plugin) {
  60423. plugin.syncMeshWithImpostor(mesh, impostor);
  60424. }
  60425. }
  60426. }
  60427. };
  60428. /**
  60429. * Renders a specified physic impostor
  60430. * @param impostor defines the impostor to render
  60431. */
  60432. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60433. if (!this._scene) {
  60434. return;
  60435. }
  60436. for (var i = 0; i < this._numMeshes; i++) {
  60437. if (this._impostors[i] == impostor) {
  60438. return;
  60439. }
  60440. }
  60441. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60442. if (debugMesh) {
  60443. this._impostors[this._numMeshes] = impostor;
  60444. this._meshes[this._numMeshes] = debugMesh;
  60445. if (this._numMeshes === 0) {
  60446. this._renderFunction = this._updateDebugMeshes.bind(this);
  60447. this._scene.registerBeforeRender(this._renderFunction);
  60448. }
  60449. this._numMeshes++;
  60450. }
  60451. };
  60452. /**
  60453. * Hides a specified physic impostor
  60454. * @param impostor defines the impostor to hide
  60455. */
  60456. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60457. if (!impostor || !this._scene) {
  60458. return;
  60459. }
  60460. var removed = false;
  60461. for (var i = 0; i < this._numMeshes; i++) {
  60462. if (this._impostors[i] == impostor) {
  60463. var mesh = this._meshes[i];
  60464. if (!mesh) {
  60465. continue;
  60466. }
  60467. this._scene.removeMesh(mesh);
  60468. mesh.dispose();
  60469. this._numMeshes--;
  60470. if (this._numMeshes > 0) {
  60471. this._meshes[i] = this._meshes[this._numMeshes];
  60472. this._impostors[i] = this._impostors[this._numMeshes];
  60473. this._meshes[this._numMeshes] = null;
  60474. this._impostors[this._numMeshes] = null;
  60475. }
  60476. else {
  60477. this._meshes[0] = null;
  60478. this._impostors[0] = null;
  60479. }
  60480. removed = true;
  60481. break;
  60482. }
  60483. }
  60484. if (removed && this._numMeshes === 0) {
  60485. this._scene.unregisterBeforeRender(this._renderFunction);
  60486. }
  60487. };
  60488. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60489. if (!this._debugMaterial) {
  60490. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60491. this._debugMaterial.wireframe = true;
  60492. }
  60493. return this._debugMaterial;
  60494. };
  60495. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60496. if (!this._debugBoxMesh) {
  60497. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60498. this._debugBoxMesh.renderingGroupId = 1;
  60499. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60500. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60501. scene.removeMesh(this._debugBoxMesh);
  60502. }
  60503. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60504. };
  60505. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60506. if (!this._debugSphereMesh) {
  60507. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60508. this._debugSphereMesh.renderingGroupId = 1;
  60509. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60510. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60511. scene.removeMesh(this._debugSphereMesh);
  60512. }
  60513. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60514. };
  60515. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60516. var mesh = null;
  60517. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60518. mesh = this._getDebugBoxMesh(scene);
  60519. impostor.getBoxSizeToRef(mesh.scaling);
  60520. }
  60521. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60522. mesh = this._getDebugSphereMesh(scene);
  60523. var radius = impostor.getRadius();
  60524. mesh.scaling.x = radius * 2;
  60525. mesh.scaling.y = radius * 2;
  60526. mesh.scaling.z = radius * 2;
  60527. }
  60528. return mesh;
  60529. };
  60530. /** Releases all resources */
  60531. PhysicsViewer.prototype.dispose = function () {
  60532. for (var i = 0; i < this._numMeshes; i++) {
  60533. this.hideImpostor(this._impostors[i]);
  60534. }
  60535. if (this._debugBoxMesh) {
  60536. this._debugBoxMesh.dispose();
  60537. }
  60538. if (this._debugSphereMesh) {
  60539. this._debugSphereMesh.dispose();
  60540. }
  60541. if (this._debugMaterial) {
  60542. this._debugMaterial.dispose();
  60543. }
  60544. this._impostors.length = 0;
  60545. this._scene = null;
  60546. this._physicsEnginePlugin = null;
  60547. };
  60548. return PhysicsViewer;
  60549. }());
  60550. Debug.PhysicsViewer = PhysicsViewer;
  60551. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60552. })(BABYLON || (BABYLON = {}));
  60553. //# sourceMappingURL=babylon.physicsViewer.js.map
  60554. var BABYLON;
  60555. (function (BABYLON) {
  60556. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60557. get: function () {
  60558. return this._forceShowBoundingBoxes || false;
  60559. },
  60560. set: function (value) {
  60561. this._forceShowBoundingBoxes = value;
  60562. // Lazyly creates a BB renderer if needed.
  60563. if (value) {
  60564. this.getBoundingBoxRenderer();
  60565. }
  60566. },
  60567. enumerable: true,
  60568. configurable: true
  60569. });
  60570. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60571. if (!this._boundingBoxRenderer) {
  60572. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60573. }
  60574. return this._boundingBoxRenderer;
  60575. };
  60576. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60577. get: function () {
  60578. return this._showBoundingBox || false;
  60579. },
  60580. set: function (value) {
  60581. this._showBoundingBox = value;
  60582. // Lazyly creates a BB renderer if needed.
  60583. if (value) {
  60584. this.getScene().getBoundingBoxRenderer();
  60585. }
  60586. },
  60587. enumerable: true,
  60588. configurable: true
  60589. });
  60590. var BoundingBoxRenderer = /** @class */ (function () {
  60591. function BoundingBoxRenderer(scene) {
  60592. /**
  60593. * The component name helpfull to identify the component in the list of scene components.
  60594. */
  60595. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60596. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60597. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60598. this.showBackLines = true;
  60599. this.renderList = new BABYLON.SmartArray(32);
  60600. this._vertexBuffers = {};
  60601. this.scene = scene;
  60602. scene._addComponent(this);
  60603. }
  60604. /**
  60605. * Registers the component in a given scene
  60606. */
  60607. BoundingBoxRenderer.prototype.register = function () {
  60608. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60609. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60610. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60611. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60612. };
  60613. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60614. if (mesh.showSubMeshesBoundingBox) {
  60615. var boundingInfo = subMesh.getBoundingInfo();
  60616. if (boundingInfo !== null && boundingInfo !== undefined) {
  60617. this.renderList.push(boundingInfo.boundingBox);
  60618. }
  60619. }
  60620. };
  60621. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60622. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60623. var boundingInfo = sourceMesh.getBoundingInfo();
  60624. this.renderList.push(boundingInfo.boundingBox);
  60625. }
  60626. };
  60627. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60628. if (this._colorShader) {
  60629. return;
  60630. }
  60631. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60632. attributes: [BABYLON.VertexBuffer.PositionKind],
  60633. uniforms: ["world", "viewProjection", "color"]
  60634. });
  60635. var engine = this.scene.getEngine();
  60636. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60637. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60638. this._createIndexBuffer();
  60639. };
  60640. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60641. var engine = this.scene.getEngine();
  60642. 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]);
  60643. };
  60644. /**
  60645. * Rebuilds the elements related to this component in case of
  60646. * context lost for instance.
  60647. */
  60648. BoundingBoxRenderer.prototype.rebuild = function () {
  60649. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60650. if (vb) {
  60651. vb._rebuild();
  60652. }
  60653. this._createIndexBuffer();
  60654. };
  60655. BoundingBoxRenderer.prototype.reset = function () {
  60656. this.renderList.reset();
  60657. };
  60658. BoundingBoxRenderer.prototype.render = function () {
  60659. if (this.renderList.length === 0) {
  60660. return;
  60661. }
  60662. this._prepareRessources();
  60663. if (!this._colorShader.isReady()) {
  60664. return;
  60665. }
  60666. var engine = this.scene.getEngine();
  60667. engine.setDepthWrite(false);
  60668. this._colorShader._preBind();
  60669. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60670. var boundingBox = this.renderList.data[boundingBoxIndex];
  60671. var min = boundingBox.minimum;
  60672. var max = boundingBox.maximum;
  60673. var diff = max.subtract(min);
  60674. var median = min.add(diff.scale(0.5));
  60675. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60676. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60677. .multiply(boundingBox.getWorldMatrix());
  60678. // VBOs
  60679. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60680. if (this.showBackLines) {
  60681. // Back
  60682. engine.setDepthFunctionToGreaterOrEqual();
  60683. this.scene.resetCachedMaterial();
  60684. this._colorShader.setColor4("color", this.backColor.toColor4());
  60685. this._colorShader.bind(worldMatrix);
  60686. // Draw order
  60687. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60688. }
  60689. // Front
  60690. engine.setDepthFunctionToLess();
  60691. this.scene.resetCachedMaterial();
  60692. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60693. this._colorShader.bind(worldMatrix);
  60694. // Draw order
  60695. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60696. }
  60697. this._colorShader.unbind();
  60698. engine.setDepthFunctionToLessOrEqual();
  60699. engine.setDepthWrite(true);
  60700. };
  60701. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60702. this._prepareRessources();
  60703. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60704. return;
  60705. }
  60706. var engine = this.scene.getEngine();
  60707. engine.setDepthWrite(false);
  60708. engine.setColorWrite(false);
  60709. this._colorShader._preBind();
  60710. var boundingBox = mesh._boundingInfo.boundingBox;
  60711. var min = boundingBox.minimum;
  60712. var max = boundingBox.maximum;
  60713. var diff = max.subtract(min);
  60714. var median = min.add(diff.scale(0.5));
  60715. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60716. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60717. .multiply(boundingBox.getWorldMatrix());
  60718. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60719. engine.setDepthFunctionToLess();
  60720. this.scene.resetCachedMaterial();
  60721. this._colorShader.bind(worldMatrix);
  60722. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60723. this._colorShader.unbind();
  60724. engine.setDepthFunctionToLessOrEqual();
  60725. engine.setDepthWrite(true);
  60726. engine.setColorWrite(true);
  60727. };
  60728. BoundingBoxRenderer.prototype.dispose = function () {
  60729. if (!this._colorShader) {
  60730. return;
  60731. }
  60732. this.renderList.dispose();
  60733. this._colorShader.dispose();
  60734. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60735. if (buffer) {
  60736. buffer.dispose();
  60737. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60738. }
  60739. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60740. };
  60741. return BoundingBoxRenderer;
  60742. }());
  60743. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60744. })(BABYLON || (BABYLON = {}));
  60745. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60746. var BABYLON;
  60747. (function (BABYLON) {
  60748. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60749. return this._gl.createTransformFeedback();
  60750. };
  60751. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60752. this._gl.deleteTransformFeedback(value);
  60753. };
  60754. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60755. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60756. };
  60757. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60758. if (usePoints === void 0) { usePoints = true; }
  60759. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60760. };
  60761. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60762. this._gl.endTransformFeedback();
  60763. };
  60764. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60765. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60766. };
  60767. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60768. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60769. };
  60770. })(BABYLON || (BABYLON = {}));
  60771. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60772. var BABYLON;
  60773. (function (BABYLON) {
  60774. /**
  60775. * This represents a GPU particle system in Babylon
  60776. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60777. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60778. */
  60779. var GPUParticleSystem = /** @class */ (function (_super) {
  60780. __extends(GPUParticleSystem, _super);
  60781. /**
  60782. * Instantiates a GPU particle system.
  60783. * 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.
  60784. * @param name The name of the particle system
  60785. * @param options The options used to create the system
  60786. * @param scene The scene the particle system belongs to
  60787. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60788. */
  60789. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60790. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60791. var _this = _super.call(this, name) || this;
  60792. /**
  60793. * The layer mask we are rendering the particles through.
  60794. */
  60795. _this.layerMask = 0x0FFFFFFF;
  60796. _this._accumulatedCount = 0;
  60797. _this._targetIndex = 0;
  60798. _this._currentRenderId = -1;
  60799. _this._started = false;
  60800. _this._stopped = false;
  60801. _this._timeDelta = 0;
  60802. _this._attributesStrideSize = 21;
  60803. _this._actualFrame = 0;
  60804. _this._rawTextureWidth = 256;
  60805. /**
  60806. * An event triggered when the system is disposed.
  60807. */
  60808. _this.onDisposeObservable = new BABYLON.Observable();
  60809. /**
  60810. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60811. * to override the particles.
  60812. */
  60813. _this.forceDepthWrite = false;
  60814. _this._preWarmDone = false;
  60815. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60816. // Setup the default processing configuration to the scene.
  60817. _this._attachImageProcessingConfiguration(null);
  60818. _this._engine = _this._scene.getEngine();
  60819. if (!options.randomTextureSize) {
  60820. delete options.randomTextureSize;
  60821. }
  60822. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60823. var optionsAsNumber = options;
  60824. if (isFinite(optionsAsNumber)) {
  60825. fullOptions.capacity = optionsAsNumber;
  60826. }
  60827. _this._capacity = fullOptions.capacity;
  60828. _this._activeCount = fullOptions.capacity;
  60829. _this._currentActiveCount = 0;
  60830. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60831. _this._scene.particleSystems.push(_this);
  60832. _this._updateEffectOptions = {
  60833. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60834. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60835. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60836. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60837. uniformBuffersNames: [],
  60838. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60839. defines: "",
  60840. fallbacks: null,
  60841. onCompiled: null,
  60842. onError: null,
  60843. indexParameters: null,
  60844. maxSimultaneousLights: 0,
  60845. transformFeedbackVaryings: []
  60846. };
  60847. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60848. // Random data
  60849. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60850. var d = [];
  60851. for (var i = 0; i < maxTextureSize; ++i) {
  60852. d.push(Math.random());
  60853. d.push(Math.random());
  60854. d.push(Math.random());
  60855. d.push(Math.random());
  60856. }
  60857. _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);
  60858. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60859. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60860. d = [];
  60861. for (var i = 0; i < maxTextureSize; ++i) {
  60862. d.push(Math.random());
  60863. d.push(Math.random());
  60864. d.push(Math.random());
  60865. d.push(Math.random());
  60866. }
  60867. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  60868. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60869. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60870. _this._randomTextureSize = maxTextureSize;
  60871. return _this;
  60872. }
  60873. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60874. /**
  60875. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60876. */
  60877. get: function () {
  60878. if (!BABYLON.Engine.LastCreatedEngine) {
  60879. return false;
  60880. }
  60881. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60882. },
  60883. enumerable: true,
  60884. configurable: true
  60885. });
  60886. /**
  60887. * Gets the maximum number of particles active at the same time.
  60888. * @returns The max number of active particles.
  60889. */
  60890. GPUParticleSystem.prototype.getCapacity = function () {
  60891. return this._capacity;
  60892. };
  60893. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60894. /**
  60895. * Gets or set the number of active particles
  60896. */
  60897. get: function () {
  60898. return this._activeCount;
  60899. },
  60900. set: function (value) {
  60901. this._activeCount = Math.min(value, this._capacity);
  60902. },
  60903. enumerable: true,
  60904. configurable: true
  60905. });
  60906. /**
  60907. * Is this system ready to be used/rendered
  60908. * @return true if the system is ready
  60909. */
  60910. GPUParticleSystem.prototype.isReady = function () {
  60911. if (!this._updateEffect) {
  60912. this._recreateUpdateEffect();
  60913. this._recreateRenderEffect();
  60914. return false;
  60915. }
  60916. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60917. return false;
  60918. }
  60919. return true;
  60920. };
  60921. /**
  60922. * Gets if the system has been started. (Note: this will still be true after stop is called)
  60923. * @returns True if it has been started, otherwise false.
  60924. */
  60925. GPUParticleSystem.prototype.isStarted = function () {
  60926. return this._started;
  60927. };
  60928. /**
  60929. * Starts the particle system and begins to emit
  60930. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60931. */
  60932. GPUParticleSystem.prototype.start = function (delay) {
  60933. var _this = this;
  60934. if (delay === void 0) { delay = 0; }
  60935. if (delay) {
  60936. setTimeout(function () {
  60937. _this.start(0);
  60938. }, delay);
  60939. return;
  60940. }
  60941. this._started = true;
  60942. this._stopped = false;
  60943. this._preWarmDone = false;
  60944. };
  60945. /**
  60946. * Stops the particle system.
  60947. */
  60948. GPUParticleSystem.prototype.stop = function () {
  60949. this._stopped = true;
  60950. };
  60951. /**
  60952. * Remove all active particles
  60953. */
  60954. GPUParticleSystem.prototype.reset = function () {
  60955. this._releaseBuffers();
  60956. this._releaseVAOs();
  60957. this._currentActiveCount = 0;
  60958. this._targetIndex = 0;
  60959. };
  60960. /**
  60961. * Returns the string "GPUParticleSystem"
  60962. * @returns a string containing the class name
  60963. */
  60964. GPUParticleSystem.prototype.getClassName = function () {
  60965. return "GPUParticleSystem";
  60966. };
  60967. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60968. if (!gradients) {
  60969. return this;
  60970. }
  60971. var index = 0;
  60972. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60973. var valueGradient = gradients_1[_i];
  60974. if (valueGradient.gradient === gradient) {
  60975. gradients.splice(index, 1);
  60976. break;
  60977. }
  60978. index++;
  60979. }
  60980. if (texture) {
  60981. texture.dispose();
  60982. }
  60983. this._releaseBuffers();
  60984. return this;
  60985. };
  60986. /**
  60987. * Adds a new color gradient
  60988. * @param gradient defines the gradient to use (between 0 and 1)
  60989. * @param color defines the color to affect to the specified gradient
  60990. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60991. * @returns the current particle system
  60992. */
  60993. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60994. if (!this._colorGradients) {
  60995. this._colorGradients = [];
  60996. }
  60997. var colorGradient = new BABYLON.ColorGradient();
  60998. colorGradient.gradient = gradient;
  60999. colorGradient.color1 = color1;
  61000. this._colorGradients.push(colorGradient);
  61001. this._colorGradients.sort(function (a, b) {
  61002. if (a.gradient < b.gradient) {
  61003. return -1;
  61004. }
  61005. else if (a.gradient > b.gradient) {
  61006. return 1;
  61007. }
  61008. return 0;
  61009. });
  61010. if (this._colorGradientsTexture) {
  61011. this._colorGradientsTexture.dispose();
  61012. this._colorGradientsTexture = null;
  61013. }
  61014. this._releaseBuffers();
  61015. return this;
  61016. };
  61017. /**
  61018. * Remove a specific color gradient
  61019. * @param gradient defines the gradient to remove
  61020. * @returns the current particle system
  61021. */
  61022. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61023. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  61024. this._colorGradientsTexture = null;
  61025. return this;
  61026. };
  61027. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61028. var valueGradient = new BABYLON.FactorGradient();
  61029. valueGradient.gradient = gradient;
  61030. valueGradient.factor1 = factor;
  61031. factorGradients.push(valueGradient);
  61032. factorGradients.sort(function (a, b) {
  61033. if (a.gradient < b.gradient) {
  61034. return -1;
  61035. }
  61036. else if (a.gradient > b.gradient) {
  61037. return 1;
  61038. }
  61039. return 0;
  61040. });
  61041. this._releaseBuffers();
  61042. };
  61043. /**
  61044. * Adds a new size gradient
  61045. * @param gradient defines the gradient to use (between 0 and 1)
  61046. * @param factor defines the size factor to affect to the specified gradient
  61047. * @returns the current particle system
  61048. */
  61049. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61050. if (!this._sizeGradients) {
  61051. this._sizeGradients = [];
  61052. }
  61053. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61054. if (this._sizeGradientsTexture) {
  61055. this._sizeGradientsTexture.dispose();
  61056. this._sizeGradientsTexture = null;
  61057. }
  61058. this._releaseBuffers();
  61059. return this;
  61060. };
  61061. /**
  61062. * Remove a specific size gradient
  61063. * @param gradient defines the gradient to remove
  61064. * @returns the current particle system
  61065. */
  61066. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61067. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61068. this._sizeGradientsTexture = null;
  61069. return this;
  61070. };
  61071. /**
  61072. * Adds a new angular speed gradient
  61073. * @param gradient defines the gradient to use (between 0 and 1)
  61074. * @param factor defines the angular speed to affect to the specified gradient
  61075. * @returns the current particle system
  61076. */
  61077. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61078. if (!this._angularSpeedGradients) {
  61079. this._angularSpeedGradients = [];
  61080. }
  61081. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61082. if (this._angularSpeedGradientsTexture) {
  61083. this._angularSpeedGradientsTexture.dispose();
  61084. this._angularSpeedGradientsTexture = null;
  61085. }
  61086. this._releaseBuffers();
  61087. return this;
  61088. };
  61089. /**
  61090. * Remove a specific angular speed gradient
  61091. * @param gradient defines the gradient to remove
  61092. * @returns the current particle system
  61093. */
  61094. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61095. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61096. this._angularSpeedGradientsTexture = null;
  61097. return this;
  61098. };
  61099. /**
  61100. * Adds a new velocity gradient
  61101. * @param gradient defines the gradient to use (between 0 and 1)
  61102. * @param factor defines the velocity to affect to the specified gradient
  61103. * @returns the current particle system
  61104. */
  61105. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61106. if (!this._velocityGradients) {
  61107. this._velocityGradients = [];
  61108. }
  61109. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61110. if (this._velocityGradientsTexture) {
  61111. this._velocityGradientsTexture.dispose();
  61112. this._velocityGradientsTexture = null;
  61113. }
  61114. this._releaseBuffers();
  61115. return this;
  61116. };
  61117. /**
  61118. * Remove a specific velocity gradient
  61119. * @param gradient defines the gradient to remove
  61120. * @returns the current particle system
  61121. */
  61122. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61123. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61124. this._velocityGradientsTexture = null;
  61125. return this;
  61126. };
  61127. /**
  61128. * Adds a new limit velocity gradient
  61129. * @param gradient defines the gradient to use (between 0 and 1)
  61130. * @param factor defines the limit velocity value to affect to the specified gradient
  61131. * @returns the current particle system
  61132. */
  61133. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61134. if (!this._limitVelocityGradients) {
  61135. this._limitVelocityGradients = [];
  61136. }
  61137. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61138. if (this._limitVelocityGradientsTexture) {
  61139. this._limitVelocityGradientsTexture.dispose();
  61140. this._limitVelocityGradientsTexture = null;
  61141. }
  61142. this._releaseBuffers();
  61143. return this;
  61144. };
  61145. /**
  61146. * Remove a specific limit velocity gradient
  61147. * @param gradient defines the gradient to remove
  61148. * @returns the current particle system
  61149. */
  61150. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61151. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61152. this._limitVelocityGradientsTexture = null;
  61153. return this;
  61154. };
  61155. /**
  61156. * Adds a new drag gradient
  61157. * @param gradient defines the gradient to use (between 0 and 1)
  61158. * @param factor defines the drag value to affect to the specified gradient
  61159. * @returns the current particle system
  61160. */
  61161. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61162. if (!this._dragGradients) {
  61163. this._dragGradients = [];
  61164. }
  61165. this._addFactorGradient(this._dragGradients, gradient, factor);
  61166. if (this._dragGradientsTexture) {
  61167. this._dragGradientsTexture.dispose();
  61168. this._dragGradientsTexture = null;
  61169. }
  61170. this._releaseBuffers();
  61171. return this;
  61172. };
  61173. /**
  61174. * Remove a specific drag gradient
  61175. * @param gradient defines the gradient to remove
  61176. * @returns the current particle system
  61177. */
  61178. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61179. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  61180. this._dragGradientsTexture = null;
  61181. return this;
  61182. };
  61183. GPUParticleSystem.prototype._reset = function () {
  61184. this._releaseBuffers();
  61185. };
  61186. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61187. var updateVertexBuffers = {};
  61188. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61189. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61190. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61191. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61192. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61193. var offset = 12;
  61194. if (!this._colorGradientsTexture) {
  61195. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61196. offset += 4;
  61197. }
  61198. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61199. offset += 3;
  61200. if (!this._isBillboardBased) {
  61201. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61202. offset += 3;
  61203. }
  61204. if (this._angularSpeedGradientsTexture) {
  61205. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61206. offset += 1;
  61207. }
  61208. else {
  61209. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61210. offset += 2;
  61211. }
  61212. if (this._isAnimationSheetEnabled) {
  61213. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61214. offset += 1;
  61215. }
  61216. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61217. this._engine.bindArrayBuffer(null);
  61218. return vao;
  61219. };
  61220. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61221. var renderVertexBuffers = {};
  61222. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61223. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61224. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61225. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61226. var offset = 12;
  61227. if (!this._colorGradientsTexture) {
  61228. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61229. offset += 4;
  61230. }
  61231. offset += 3; // Direction
  61232. if (!this._isBillboardBased) {
  61233. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61234. offset += 3;
  61235. }
  61236. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61237. if (this._angularSpeedGradientsTexture) {
  61238. offset++;
  61239. }
  61240. else {
  61241. offset += 2;
  61242. }
  61243. if (this._isAnimationSheetEnabled) {
  61244. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61245. offset += 1;
  61246. }
  61247. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61248. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61249. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61250. this._engine.bindArrayBuffer(null);
  61251. return vao;
  61252. };
  61253. GPUParticleSystem.prototype._initialize = function (force) {
  61254. if (force === void 0) { force = false; }
  61255. if (this._buffer0 && !force) {
  61256. return;
  61257. }
  61258. var engine = this._scene.getEngine();
  61259. var data = new Array();
  61260. if (!this.isBillboardBased) {
  61261. this._attributesStrideSize += 3;
  61262. }
  61263. if (this._colorGradientsTexture) {
  61264. this._attributesStrideSize -= 4;
  61265. }
  61266. if (this._angularSpeedGradientsTexture) {
  61267. this._attributesStrideSize -= 1;
  61268. }
  61269. if (this._isAnimationSheetEnabled) {
  61270. this._attributesStrideSize += 1;
  61271. }
  61272. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61273. // position
  61274. data.push(0.0);
  61275. data.push(0.0);
  61276. data.push(0.0);
  61277. // Age and life
  61278. data.push(0.0); // create the particle as a dead one to create a new one at start
  61279. data.push(0.0);
  61280. // Seed
  61281. data.push(Math.random());
  61282. data.push(Math.random());
  61283. data.push(Math.random());
  61284. data.push(Math.random());
  61285. // Size
  61286. data.push(0.0);
  61287. data.push(0.0);
  61288. data.push(0.0);
  61289. if (!this._colorGradientsTexture) {
  61290. // color
  61291. data.push(0.0);
  61292. data.push(0.0);
  61293. data.push(0.0);
  61294. data.push(0.0);
  61295. }
  61296. // direction
  61297. data.push(0.0);
  61298. data.push(0.0);
  61299. data.push(0.0);
  61300. if (!this.isBillboardBased) {
  61301. // initialDirection
  61302. data.push(0.0);
  61303. data.push(0.0);
  61304. data.push(0.0);
  61305. }
  61306. // angle
  61307. data.push(0.0);
  61308. if (!this._angularSpeedGradientsTexture) {
  61309. data.push(0.0);
  61310. }
  61311. if (this._isAnimationSheetEnabled) {
  61312. data.push(0.0);
  61313. }
  61314. }
  61315. // Sprite data
  61316. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61317. -0.5, 0.5, 0, 1,
  61318. -0.5, -0.5, 0, 0,
  61319. 0.5, -0.5, 1, 0]);
  61320. // Buffers
  61321. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61322. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61323. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61324. // Update VAO
  61325. this._updateVAO = [];
  61326. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61327. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61328. // Render VAO
  61329. this._renderVAO = [];
  61330. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61331. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61332. // Links
  61333. this._sourceBuffer = this._buffer0;
  61334. this._targetBuffer = this._buffer1;
  61335. };
  61336. /** @hidden */
  61337. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61338. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61339. if (this._isBillboardBased) {
  61340. defines += "\n#define BILLBOARD";
  61341. }
  61342. if (this._colorGradientsTexture) {
  61343. defines += "\n#define COLORGRADIENTS";
  61344. }
  61345. if (this._sizeGradientsTexture) {
  61346. defines += "\n#define SIZEGRADIENTS";
  61347. }
  61348. if (this._angularSpeedGradientsTexture) {
  61349. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61350. }
  61351. if (this._velocityGradientsTexture) {
  61352. defines += "\n#define VELOCITYGRADIENTS";
  61353. }
  61354. if (this.isAnimationSheetEnabled) {
  61355. defines += "\n#define ANIMATESHEET";
  61356. }
  61357. if (this.noiseTexture) {
  61358. defines += "\n#define NOISE";
  61359. }
  61360. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61361. return;
  61362. }
  61363. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61364. if (!this._colorGradientsTexture) {
  61365. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61366. }
  61367. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61368. if (!this._isBillboardBased) {
  61369. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61370. }
  61371. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61372. if (this.isAnimationSheetEnabled) {
  61373. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61374. }
  61375. this._updateEffectOptions.defines = defines;
  61376. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61377. };
  61378. /** @hidden */
  61379. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61380. var defines = "";
  61381. if (this._scene.clipPlane) {
  61382. defines = "\n#define CLIPPLANE";
  61383. }
  61384. if (this._scene.clipPlane2) {
  61385. defines = "\n#define CLIPPLANE2";
  61386. }
  61387. if (this._scene.clipPlane3) {
  61388. defines = "\n#define CLIPPLANE3";
  61389. }
  61390. if (this._scene.clipPlane4) {
  61391. defines = "\n#define CLIPPLANE4";
  61392. }
  61393. if (this._isBillboardBased) {
  61394. defines += "\n#define BILLBOARD";
  61395. switch (this.billboardMode) {
  61396. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61397. defines += "\n#define BILLBOARDY";
  61398. break;
  61399. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61400. default:
  61401. break;
  61402. }
  61403. }
  61404. if (this._colorGradientsTexture) {
  61405. defines += "\n#define COLORGRADIENTS";
  61406. }
  61407. if (this.isAnimationSheetEnabled) {
  61408. defines += "\n#define ANIMATESHEET";
  61409. }
  61410. if (this._imageProcessingConfiguration) {
  61411. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61412. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61413. }
  61414. if (this._renderEffect && this._renderEffect.defines === defines) {
  61415. return;
  61416. }
  61417. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61418. var samplers = ["textureSampler", "colorGradientSampler"];
  61419. if (BABYLON.ImageProcessingConfiguration) {
  61420. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61421. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61422. }
  61423. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61424. };
  61425. /**
  61426. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61427. * @param preWarm defines if we are in the pre-warmimg phase
  61428. */
  61429. GPUParticleSystem.prototype.animate = function (preWarm) {
  61430. if (preWarm === void 0) { preWarm = false; }
  61431. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61432. this._actualFrame += this._timeDelta;
  61433. if (!this._stopped) {
  61434. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61435. this.stop();
  61436. }
  61437. }
  61438. };
  61439. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61440. var texture = this[textureName];
  61441. if (!factorGradients || !factorGradients.length || texture) {
  61442. return;
  61443. }
  61444. var data = new Float32Array(this._rawTextureWidth);
  61445. for (var x = 0; x < this._rawTextureWidth; x++) {
  61446. var ratio = x / this._rawTextureWidth;
  61447. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61448. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61449. });
  61450. }
  61451. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61452. };
  61453. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61454. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61455. };
  61456. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61457. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61458. };
  61459. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61460. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61461. };
  61462. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61463. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61464. return;
  61465. }
  61466. var data = new Uint8Array(this._rawTextureWidth * 4);
  61467. var tmpColor = BABYLON.Tmp.Color4[0];
  61468. for (var x = 0; x < this._rawTextureWidth; x++) {
  61469. var ratio = x / this._rawTextureWidth;
  61470. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61471. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61472. data[x * 4] = tmpColor.r * 255;
  61473. data[x * 4 + 1] = tmpColor.g * 255;
  61474. data[x * 4 + 2] = tmpColor.b * 255;
  61475. data[x * 4 + 3] = tmpColor.a * 255;
  61476. });
  61477. }
  61478. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61479. };
  61480. /**
  61481. * Renders the particle system in its current state
  61482. * @param preWarm defines if the system should only update the particles but not render them
  61483. * @returns the current number of particles
  61484. */
  61485. GPUParticleSystem.prototype.render = function (preWarm) {
  61486. if (preWarm === void 0) { preWarm = false; }
  61487. if (!this._started) {
  61488. return 0;
  61489. }
  61490. this._createColorGradientTexture();
  61491. this._createSizeGradientTexture();
  61492. this._createAngularSpeedGradientTexture();
  61493. this._createVelocityGradientTexture();
  61494. this._recreateUpdateEffect();
  61495. this._recreateRenderEffect();
  61496. if (!this.isReady()) {
  61497. return 0;
  61498. }
  61499. if (!preWarm) {
  61500. if (!this._preWarmDone && this.preWarmCycles) {
  61501. for (var index = 0; index < this.preWarmCycles; index++) {
  61502. this.animate(true);
  61503. this.render(true);
  61504. }
  61505. this._preWarmDone = true;
  61506. }
  61507. if (this._currentRenderId === this._scene.getRenderId()) {
  61508. return 0;
  61509. }
  61510. this._currentRenderId = this._scene.getRenderId();
  61511. }
  61512. // Get everything ready to render
  61513. this._initialize();
  61514. this._accumulatedCount += this.emitRate * this._timeDelta;
  61515. if (this._accumulatedCount > 1) {
  61516. var intPart = this._accumulatedCount | 0;
  61517. this._accumulatedCount -= intPart;
  61518. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61519. }
  61520. if (!this._currentActiveCount) {
  61521. return 0;
  61522. }
  61523. // Enable update effect
  61524. this._engine.enableEffect(this._updateEffect);
  61525. this._engine.setState(false);
  61526. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61527. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61528. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61529. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61530. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61531. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61532. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61533. if (!this._colorGradientsTexture) {
  61534. this._updateEffect.setDirectColor4("color1", this.color1);
  61535. this._updateEffect.setDirectColor4("color2", this.color2);
  61536. }
  61537. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61538. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61539. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61540. this._updateEffect.setVector3("gravity", this.gravity);
  61541. if (this._sizeGradientsTexture) {
  61542. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61543. }
  61544. if (this._angularSpeedGradientsTexture) {
  61545. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61546. }
  61547. if (this._velocityGradientsTexture) {
  61548. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61549. }
  61550. if (this.particleEmitterType) {
  61551. this.particleEmitterType.applyToShader(this._updateEffect);
  61552. }
  61553. if (this._isAnimationSheetEnabled) {
  61554. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61555. }
  61556. if (this.noiseTexture) {
  61557. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61558. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61559. }
  61560. var emitterWM;
  61561. if (this.emitter.position) {
  61562. var emitterMesh = this.emitter;
  61563. emitterWM = emitterMesh.getWorldMatrix();
  61564. }
  61565. else {
  61566. var emitterPosition = this.emitter;
  61567. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61568. }
  61569. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61570. // Bind source VAO
  61571. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61572. // Update
  61573. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61574. this._engine.setRasterizerState(false);
  61575. this._engine.beginTransformFeedback(true);
  61576. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61577. this._engine.endTransformFeedback();
  61578. this._engine.setRasterizerState(true);
  61579. this._engine.bindTransformFeedbackBuffer(null);
  61580. if (!preWarm) {
  61581. // Enable render effect
  61582. this._engine.enableEffect(this._renderEffect);
  61583. var viewMatrix = this._scene.getViewMatrix();
  61584. this._renderEffect.setMatrix("view", viewMatrix);
  61585. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61586. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61587. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61588. if (this._colorGradientsTexture) {
  61589. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61590. }
  61591. else {
  61592. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61593. }
  61594. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61595. var baseSize = this.particleTexture.getBaseSize();
  61596. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61597. }
  61598. if (this._isBillboardBased) {
  61599. var camera = this._scene.activeCamera;
  61600. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61601. }
  61602. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61603. var invView = viewMatrix.clone();
  61604. invView.invert();
  61605. this._renderEffect.setMatrix("invView", invView);
  61606. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  61607. }
  61608. // image processing
  61609. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61610. this._imageProcessingConfiguration.bind(this._renderEffect);
  61611. }
  61612. // Draw order
  61613. switch (this.blendMode) {
  61614. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61615. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61616. break;
  61617. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61618. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61619. break;
  61620. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61621. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61622. break;
  61623. }
  61624. if (this.forceDepthWrite) {
  61625. this._engine.setDepthWrite(true);
  61626. }
  61627. // Bind source VAO
  61628. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61629. // Render
  61630. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61631. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61632. }
  61633. // Switch VAOs
  61634. this._targetIndex++;
  61635. if (this._targetIndex === 2) {
  61636. this._targetIndex = 0;
  61637. }
  61638. // Switch buffers
  61639. var tmpBuffer = this._sourceBuffer;
  61640. this._sourceBuffer = this._targetBuffer;
  61641. this._targetBuffer = tmpBuffer;
  61642. return this._currentActiveCount;
  61643. };
  61644. /**
  61645. * Rebuilds the particle system
  61646. */
  61647. GPUParticleSystem.prototype.rebuild = function () {
  61648. this._initialize(true);
  61649. };
  61650. GPUParticleSystem.prototype._releaseBuffers = function () {
  61651. if (this._buffer0) {
  61652. this._buffer0.dispose();
  61653. this._buffer0 = null;
  61654. }
  61655. if (this._buffer1) {
  61656. this._buffer1.dispose();
  61657. this._buffer1 = null;
  61658. }
  61659. if (this._spriteBuffer) {
  61660. this._spriteBuffer.dispose();
  61661. this._spriteBuffer = null;
  61662. }
  61663. };
  61664. GPUParticleSystem.prototype._releaseVAOs = function () {
  61665. if (!this._updateVAO) {
  61666. return;
  61667. }
  61668. for (var index = 0; index < this._updateVAO.length; index++) {
  61669. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61670. }
  61671. this._updateVAO = [];
  61672. for (var index = 0; index < this._renderVAO.length; index++) {
  61673. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61674. }
  61675. this._renderVAO = [];
  61676. };
  61677. /**
  61678. * Disposes the particle system and free the associated resources
  61679. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61680. */
  61681. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61682. if (disposeTexture === void 0) { disposeTexture = true; }
  61683. var index = this._scene.particleSystems.indexOf(this);
  61684. if (index > -1) {
  61685. this._scene.particleSystems.splice(index, 1);
  61686. }
  61687. this._releaseBuffers();
  61688. this._releaseVAOs();
  61689. if (this._colorGradientsTexture) {
  61690. this._colorGradientsTexture.dispose();
  61691. this._colorGradientsTexture = null;
  61692. }
  61693. if (this._sizeGradientsTexture) {
  61694. this._sizeGradientsTexture.dispose();
  61695. this._sizeGradientsTexture = null;
  61696. }
  61697. if (this._angularSpeedGradientsTexture) {
  61698. this._angularSpeedGradientsTexture.dispose();
  61699. this._angularSpeedGradientsTexture = null;
  61700. }
  61701. if (this._velocityGradientsTexture) {
  61702. this._velocityGradientsTexture.dispose();
  61703. this._velocityGradientsTexture = null;
  61704. }
  61705. if (this._limitVelocityGradientsTexture) {
  61706. this._limitVelocityGradientsTexture.dispose();
  61707. this._limitVelocityGradientsTexture = null;
  61708. }
  61709. if (this._randomTexture) {
  61710. this._randomTexture.dispose();
  61711. this._randomTexture = null;
  61712. }
  61713. if (this._randomTexture2) {
  61714. this._randomTexture2.dispose();
  61715. this._randomTexture2 = null;
  61716. }
  61717. if (disposeTexture && this.particleTexture) {
  61718. this.particleTexture.dispose();
  61719. this.particleTexture = null;
  61720. }
  61721. if (disposeTexture && this.noiseTexture) {
  61722. this.noiseTexture.dispose();
  61723. this.noiseTexture = null;
  61724. }
  61725. // Callback
  61726. this.onDisposeObservable.notifyObservers(this);
  61727. this.onDisposeObservable.clear();
  61728. };
  61729. /**
  61730. * Clones the particle system.
  61731. * @param name The name of the cloned object
  61732. * @param newEmitter The new emitter to use
  61733. * @returns the cloned particle system
  61734. */
  61735. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61736. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61737. BABYLON.Tools.DeepCopy(this, result);
  61738. if (newEmitter === undefined) {
  61739. newEmitter = this.emitter;
  61740. }
  61741. result.emitter = newEmitter;
  61742. if (this.particleTexture) {
  61743. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61744. }
  61745. return result;
  61746. };
  61747. /**
  61748. * Serializes the particle system to a JSON object.
  61749. * @returns the JSON object
  61750. */
  61751. GPUParticleSystem.prototype.serialize = function () {
  61752. var serializationObject = {};
  61753. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61754. serializationObject.activeParticleCount = this.activeParticleCount;
  61755. return serializationObject;
  61756. };
  61757. /**
  61758. * Parses a JSON object to create a GPU particle system.
  61759. * @param parsedParticleSystem The JSON object to parse
  61760. * @param scene The scene to create the particle system in
  61761. * @param rootUrl The root url to use to load external dependencies like texture
  61762. * @returns the parsed GPU particle system
  61763. */
  61764. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61765. var name = parsedParticleSystem.name;
  61766. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61767. if (parsedParticleSystem.activeParticleCount) {
  61768. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61769. }
  61770. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61771. return particleSystem;
  61772. };
  61773. return GPUParticleSystem;
  61774. }(BABYLON.BaseParticleSystem));
  61775. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61776. })(BABYLON || (BABYLON = {}));
  61777. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61778. var BABYLON;
  61779. (function (BABYLON) {
  61780. /**
  61781. * Represents one particle of a solid particle system.
  61782. */
  61783. var SolidParticle = /** @class */ (function () {
  61784. /**
  61785. * Creates a Solid Particle object.
  61786. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61787. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61788. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61789. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61790. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61791. * @param shapeId (integer) is the model shape identifier in the SPS.
  61792. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61793. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61794. */
  61795. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61796. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61797. /**
  61798. * particle global index
  61799. */
  61800. this.idx = 0;
  61801. /**
  61802. * The color of the particle
  61803. */
  61804. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61805. /**
  61806. * The world space position of the particle.
  61807. */
  61808. this.position = BABYLON.Vector3.Zero();
  61809. /**
  61810. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61811. */
  61812. this.rotation = BABYLON.Vector3.Zero();
  61813. /**
  61814. * The scaling of the particle.
  61815. */
  61816. this.scaling = BABYLON.Vector3.One();
  61817. /**
  61818. * The uvs of the particle.
  61819. */
  61820. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61821. /**
  61822. * The current speed of the particle.
  61823. */
  61824. this.velocity = BABYLON.Vector3.Zero();
  61825. /**
  61826. * The pivot point in the particle local space.
  61827. */
  61828. this.pivot = BABYLON.Vector3.Zero();
  61829. /**
  61830. * Must the particle be translated from its pivot point in its local space ?
  61831. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61832. * Default : false
  61833. */
  61834. this.translateFromPivot = false;
  61835. /**
  61836. * Is the particle active or not ?
  61837. */
  61838. this.alive = true;
  61839. /**
  61840. * Is the particle visible or not ?
  61841. */
  61842. this.isVisible = true;
  61843. /**
  61844. * Index of this particle in the global "positions" array (Internal use)
  61845. * @hidden
  61846. */
  61847. this._pos = 0;
  61848. /**
  61849. * @hidden Index of this particle in the global "indices" array (Internal use)
  61850. */
  61851. this._ind = 0;
  61852. /**
  61853. * ModelShape id of this particle
  61854. */
  61855. this.shapeId = 0;
  61856. /**
  61857. * Index of the particle in its shape id (Internal use)
  61858. */
  61859. this.idxInShape = 0;
  61860. /**
  61861. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  61862. */
  61863. this._stillInvisible = false;
  61864. /**
  61865. * @hidden Last computed particle rotation matrix
  61866. */
  61867. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61868. /**
  61869. * Parent particle Id, if any.
  61870. * Default null.
  61871. */
  61872. this.parentId = null;
  61873. /**
  61874. * @hidden Internal global position in the SPS.
  61875. */
  61876. this._globalPosition = BABYLON.Vector3.Zero();
  61877. this.idx = particleIndex;
  61878. this._pos = positionIndex;
  61879. this._ind = indiceIndex;
  61880. this._model = model;
  61881. this.shapeId = shapeId;
  61882. this.idxInShape = idxInShape;
  61883. this._sps = sps;
  61884. if (modelBoundingInfo) {
  61885. this._modelBoundingInfo = modelBoundingInfo;
  61886. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61887. }
  61888. }
  61889. Object.defineProperty(SolidParticle.prototype, "scale", {
  61890. /**
  61891. * Legacy support, changed scale to scaling
  61892. */
  61893. get: function () {
  61894. return this.scaling;
  61895. },
  61896. /**
  61897. * Legacy support, changed scale to scaling
  61898. */
  61899. set: function (scale) {
  61900. this.scaling = scale;
  61901. },
  61902. enumerable: true,
  61903. configurable: true
  61904. });
  61905. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61906. /**
  61907. * Legacy support, changed quaternion to rotationQuaternion
  61908. */
  61909. get: function () {
  61910. return this.rotationQuaternion;
  61911. },
  61912. /**
  61913. * Legacy support, changed quaternion to rotationQuaternion
  61914. */
  61915. set: function (q) {
  61916. this.rotationQuaternion = q;
  61917. },
  61918. enumerable: true,
  61919. configurable: true
  61920. });
  61921. /**
  61922. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61923. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61924. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61925. * @returns true if it intersects
  61926. */
  61927. SolidParticle.prototype.intersectsMesh = function (target) {
  61928. if (!this._boundingInfo || !target._boundingInfo) {
  61929. return false;
  61930. }
  61931. if (this._sps._bSphereOnly) {
  61932. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61933. }
  61934. return this._boundingInfo.intersects(target._boundingInfo, false);
  61935. };
  61936. return SolidParticle;
  61937. }());
  61938. BABYLON.SolidParticle = SolidParticle;
  61939. /**
  61940. * Represents the shape of the model used by one particle of a solid particle system.
  61941. * SPS internal tool, don't use it manually.
  61942. */
  61943. var ModelShape = /** @class */ (function () {
  61944. /**
  61945. * 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.
  61946. * SPS internal tool, don't use it manually.
  61947. * @hidden
  61948. */
  61949. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61950. /**
  61951. * length of the shape in the model indices array (internal use)
  61952. * @hidden
  61953. */
  61954. this._indicesLength = 0;
  61955. this.shapeID = id;
  61956. this._shape = shape;
  61957. this._indicesLength = indicesLength;
  61958. this._shapeUV = shapeUV;
  61959. this._positionFunction = posFunction;
  61960. this._vertexFunction = vtxFunction;
  61961. }
  61962. return ModelShape;
  61963. }());
  61964. BABYLON.ModelShape = ModelShape;
  61965. /**
  61966. * Represents a Depth Sorted Particle in the solid particle system.
  61967. */
  61968. var DepthSortedParticle = /** @class */ (function () {
  61969. function DepthSortedParticle() {
  61970. /**
  61971. * Index of the particle in the "indices" array
  61972. */
  61973. this.ind = 0;
  61974. /**
  61975. * Length of the particle shape in the "indices" array
  61976. */
  61977. this.indicesLength = 0;
  61978. /**
  61979. * Squared distance from the particle to the camera
  61980. */
  61981. this.sqDistance = 0.0;
  61982. }
  61983. return DepthSortedParticle;
  61984. }());
  61985. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61986. })(BABYLON || (BABYLON = {}));
  61987. //# sourceMappingURL=babylon.solidParticle.js.map
  61988. var BABYLON;
  61989. (function (BABYLON) {
  61990. /**
  61991. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61992. *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.
  61993. * The SPS is also a particle system. It provides some methods to manage the particles.
  61994. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61995. *
  61996. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61997. */
  61998. var SolidParticleSystem = /** @class */ (function () {
  61999. /**
  62000. * Creates a SPS (Solid Particle System) object.
  62001. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62002. * @param scene (Scene) is the scene in which the SPS is added.
  62003. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62004. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62005. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62006. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62007. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62008. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62009. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62010. */
  62011. function SolidParticleSystem(name, scene, options) {
  62012. /**
  62013. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62014. * Example : var p = SPS.particles[i];
  62015. */
  62016. this.particles = new Array();
  62017. /**
  62018. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62019. */
  62020. this.nbParticles = 0;
  62021. /**
  62022. * If the particles must ever face the camera (default false). Useful for planar particles.
  62023. */
  62024. this.billboard = false;
  62025. /**
  62026. * Recompute normals when adding a shape
  62027. */
  62028. this.recomputeNormals = true;
  62029. /**
  62030. * This a counter ofr your own usage. It's not set by any SPS functions.
  62031. */
  62032. this.counter = 0;
  62033. /**
  62034. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62035. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62036. */
  62037. this.vars = {};
  62038. /**
  62039. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62040. * @hidden
  62041. */
  62042. this._bSphereOnly = false;
  62043. /**
  62044. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62045. * @hidden
  62046. */
  62047. this._bSphereRadiusFactor = 1.0;
  62048. this._positions = new Array();
  62049. this._indices = new Array();
  62050. this._normals = new Array();
  62051. this._colors = new Array();
  62052. this._uvs = new Array();
  62053. this._index = 0; // indices index
  62054. this._updatable = true;
  62055. this._pickable = false;
  62056. this._isVisibilityBoxLocked = false;
  62057. this._alwaysVisible = false;
  62058. this._depthSort = false;
  62059. this._shapeCounter = 0;
  62060. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62061. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62062. this._computeParticleColor = true;
  62063. this._computeParticleTexture = true;
  62064. this._computeParticleRotation = true;
  62065. this._computeParticleVertex = false;
  62066. this._computeBoundingBox = false;
  62067. this._depthSortParticles = true;
  62068. this._cam_axisZ = BABYLON.Vector3.Zero();
  62069. this._cam_axisY = BABYLON.Vector3.Zero();
  62070. this._cam_axisX = BABYLON.Vector3.Zero();
  62071. this._axisZ = BABYLON.Axis.Z;
  62072. this._camDir = BABYLON.Vector3.Zero();
  62073. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62074. this._rotMatrix = new BABYLON.Matrix();
  62075. this._invertMatrix = new BABYLON.Matrix();
  62076. this._rotated = BABYLON.Vector3.Zero();
  62077. this._quaternion = new BABYLON.Quaternion();
  62078. this._vertex = BABYLON.Vector3.Zero();
  62079. this._normal = BABYLON.Vector3.Zero();
  62080. this._yaw = 0.0;
  62081. this._pitch = 0.0;
  62082. this._roll = 0.0;
  62083. this._halfroll = 0.0;
  62084. this._halfpitch = 0.0;
  62085. this._halfyaw = 0.0;
  62086. this._sinRoll = 0.0;
  62087. this._cosRoll = 0.0;
  62088. this._sinPitch = 0.0;
  62089. this._cosPitch = 0.0;
  62090. this._sinYaw = 0.0;
  62091. this._cosYaw = 0.0;
  62092. this._mustUnrotateFixedNormals = false;
  62093. this._minimum = BABYLON.Vector3.Zero();
  62094. this._maximum = BABYLON.Vector3.Zero();
  62095. this._minBbox = BABYLON.Vector3.Zero();
  62096. this._maxBbox = BABYLON.Vector3.Zero();
  62097. this._particlesIntersect = false;
  62098. this._depthSortFunction = function (p1, p2) {
  62099. return (p2.sqDistance - p1.sqDistance);
  62100. };
  62101. this._needs32Bits = false;
  62102. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62103. this._scaledPivot = BABYLON.Vector3.Zero();
  62104. this._particleHasParent = false;
  62105. this.name = name;
  62106. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62107. this._camera = scene.activeCamera;
  62108. this._pickable = options ? options.isPickable : false;
  62109. this._depthSort = options ? options.enableDepthSort : false;
  62110. this._particlesIntersect = options ? options.particleIntersection : false;
  62111. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62112. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62113. if (options && options.updatable !== undefined) {
  62114. this._updatable = options.updatable;
  62115. }
  62116. else {
  62117. this._updatable = true;
  62118. }
  62119. if (this._pickable) {
  62120. this.pickedParticles = [];
  62121. }
  62122. if (this._depthSort) {
  62123. this.depthSortedParticles = [];
  62124. }
  62125. }
  62126. /**
  62127. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62128. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62129. * @returns the created mesh
  62130. */
  62131. SolidParticleSystem.prototype.buildMesh = function () {
  62132. if (this.nbParticles === 0) {
  62133. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62134. this.addShape(triangle, 1);
  62135. triangle.dispose();
  62136. }
  62137. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62138. this._positions32 = new Float32Array(this._positions);
  62139. this._uvs32 = new Float32Array(this._uvs);
  62140. this._colors32 = new Float32Array(this._colors);
  62141. if (this.recomputeNormals) {
  62142. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62143. }
  62144. this._normals32 = new Float32Array(this._normals);
  62145. this._fixedNormal32 = new Float32Array(this._normals);
  62146. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62147. this._unrotateFixedNormals();
  62148. }
  62149. var vertexData = new BABYLON.VertexData();
  62150. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62151. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62152. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62153. if (this._uvs32.length > 0) {
  62154. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62155. }
  62156. if (this._colors32.length > 0) {
  62157. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62158. }
  62159. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62160. vertexData.applyToMesh(mesh, this._updatable);
  62161. this.mesh = mesh;
  62162. this.mesh.isPickable = this._pickable;
  62163. // free memory
  62164. if (!this._depthSort) {
  62165. this._indices = null;
  62166. }
  62167. this._positions = null;
  62168. this._normals = null;
  62169. this._uvs = null;
  62170. this._colors = null;
  62171. if (!this._updatable) {
  62172. this.particles.length = 0;
  62173. }
  62174. return mesh;
  62175. };
  62176. /**
  62177. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62178. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62179. * Thus the particles generated from `digest()` have their property `position` set yet.
  62180. * @param mesh ( Mesh ) is the mesh to be digested
  62181. * @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
  62182. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62183. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62184. * @returns the current SPS
  62185. */
  62186. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62187. var size = (options && options.facetNb) || 1;
  62188. var number = (options && options.number) || 0;
  62189. var delta = (options && options.delta) || 0;
  62190. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62191. var meshInd = mesh.getIndices();
  62192. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62193. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62194. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62195. var f = 0; // facet counter
  62196. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62197. // compute size from number
  62198. if (number) {
  62199. number = (number > totalFacets) ? totalFacets : number;
  62200. size = Math.round(totalFacets / number);
  62201. delta = 0;
  62202. }
  62203. else {
  62204. size = (size > totalFacets) ? totalFacets : size;
  62205. }
  62206. var facetPos = []; // submesh positions
  62207. var facetInd = []; // submesh indices
  62208. var facetUV = []; // submesh UV
  62209. var facetCol = []; // submesh colors
  62210. var barycenter = BABYLON.Vector3.Zero();
  62211. var sizeO = size;
  62212. while (f < totalFacets) {
  62213. size = sizeO + Math.floor((1 + delta) * Math.random());
  62214. if (f > totalFacets - size) {
  62215. size = totalFacets - f;
  62216. }
  62217. // reset temp arrays
  62218. facetPos.length = 0;
  62219. facetInd.length = 0;
  62220. facetUV.length = 0;
  62221. facetCol.length = 0;
  62222. // iterate over "size" facets
  62223. var fi = 0;
  62224. for (var j = f * 3; j < (f + size) * 3; j++) {
  62225. facetInd.push(fi);
  62226. var i = meshInd[j];
  62227. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62228. if (meshUV) {
  62229. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62230. }
  62231. if (meshCol) {
  62232. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62233. }
  62234. fi++;
  62235. }
  62236. // create a model shape for each single particle
  62237. var idx = this.nbParticles;
  62238. var shape = this._posToShape(facetPos);
  62239. var shapeUV = this._uvsToShapeUV(facetUV);
  62240. // compute the barycenter of the shape
  62241. var v;
  62242. for (v = 0; v < shape.length; v++) {
  62243. barycenter.addInPlace(shape[v]);
  62244. }
  62245. barycenter.scaleInPlace(1 / shape.length);
  62246. // shift the shape from its barycenter to the origin
  62247. for (v = 0; v < shape.length; v++) {
  62248. shape[v].subtractInPlace(barycenter);
  62249. }
  62250. var bInfo;
  62251. if (this._particlesIntersect) {
  62252. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62253. }
  62254. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62255. // add the particle in the SPS
  62256. var currentPos = this._positions.length;
  62257. var currentInd = this._indices.length;
  62258. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62259. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62260. // initialize the particle position
  62261. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62262. this._index += shape.length;
  62263. idx++;
  62264. this.nbParticles++;
  62265. this._shapeCounter++;
  62266. f += size;
  62267. }
  62268. return this;
  62269. };
  62270. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62271. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62272. var index = 0;
  62273. var idx = 0;
  62274. for (var p = 0; p < this.particles.length; p++) {
  62275. this._particle = this.particles[p];
  62276. this._shape = this._particle._model._shape;
  62277. if (this._particle.rotationQuaternion) {
  62278. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62279. }
  62280. else {
  62281. this._yaw = this._particle.rotation.y;
  62282. this._pitch = this._particle.rotation.x;
  62283. this._roll = this._particle.rotation.z;
  62284. this._quaternionRotationYPR();
  62285. }
  62286. this._quaternionToRotationMatrix();
  62287. this._rotMatrix.invertToRef(this._invertMatrix);
  62288. for (var pt = 0; pt < this._shape.length; pt++) {
  62289. idx = index + pt * 3;
  62290. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62291. this._fixedNormal32[idx] = this._normal.x;
  62292. this._fixedNormal32[idx + 1] = this._normal.y;
  62293. this._fixedNormal32[idx + 2] = this._normal.z;
  62294. }
  62295. index = idx + 3;
  62296. }
  62297. };
  62298. //reset copy
  62299. SolidParticleSystem.prototype._resetCopy = function () {
  62300. this._copy.position.x = 0;
  62301. this._copy.position.y = 0;
  62302. this._copy.position.z = 0;
  62303. this._copy.rotation.x = 0;
  62304. this._copy.rotation.y = 0;
  62305. this._copy.rotation.z = 0;
  62306. this._copy.rotationQuaternion = null;
  62307. this._copy.scaling.x = 1.0;
  62308. this._copy.scaling.y = 1.0;
  62309. this._copy.scaling.z = 1.0;
  62310. this._copy.uvs.x = 0;
  62311. this._copy.uvs.y = 0;
  62312. this._copy.uvs.z = 1.0;
  62313. this._copy.uvs.w = 1.0;
  62314. this._copy.color = null;
  62315. this._copy.translateFromPivot = false;
  62316. };
  62317. // _meshBuilder : inserts the shape model in the global SPS mesh
  62318. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62319. var i;
  62320. var u = 0;
  62321. var c = 0;
  62322. var n = 0;
  62323. this._resetCopy();
  62324. if (options && options.positionFunction) { // call to custom positionFunction
  62325. options.positionFunction(this._copy, idx, idxInShape);
  62326. this._mustUnrotateFixedNormals = true;
  62327. }
  62328. if (this._copy.rotationQuaternion) {
  62329. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62330. }
  62331. else {
  62332. this._yaw = this._copy.rotation.y;
  62333. this._pitch = this._copy.rotation.x;
  62334. this._roll = this._copy.rotation.z;
  62335. this._quaternionRotationYPR();
  62336. }
  62337. this._quaternionToRotationMatrix();
  62338. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62339. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62340. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62341. if (this._copy.translateFromPivot) {
  62342. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62343. }
  62344. else {
  62345. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62346. }
  62347. for (i = 0; i < shape.length; i++) {
  62348. this._vertex.x = shape[i].x;
  62349. this._vertex.y = shape[i].y;
  62350. this._vertex.z = shape[i].z;
  62351. if (options && options.vertexFunction) {
  62352. options.vertexFunction(this._copy, this._vertex, i);
  62353. }
  62354. this._vertex.x *= this._copy.scaling.x;
  62355. this._vertex.y *= this._copy.scaling.y;
  62356. this._vertex.z *= this._copy.scaling.z;
  62357. this._vertex.x -= this._scaledPivot.x;
  62358. this._vertex.y -= this._scaledPivot.y;
  62359. this._vertex.z -= this._scaledPivot.z;
  62360. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62361. this._rotated.addInPlace(this._pivotBackTranslation);
  62362. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62363. if (meshUV) {
  62364. 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);
  62365. u += 2;
  62366. }
  62367. if (this._copy.color) {
  62368. this._color = this._copy.color;
  62369. }
  62370. else if (meshCol && meshCol[c] !== undefined) {
  62371. this._color.r = meshCol[c];
  62372. this._color.g = meshCol[c + 1];
  62373. this._color.b = meshCol[c + 2];
  62374. this._color.a = meshCol[c + 3];
  62375. }
  62376. else {
  62377. this._color.r = 1.0;
  62378. this._color.g = 1.0;
  62379. this._color.b = 1.0;
  62380. this._color.a = 1.0;
  62381. }
  62382. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62383. c += 4;
  62384. if (!this.recomputeNormals && meshNor) {
  62385. this._normal.x = meshNor[n];
  62386. this._normal.y = meshNor[n + 1];
  62387. this._normal.z = meshNor[n + 2];
  62388. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62389. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62390. n += 3;
  62391. }
  62392. }
  62393. for (i = 0; i < meshInd.length; i++) {
  62394. var current_ind = p + meshInd[i];
  62395. indices.push(current_ind);
  62396. if (current_ind > 65535) {
  62397. this._needs32Bits = true;
  62398. }
  62399. }
  62400. if (this._pickable) {
  62401. var nbfaces = meshInd.length / 3;
  62402. for (i = 0; i < nbfaces; i++) {
  62403. this.pickedParticles.push({ idx: idx, faceId: i });
  62404. }
  62405. }
  62406. if (this._depthSort) {
  62407. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62408. }
  62409. return this._copy;
  62410. };
  62411. // returns a shape array from positions array
  62412. SolidParticleSystem.prototype._posToShape = function (positions) {
  62413. var shape = [];
  62414. for (var i = 0; i < positions.length; i += 3) {
  62415. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62416. }
  62417. return shape;
  62418. };
  62419. // returns a shapeUV array from a Vector4 uvs
  62420. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62421. var shapeUV = [];
  62422. if (uvs) {
  62423. for (var i = 0; i < uvs.length; i++)
  62424. shapeUV.push(uvs[i]);
  62425. }
  62426. return shapeUV;
  62427. };
  62428. // adds a new particle object in the particles array
  62429. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62430. if (bInfo === void 0) { bInfo = null; }
  62431. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62432. this.particles.push(sp);
  62433. return sp;
  62434. };
  62435. /**
  62436. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62437. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62438. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62439. * @param nb (positive integer) the number of particles to be created from this model
  62440. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62441. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62442. * @returns the number of shapes in the system
  62443. */
  62444. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62445. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62446. var meshInd = mesh.getIndices();
  62447. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62448. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62449. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62450. var bbInfo;
  62451. if (this._particlesIntersect) {
  62452. bbInfo = mesh.getBoundingInfo();
  62453. }
  62454. var shape = this._posToShape(meshPos);
  62455. var shapeUV = this._uvsToShapeUV(meshUV);
  62456. var posfunc = options ? options.positionFunction : null;
  62457. var vtxfunc = options ? options.vertexFunction : null;
  62458. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62459. // particles
  62460. var sp;
  62461. var currentCopy;
  62462. var idx = this.nbParticles;
  62463. for (var i = 0; i < nb; i++) {
  62464. var currentPos = this._positions.length;
  62465. var currentInd = this._indices.length;
  62466. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62467. if (this._updatable) {
  62468. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62469. sp.position.copyFrom(currentCopy.position);
  62470. sp.rotation.copyFrom(currentCopy.rotation);
  62471. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62472. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62473. }
  62474. if (currentCopy.color && sp.color) {
  62475. sp.color.copyFrom(currentCopy.color);
  62476. }
  62477. sp.scaling.copyFrom(currentCopy.scaling);
  62478. sp.uvs.copyFrom(currentCopy.uvs);
  62479. }
  62480. this._index += shape.length;
  62481. idx++;
  62482. }
  62483. this.nbParticles += nb;
  62484. this._shapeCounter++;
  62485. return this._shapeCounter - 1;
  62486. };
  62487. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62488. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62489. this._resetCopy();
  62490. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62491. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62492. }
  62493. if (this._copy.rotationQuaternion) {
  62494. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62495. }
  62496. else {
  62497. this._yaw = this._copy.rotation.y;
  62498. this._pitch = this._copy.rotation.x;
  62499. this._roll = this._copy.rotation.z;
  62500. this._quaternionRotationYPR();
  62501. }
  62502. this._quaternionToRotationMatrix();
  62503. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62504. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62505. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62506. if (this._copy.translateFromPivot) {
  62507. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62508. }
  62509. else {
  62510. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62511. }
  62512. this._shape = particle._model._shape;
  62513. for (var pt = 0; pt < this._shape.length; pt++) {
  62514. this._vertex.x = this._shape[pt].x;
  62515. this._vertex.y = this._shape[pt].y;
  62516. this._vertex.z = this._shape[pt].z;
  62517. if (particle._model._vertexFunction) {
  62518. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62519. }
  62520. this._vertex.x *= this._copy.scaling.x;
  62521. this._vertex.y *= this._copy.scaling.y;
  62522. this._vertex.z *= this._copy.scaling.z;
  62523. this._vertex.x -= this._scaledPivot.x;
  62524. this._vertex.y -= this._scaledPivot.y;
  62525. this._vertex.z -= this._scaledPivot.z;
  62526. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62527. this._rotated.addInPlace(this._pivotBackTranslation);
  62528. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62529. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62530. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62531. }
  62532. particle.position.x = 0.0;
  62533. particle.position.y = 0.0;
  62534. particle.position.z = 0.0;
  62535. particle.rotation.x = 0.0;
  62536. particle.rotation.y = 0.0;
  62537. particle.rotation.z = 0.0;
  62538. particle.rotationQuaternion = null;
  62539. particle.scaling.x = 1.0;
  62540. particle.scaling.y = 1.0;
  62541. particle.scaling.z = 1.0;
  62542. particle.uvs.x = 0.0;
  62543. particle.uvs.y = 0.0;
  62544. particle.uvs.z = 1.0;
  62545. particle.uvs.w = 1.0;
  62546. particle.pivot.x = 0.0;
  62547. particle.pivot.y = 0.0;
  62548. particle.pivot.z = 0.0;
  62549. particle.translateFromPivot = false;
  62550. particle.parentId = null;
  62551. };
  62552. /**
  62553. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62554. * @returns the SPS.
  62555. */
  62556. SolidParticleSystem.prototype.rebuildMesh = function () {
  62557. for (var p = 0; p < this.particles.length; p++) {
  62558. this._rebuildParticle(this.particles[p]);
  62559. }
  62560. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62561. return this;
  62562. };
  62563. /**
  62564. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62565. * This method calls `updateParticle()` for each particle of the SPS.
  62566. * For an animated SPS, it is usually called within the render loop.
  62567. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62568. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62569. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62570. * @returns the SPS.
  62571. */
  62572. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62573. if (start === void 0) { start = 0; }
  62574. if (end === void 0) { end = this.nbParticles - 1; }
  62575. if (update === void 0) { update = true; }
  62576. if (!this._updatable) {
  62577. return this;
  62578. }
  62579. // custom beforeUpdate
  62580. this.beforeUpdateParticles(start, end, update);
  62581. this._cam_axisX.x = 1.0;
  62582. this._cam_axisX.y = 0.0;
  62583. this._cam_axisX.z = 0.0;
  62584. this._cam_axisY.x = 0.0;
  62585. this._cam_axisY.y = 1.0;
  62586. this._cam_axisY.z = 0.0;
  62587. this._cam_axisZ.x = 0.0;
  62588. this._cam_axisZ.y = 0.0;
  62589. this._cam_axisZ.z = 1.0;
  62590. // cases when the World Matrix is to be computed first
  62591. if (this.billboard || this._depthSort) {
  62592. this.mesh.computeWorldMatrix(true);
  62593. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62594. }
  62595. // if the particles will always face the camera
  62596. if (this.billboard) {
  62597. // compute the camera position and un-rotate it by the current mesh rotation
  62598. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62599. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62600. this._cam_axisZ.normalize();
  62601. // same for camera up vector extracted from the cam view matrix
  62602. var view = this._camera.getViewMatrix(true);
  62603. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62604. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62605. this._cam_axisY.normalize();
  62606. this._cam_axisX.normalize();
  62607. }
  62608. // if depthSort, compute the camera global position in the mesh local system
  62609. if (this._depthSort) {
  62610. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62611. }
  62612. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62613. var idx = 0; // current position index in the global array positions32
  62614. var index = 0; // position start index in the global array positions32 of the current particle
  62615. var colidx = 0; // current color index in the global array colors32
  62616. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62617. var uvidx = 0; // current uv index in the global array uvs32
  62618. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62619. var pt = 0; // current index in the particle model shape
  62620. if (this.mesh.isFacetDataEnabled) {
  62621. this._computeBoundingBox = true;
  62622. }
  62623. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62624. if (this._computeBoundingBox) {
  62625. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62626. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62627. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62628. }
  62629. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62630. if (this.mesh._boundingInfo) {
  62631. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62632. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62633. }
  62634. }
  62635. }
  62636. // particle loop
  62637. index = this.particles[start]._pos;
  62638. var vpos = (index / 3) | 0;
  62639. colorIndex = vpos * 4;
  62640. uvIndex = vpos * 2;
  62641. for (var p = start; p <= end; p++) {
  62642. this._particle = this.particles[p];
  62643. this._shape = this._particle._model._shape;
  62644. this._shapeUV = this._particle._model._shapeUV;
  62645. // call to custom user function to update the particle properties
  62646. this.updateParticle(this._particle);
  62647. // camera-particle distance for depth sorting
  62648. if (this._depthSort && this._depthSortParticles) {
  62649. var dsp = this.depthSortedParticles[p];
  62650. dsp.ind = this._particle._ind;
  62651. dsp.indicesLength = this._particle._model._indicesLength;
  62652. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62653. }
  62654. // skip the computations for inactive or already invisible particles
  62655. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62656. // increment indexes for the next particle
  62657. pt = this._shape.length;
  62658. index += pt * 3;
  62659. colorIndex += pt * 4;
  62660. uvIndex += pt * 2;
  62661. continue;
  62662. }
  62663. if (this._particle.isVisible) {
  62664. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62665. this._particleHasParent = (this._particle.parentId !== null);
  62666. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62667. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62668. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62669. // particle rotation matrix
  62670. if (this.billboard) {
  62671. this._particle.rotation.x = 0.0;
  62672. this._particle.rotation.y = 0.0;
  62673. }
  62674. if (this._computeParticleRotation || this.billboard) {
  62675. if (this._particle.rotationQuaternion) {
  62676. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62677. }
  62678. else {
  62679. this._yaw = this._particle.rotation.y;
  62680. this._pitch = this._particle.rotation.x;
  62681. this._roll = this._particle.rotation.z;
  62682. this._quaternionRotationYPR();
  62683. }
  62684. this._quaternionToRotationMatrix();
  62685. }
  62686. if (this._particleHasParent) {
  62687. this._parent = this.particles[this._particle.parentId];
  62688. 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];
  62689. 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];
  62690. 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];
  62691. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62692. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62693. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62694. if (this._computeParticleRotation || this.billboard) {
  62695. 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];
  62696. 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];
  62697. 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];
  62698. 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];
  62699. 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];
  62700. 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];
  62701. 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];
  62702. 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];
  62703. 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];
  62704. }
  62705. }
  62706. else {
  62707. this._particle._globalPosition.x = this._particle.position.x;
  62708. this._particle._globalPosition.y = this._particle.position.y;
  62709. this._particle._globalPosition.z = this._particle.position.z;
  62710. if (this._computeParticleRotation || this.billboard) {
  62711. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62712. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62713. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62714. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62715. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62716. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62717. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62718. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62719. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62720. }
  62721. }
  62722. if (this._particle.translateFromPivot) {
  62723. this._pivotBackTranslation.x = 0.0;
  62724. this._pivotBackTranslation.y = 0.0;
  62725. this._pivotBackTranslation.z = 0.0;
  62726. }
  62727. else {
  62728. this._pivotBackTranslation.x = this._scaledPivot.x;
  62729. this._pivotBackTranslation.y = this._scaledPivot.y;
  62730. this._pivotBackTranslation.z = this._scaledPivot.z;
  62731. }
  62732. // particle vertex loop
  62733. for (pt = 0; pt < this._shape.length; pt++) {
  62734. idx = index + pt * 3;
  62735. colidx = colorIndex + pt * 4;
  62736. uvidx = uvIndex + pt * 2;
  62737. this._vertex.x = this._shape[pt].x;
  62738. this._vertex.y = this._shape[pt].y;
  62739. this._vertex.z = this._shape[pt].z;
  62740. if (this._computeParticleVertex) {
  62741. this.updateParticleVertex(this._particle, this._vertex, pt);
  62742. }
  62743. // positions
  62744. this._vertex.x *= this._particle.scaling.x;
  62745. this._vertex.y *= this._particle.scaling.y;
  62746. this._vertex.z *= this._particle.scaling.z;
  62747. this._vertex.x -= this._scaledPivot.x;
  62748. this._vertex.y -= this._scaledPivot.y;
  62749. this._vertex.z -= this._scaledPivot.z;
  62750. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62751. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62752. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62753. this._rotated.x += this._pivotBackTranslation.x;
  62754. this._rotated.y += this._pivotBackTranslation.y;
  62755. this._rotated.z += this._pivotBackTranslation.z;
  62756. 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;
  62757. 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;
  62758. 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;
  62759. if (this._computeBoundingBox) {
  62760. if (this._positions32[idx] < this._minimum.x) {
  62761. this._minimum.x = this._positions32[idx];
  62762. }
  62763. if (this._positions32[idx] > this._maximum.x) {
  62764. this._maximum.x = this._positions32[idx];
  62765. }
  62766. if (this._positions32[idx + 1] < this._minimum.y) {
  62767. this._minimum.y = this._positions32[idx + 1];
  62768. }
  62769. if (this._positions32[idx + 1] > this._maximum.y) {
  62770. this._maximum.y = this._positions32[idx + 1];
  62771. }
  62772. if (this._positions32[idx + 2] < this._minimum.z) {
  62773. this._minimum.z = this._positions32[idx + 2];
  62774. }
  62775. if (this._positions32[idx + 2] > this._maximum.z) {
  62776. this._maximum.z = this._positions32[idx + 2];
  62777. }
  62778. }
  62779. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62780. if (!this._computeParticleVertex) {
  62781. this._normal.x = this._fixedNormal32[idx];
  62782. this._normal.y = this._fixedNormal32[idx + 1];
  62783. this._normal.z = this._fixedNormal32[idx + 2];
  62784. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62785. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62786. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62787. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62788. 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;
  62789. 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;
  62790. }
  62791. if (this._computeParticleColor && this._particle.color) {
  62792. this._colors32[colidx] = this._particle.color.r;
  62793. this._colors32[colidx + 1] = this._particle.color.g;
  62794. this._colors32[colidx + 2] = this._particle.color.b;
  62795. this._colors32[colidx + 3] = this._particle.color.a;
  62796. }
  62797. if (this._computeParticleTexture) {
  62798. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62799. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62800. }
  62801. }
  62802. }
  62803. // particle just set invisible : scaled to zero and positioned at the origin
  62804. else {
  62805. this._particle._stillInvisible = true; // mark the particle as invisible
  62806. for (pt = 0; pt < this._shape.length; pt++) {
  62807. idx = index + pt * 3;
  62808. colidx = colorIndex + pt * 4;
  62809. uvidx = uvIndex + pt * 2;
  62810. this._positions32[idx] = 0.0;
  62811. this._positions32[idx + 1] = 0.0;
  62812. this._positions32[idx + 2] = 0.0;
  62813. this._normals32[idx] = 0.0;
  62814. this._normals32[idx + 1] = 0.0;
  62815. this._normals32[idx + 2] = 0.0;
  62816. if (this._computeParticleColor && this._particle.color) {
  62817. this._colors32[colidx] = this._particle.color.r;
  62818. this._colors32[colidx + 1] = this._particle.color.g;
  62819. this._colors32[colidx + 2] = this._particle.color.b;
  62820. this._colors32[colidx + 3] = this._particle.color.a;
  62821. }
  62822. if (this._computeParticleTexture) {
  62823. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62824. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62825. }
  62826. }
  62827. }
  62828. // if the particle intersections must be computed : update the bbInfo
  62829. if (this._particlesIntersect) {
  62830. var bInfo = this._particle._boundingInfo;
  62831. var bBox = bInfo.boundingBox;
  62832. var bSphere = bInfo.boundingSphere;
  62833. if (!this._bSphereOnly) {
  62834. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62835. for (var b = 0; b < bBox.vectors.length; b++) {
  62836. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62837. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62838. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62839. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62840. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62841. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62842. 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;
  62843. 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;
  62844. 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;
  62845. }
  62846. bBox._update(this.mesh._worldMatrix);
  62847. }
  62848. // place and scale the particle bouding sphere in the SPS local system, then update it
  62849. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62850. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62851. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62852. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62853. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62854. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62855. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62856. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62857. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62858. 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));
  62859. bSphere._update(this.mesh._worldMatrix);
  62860. }
  62861. // increment indexes for the next particle
  62862. index = idx + 3;
  62863. colorIndex = colidx + 4;
  62864. uvIndex = uvidx + 2;
  62865. }
  62866. // if the VBO must be updated
  62867. if (update) {
  62868. if (this._computeParticleColor) {
  62869. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62870. }
  62871. if (this._computeParticleTexture) {
  62872. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62873. }
  62874. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62875. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62876. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62877. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62878. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62879. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62880. for (var i = 0; i < this._normals32.length; i++) {
  62881. this._fixedNormal32[i] = this._normals32[i];
  62882. }
  62883. }
  62884. if (!this.mesh.areNormalsFrozen) {
  62885. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62886. }
  62887. }
  62888. if (this._depthSort && this._depthSortParticles) {
  62889. this.depthSortedParticles.sort(this._depthSortFunction);
  62890. var dspl = this.depthSortedParticles.length;
  62891. var sorted = 0;
  62892. var lind = 0;
  62893. var sind = 0;
  62894. var sid = 0;
  62895. for (sorted = 0; sorted < dspl; sorted++) {
  62896. lind = this.depthSortedParticles[sorted].indicesLength;
  62897. sind = this.depthSortedParticles[sorted].ind;
  62898. for (var i = 0; i < lind; i++) {
  62899. this._indices32[sid] = this._indices[sind + i];
  62900. sid++;
  62901. }
  62902. }
  62903. this.mesh.updateIndices(this._indices32);
  62904. }
  62905. }
  62906. if (this._computeBoundingBox) {
  62907. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62908. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62909. }
  62910. this.afterUpdateParticles(start, end, update);
  62911. return this;
  62912. };
  62913. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62914. this._halfroll = this._roll * 0.5;
  62915. this._halfpitch = this._pitch * 0.5;
  62916. this._halfyaw = this._yaw * 0.5;
  62917. this._sinRoll = Math.sin(this._halfroll);
  62918. this._cosRoll = Math.cos(this._halfroll);
  62919. this._sinPitch = Math.sin(this._halfpitch);
  62920. this._cosPitch = Math.cos(this._halfpitch);
  62921. this._sinYaw = Math.sin(this._halfyaw);
  62922. this._cosYaw = Math.cos(this._halfyaw);
  62923. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62924. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62925. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62926. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62927. };
  62928. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62929. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62930. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62931. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62932. this._rotMatrix.m[3] = 0;
  62933. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62934. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62935. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62936. this._rotMatrix.m[7] = 0;
  62937. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62938. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62939. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62940. this._rotMatrix.m[11] = 0;
  62941. this._rotMatrix.m[12] = 0;
  62942. this._rotMatrix.m[13] = 0;
  62943. this._rotMatrix.m[14] = 0;
  62944. this._rotMatrix.m[15] = 1.0;
  62945. };
  62946. /**
  62947. * Disposes the SPS.
  62948. */
  62949. SolidParticleSystem.prototype.dispose = function () {
  62950. this.mesh.dispose();
  62951. this.vars = null;
  62952. // drop references to internal big arrays for the GC
  62953. this._positions = null;
  62954. this._indices = null;
  62955. this._normals = null;
  62956. this._uvs = null;
  62957. this._colors = null;
  62958. this._indices32 = null;
  62959. this._positions32 = null;
  62960. this._normals32 = null;
  62961. this._fixedNormal32 = null;
  62962. this._uvs32 = null;
  62963. this._colors32 = null;
  62964. this.pickedParticles = null;
  62965. };
  62966. /**
  62967. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62968. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62969. * @returns the SPS.
  62970. */
  62971. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62972. if (!this._isVisibilityBoxLocked) {
  62973. this.mesh.refreshBoundingInfo();
  62974. }
  62975. return this;
  62976. };
  62977. /**
  62978. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62979. * @param size the size (float) of the visibility box
  62980. * note : this doesn't lock the SPS mesh bounding box.
  62981. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62982. */
  62983. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62984. var vis = size / 2;
  62985. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62986. };
  62987. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62988. /**
  62989. * Gets whether the SPS as always visible or not
  62990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62991. */
  62992. get: function () {
  62993. return this._alwaysVisible;
  62994. },
  62995. /**
  62996. * Sets the SPS as always visible or not
  62997. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62998. */
  62999. set: function (val) {
  63000. this._alwaysVisible = val;
  63001. this.mesh.alwaysSelectAsActiveMesh = val;
  63002. },
  63003. enumerable: true,
  63004. configurable: true
  63005. });
  63006. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63007. /**
  63008. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63009. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63010. */
  63011. get: function () {
  63012. return this._isVisibilityBoxLocked;
  63013. },
  63014. /**
  63015. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63016. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63017. */
  63018. set: function (val) {
  63019. this._isVisibilityBoxLocked = val;
  63020. var boundingInfo = this.mesh.getBoundingInfo();
  63021. boundingInfo.isLocked = val;
  63022. },
  63023. enumerable: true,
  63024. configurable: true
  63025. });
  63026. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63027. /**
  63028. * Gets if `setParticles()` computes the particle rotations or not.
  63029. * Default value : true. The SPS is faster when it's set to false.
  63030. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63031. */
  63032. get: function () {
  63033. return this._computeParticleRotation;
  63034. },
  63035. /**
  63036. * Tells to `setParticles()` to compute the particle rotations or not.
  63037. * Default value : true. The SPS is faster when it's set to false.
  63038. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63039. */
  63040. set: function (val) {
  63041. this._computeParticleRotation = val;
  63042. },
  63043. enumerable: true,
  63044. configurable: true
  63045. });
  63046. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63047. /**
  63048. * Gets if `setParticles()` computes the particle colors or not.
  63049. * Default value : true. The SPS is faster when it's set to false.
  63050. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63051. */
  63052. get: function () {
  63053. return this._computeParticleColor;
  63054. },
  63055. /**
  63056. * Tells to `setParticles()` to compute the particle colors or not.
  63057. * Default value : true. The SPS is faster when it's set to false.
  63058. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63059. */
  63060. set: function (val) {
  63061. this._computeParticleColor = val;
  63062. },
  63063. enumerable: true,
  63064. configurable: true
  63065. });
  63066. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63067. /**
  63068. * Gets if `setParticles()` computes the particle textures or not.
  63069. * Default value : true. The SPS is faster when it's set to false.
  63070. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63071. */
  63072. get: function () {
  63073. return this._computeParticleTexture;
  63074. },
  63075. set: function (val) {
  63076. this._computeParticleTexture = val;
  63077. },
  63078. enumerable: true,
  63079. configurable: true
  63080. });
  63081. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63082. /**
  63083. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63084. * Default value : false. The SPS is faster when it's set to false.
  63085. * Note : the particle custom vertex positions aren't stored values.
  63086. */
  63087. get: function () {
  63088. return this._computeParticleVertex;
  63089. },
  63090. /**
  63091. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63092. * Default value : false. The SPS is faster when it's set to false.
  63093. * Note : the particle custom vertex positions aren't stored values.
  63094. */
  63095. set: function (val) {
  63096. this._computeParticleVertex = val;
  63097. },
  63098. enumerable: true,
  63099. configurable: true
  63100. });
  63101. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63102. /**
  63103. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63104. */
  63105. get: function () {
  63106. return this._computeBoundingBox;
  63107. },
  63108. /**
  63109. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63110. */
  63111. set: function (val) {
  63112. this._computeBoundingBox = val;
  63113. },
  63114. enumerable: true,
  63115. configurable: true
  63116. });
  63117. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63118. /**
  63119. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63120. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63121. * Default : `true`
  63122. */
  63123. get: function () {
  63124. return this._depthSortParticles;
  63125. },
  63126. /**
  63127. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63128. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63129. * Default : `true`
  63130. */
  63131. set: function (val) {
  63132. this._depthSortParticles = val;
  63133. },
  63134. enumerable: true,
  63135. configurable: true
  63136. });
  63137. // =======================================================================
  63138. // Particle behavior logic
  63139. // these following methods may be overwritten by the user to fit his needs
  63140. /**
  63141. * This function does nothing. It may be overwritten to set all the particle first values.
  63142. * The SPS doesn't call this function, you may have to call it by your own.
  63143. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63144. */
  63145. SolidParticleSystem.prototype.initParticles = function () {
  63146. };
  63147. /**
  63148. * This function does nothing. It may be overwritten to recycle a particle.
  63149. * The SPS doesn't call this function, you may have to call it by your own.
  63150. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63151. * @param particle The particle to recycle
  63152. * @returns the recycled particle
  63153. */
  63154. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63155. return particle;
  63156. };
  63157. /**
  63158. * Updates a particle : this function should be overwritten by the user.
  63159. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63160. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63161. * @example : just set a particle position or velocity and recycle conditions
  63162. * @param particle The particle to update
  63163. * @returns the updated particle
  63164. */
  63165. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63166. return particle;
  63167. };
  63168. /**
  63169. * Updates a vertex of a particle : it can be overwritten by the user.
  63170. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63171. * @param particle the current particle
  63172. * @param vertex the current index of the current particle
  63173. * @param pt the index of the current vertex in the particle shape
  63174. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63175. * @example : just set a vertex particle position
  63176. * @returns the updated vertex
  63177. */
  63178. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63179. return vertex;
  63180. };
  63181. /**
  63182. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63183. * This does nothing and may be overwritten by the user.
  63184. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63185. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63186. * @param update the boolean update value actually passed to setParticles()
  63187. */
  63188. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63189. };
  63190. /**
  63191. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63192. * This will be passed three parameters.
  63193. * This does nothing and may be overwritten by the user.
  63194. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63195. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63196. * @param update the boolean update value actually passed to setParticles()
  63197. */
  63198. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63199. };
  63200. return SolidParticleSystem;
  63201. }());
  63202. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63203. })(BABYLON || (BABYLON = {}));
  63204. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63205. var BABYLON;
  63206. (function (BABYLON) {
  63207. /**
  63208. * Class containing static functions to help procedurally build meshes
  63209. */
  63210. var MeshBuilder = /** @class */ (function () {
  63211. function MeshBuilder() {
  63212. }
  63213. MeshBuilder.updateSideOrientation = function (orientation) {
  63214. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63215. return BABYLON.Mesh.DOUBLESIDE;
  63216. }
  63217. if (orientation === undefined || orientation === null) {
  63218. return BABYLON.Mesh.FRONTSIDE;
  63219. }
  63220. return orientation;
  63221. };
  63222. /**
  63223. * Creates a box mesh
  63224. * * The parameter `size` sets the size (float) of each box side (default 1)
  63225. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63226. * * 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)
  63227. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63228. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63229. * * 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
  63230. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63231. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63232. * @param name defines the name of the mesh
  63233. * @param options defines the options used to create the mesh
  63234. * @param scene defines the hosting scene
  63235. * @returns the box mesh
  63236. */
  63237. MeshBuilder.CreateBox = function (name, options, scene) {
  63238. if (scene === void 0) { scene = null; }
  63239. var box = new BABYLON.Mesh(name, scene);
  63240. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63241. box._originalBuilderSideOrientation = options.sideOrientation;
  63242. var vertexData = BABYLON.VertexData.CreateBox(options);
  63243. vertexData.applyToMesh(box, options.updatable);
  63244. return box;
  63245. };
  63246. /**
  63247. * Creates a sphere mesh
  63248. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63249. * * 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`)
  63250. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63251. * * 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
  63252. * * 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)
  63253. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63254. * * 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
  63255. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63256. * @param name defines the name of the mesh
  63257. * @param options defines the options used to create the mesh
  63258. * @param scene defines the hosting scene
  63259. * @returns the sphere mesh
  63260. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63261. */
  63262. MeshBuilder.CreateSphere = function (name, options, scene) {
  63263. var sphere = new BABYLON.Mesh(name, scene);
  63264. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63265. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63266. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63267. vertexData.applyToMesh(sphere, options.updatable);
  63268. return sphere;
  63269. };
  63270. /**
  63271. * Creates a plane polygonal mesh. By default, this is a disc
  63272. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63273. * * 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
  63274. * * 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
  63275. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63276. * * 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
  63277. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63278. * @param name defines the name of the mesh
  63279. * @param options defines the options used to create the mesh
  63280. * @param scene defines the hosting scene
  63281. * @returns the plane polygonal mesh
  63282. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63283. */
  63284. MeshBuilder.CreateDisc = function (name, options, scene) {
  63285. if (scene === void 0) { scene = null; }
  63286. var disc = new BABYLON.Mesh(name, scene);
  63287. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63288. disc._originalBuilderSideOrientation = options.sideOrientation;
  63289. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63290. vertexData.applyToMesh(disc, options.updatable);
  63291. return disc;
  63292. };
  63293. /**
  63294. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63295. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63296. * * 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`)
  63297. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63298. * * 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
  63299. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63300. * * 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
  63301. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63302. * @param name defines the name of the mesh
  63303. * @param options defines the options used to create the mesh
  63304. * @param scene defines the hosting scene
  63305. * @returns the icosahedron mesh
  63306. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63307. */
  63308. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63309. var sphere = new BABYLON.Mesh(name, scene);
  63310. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63311. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63312. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63313. vertexData.applyToMesh(sphere, options.updatable);
  63314. return sphere;
  63315. };
  63316. ;
  63317. /**
  63318. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63319. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63320. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63321. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63322. * * 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
  63323. * * 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
  63324. * * 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
  63325. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63326. * * 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
  63327. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63328. * * 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
  63329. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63330. * * 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
  63331. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63332. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63333. * @param name defines the name of the mesh
  63334. * @param options defines the options used to create the mesh
  63335. * @param scene defines the hosting scene
  63336. * @returns the ribbon mesh
  63337. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63338. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63339. */
  63340. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63341. if (scene === void 0) { scene = null; }
  63342. var pathArray = options.pathArray;
  63343. var closeArray = options.closeArray;
  63344. var closePath = options.closePath;
  63345. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63346. var instance = options.instance;
  63347. var updatable = options.updatable;
  63348. if (instance) { // existing ribbon instance update
  63349. // positionFunction : ribbon case
  63350. // only pathArray and sideOrientation parameters are taken into account for positions update
  63351. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63352. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63353. var positionFunction = function (positions) {
  63354. var minlg = pathArray[0].length;
  63355. var i = 0;
  63356. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63357. for (var si = 1; si <= ns; si++) {
  63358. for (var p = 0; p < pathArray.length; p++) {
  63359. var path = pathArray[p];
  63360. var l = path.length;
  63361. minlg = (minlg < l) ? minlg : l;
  63362. var j = 0;
  63363. while (j < minlg) {
  63364. positions[i] = path[j].x;
  63365. positions[i + 1] = path[j].y;
  63366. positions[i + 2] = path[j].z;
  63367. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63368. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63369. }
  63370. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63371. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63372. }
  63373. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63374. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63375. }
  63376. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63377. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63378. }
  63379. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63380. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63381. }
  63382. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63383. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63384. }
  63385. j++;
  63386. i += 3;
  63387. }
  63388. if (instance._closePath) {
  63389. positions[i] = path[0].x;
  63390. positions[i + 1] = path[0].y;
  63391. positions[i + 2] = path[0].z;
  63392. i += 3;
  63393. }
  63394. }
  63395. }
  63396. };
  63397. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63398. positionFunction(positions);
  63399. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63400. instance._boundingInfo.update(instance._worldMatrix);
  63401. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63402. if (options.colors) {
  63403. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63404. for (var c = 0; c < options.colors.length; c++) {
  63405. colors[c * 4] = options.colors[c].r;
  63406. colors[c * 4 + 1] = options.colors[c].g;
  63407. colors[c * 4 + 2] = options.colors[c].b;
  63408. colors[c * 4 + 3] = options.colors[c].a;
  63409. }
  63410. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63411. }
  63412. if (options.uvs) {
  63413. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63414. for (var i = 0; i < options.uvs.length; i++) {
  63415. uvs[i * 2] = options.uvs[i].x;
  63416. uvs[i * 2 + 1] = options.uvs[i].y;
  63417. }
  63418. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63419. }
  63420. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63421. var indices = instance.getIndices();
  63422. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63423. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63424. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63425. if (instance._closePath) {
  63426. var indexFirst = 0;
  63427. var indexLast = 0;
  63428. for (var p = 0; p < pathArray.length; p++) {
  63429. indexFirst = instance._idx[p] * 3;
  63430. if (p + 1 < pathArray.length) {
  63431. indexLast = (instance._idx[p + 1] - 1) * 3;
  63432. }
  63433. else {
  63434. indexLast = normals.length - 3;
  63435. }
  63436. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63437. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63438. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63439. normals[indexLast] = normals[indexFirst];
  63440. normals[indexLast + 1] = normals[indexFirst + 1];
  63441. normals[indexLast + 2] = normals[indexFirst + 2];
  63442. }
  63443. }
  63444. if (!(instance.areNormalsFrozen)) {
  63445. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63446. }
  63447. }
  63448. return instance;
  63449. }
  63450. else { // new ribbon creation
  63451. var ribbon = new BABYLON.Mesh(name, scene);
  63452. ribbon._originalBuilderSideOrientation = sideOrientation;
  63453. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63454. if (closePath) {
  63455. ribbon._idx = vertexData._idx;
  63456. }
  63457. ribbon._closePath = closePath;
  63458. ribbon._closeArray = closeArray;
  63459. vertexData.applyToMesh(ribbon, updatable);
  63460. return ribbon;
  63461. }
  63462. };
  63463. /**
  63464. * Creates a cylinder or a cone mesh
  63465. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63466. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63467. * * 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.
  63468. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63469. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63470. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63471. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63472. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63473. * * 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).
  63474. * * 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
  63475. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63476. * * 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
  63477. * * 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.
  63478. * * If `enclose` is false, a ring surface is one element.
  63479. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63480. * * 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
  63481. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63482. * * 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
  63483. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63484. * @param name defines the name of the mesh
  63485. * @param options defines the options used to create the mesh
  63486. * @param scene defines the hosting scene
  63487. * @returns the cylinder mesh
  63488. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63489. */
  63490. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63491. var cylinder = new BABYLON.Mesh(name, scene);
  63492. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63493. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63494. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63495. vertexData.applyToMesh(cylinder, options.updatable);
  63496. return cylinder;
  63497. };
  63498. /**
  63499. * Creates a torus mesh
  63500. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63501. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63502. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63503. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63504. * * 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
  63505. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63506. * @param name defines the name of the mesh
  63507. * @param options defines the options used to create the mesh
  63508. * @param scene defines the hosting scene
  63509. * @returns the torus mesh
  63510. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63511. */
  63512. MeshBuilder.CreateTorus = function (name, options, scene) {
  63513. var torus = new BABYLON.Mesh(name, scene);
  63514. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63515. torus._originalBuilderSideOrientation = options.sideOrientation;
  63516. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63517. vertexData.applyToMesh(torus, options.updatable);
  63518. return torus;
  63519. };
  63520. /**
  63521. * Creates a torus knot mesh
  63522. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63523. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63524. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63525. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63526. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63527. * * 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
  63528. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63529. * @param name defines the name of the mesh
  63530. * @param options defines the options used to create the mesh
  63531. * @param scene defines the hosting scene
  63532. * @returns the torus knot mesh
  63533. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63534. */
  63535. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63536. var torusKnot = new BABYLON.Mesh(name, scene);
  63537. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63538. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63539. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63540. vertexData.applyToMesh(torusKnot, options.updatable);
  63541. return torusKnot;
  63542. };
  63543. /**
  63544. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63545. * * 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
  63546. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63547. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63548. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63549. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63550. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63551. * * 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
  63552. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63553. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63554. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63555. * @param name defines the name of the new line system
  63556. * @param options defines the options used to create the line system
  63557. * @param scene defines the hosting scene
  63558. * @returns a new line system mesh
  63559. */
  63560. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63561. var instance = options.instance;
  63562. var lines = options.lines;
  63563. var colors = options.colors;
  63564. if (instance) { // lines update
  63565. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63566. var vertexColor;
  63567. var lineColors;
  63568. if (colors) {
  63569. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63570. }
  63571. var i = 0;
  63572. var c = 0;
  63573. for (var l = 0; l < lines.length; l++) {
  63574. var points = lines[l];
  63575. for (var p = 0; p < points.length; p++) {
  63576. positions[i] = points[p].x;
  63577. positions[i + 1] = points[p].y;
  63578. positions[i + 2] = points[p].z;
  63579. if (colors && vertexColor) {
  63580. lineColors = colors[l];
  63581. vertexColor[c] = lineColors[p].r;
  63582. vertexColor[c + 1] = lineColors[p].g;
  63583. vertexColor[c + 2] = lineColors[p].b;
  63584. vertexColor[c + 3] = lineColors[p].a;
  63585. c += 4;
  63586. }
  63587. i += 3;
  63588. }
  63589. }
  63590. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63591. if (colors && vertexColor) {
  63592. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63593. }
  63594. return instance;
  63595. }
  63596. // line system creation
  63597. var useVertexColor = (colors) ? true : false;
  63598. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63599. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63600. vertexData.applyToMesh(lineSystem, options.updatable);
  63601. return lineSystem;
  63602. };
  63603. /**
  63604. * Creates a line mesh
  63605. * 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
  63606. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63607. * * The parameter `points` is an array successive Vector3
  63608. * * 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
  63609. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63610. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63611. * * When updating an instance, remember that only point positions can change, not the number of points
  63612. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63613. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63614. * @param name defines the name of the new line system
  63615. * @param options defines the options used to create the line system
  63616. * @param scene defines the hosting scene
  63617. * @returns a new line mesh
  63618. */
  63619. MeshBuilder.CreateLines = function (name, options, scene) {
  63620. if (scene === void 0) { scene = null; }
  63621. var colors = (options.colors) ? [options.colors] : null;
  63622. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63623. return lines;
  63624. };
  63625. /**
  63626. * Creates a dashed line mesh
  63627. * * 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
  63628. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63629. * * The parameter `points` is an array successive Vector3
  63630. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63631. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63632. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63633. * * 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
  63634. * * When updating an instance, remember that only point positions can change, not the number of points
  63635. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63636. * @param name defines the name of the mesh
  63637. * @param options defines the options used to create the mesh
  63638. * @param scene defines the hosting scene
  63639. * @returns the dashed line mesh
  63640. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63641. */
  63642. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63643. if (scene === void 0) { scene = null; }
  63644. var points = options.points;
  63645. var instance = options.instance;
  63646. var gapSize = options.gapSize || 1;
  63647. var dashSize = options.dashSize || 3;
  63648. if (instance) { // dashed lines update
  63649. var positionFunction = function (positions) {
  63650. var curvect = BABYLON.Vector3.Zero();
  63651. var nbSeg = positions.length / 6;
  63652. var lg = 0;
  63653. var nb = 0;
  63654. var shft = 0;
  63655. var dashshft = 0;
  63656. var curshft = 0;
  63657. var p = 0;
  63658. var i = 0;
  63659. var j = 0;
  63660. for (i = 0; i < points.length - 1; i++) {
  63661. points[i + 1].subtractToRef(points[i], curvect);
  63662. lg += curvect.length();
  63663. }
  63664. shft = lg / nbSeg;
  63665. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63666. for (i = 0; i < points.length - 1; i++) {
  63667. points[i + 1].subtractToRef(points[i], curvect);
  63668. nb = Math.floor(curvect.length() / shft);
  63669. curvect.normalize();
  63670. j = 0;
  63671. while (j < nb && p < positions.length) {
  63672. curshft = shft * j;
  63673. positions[p] = points[i].x + curshft * curvect.x;
  63674. positions[p + 1] = points[i].y + curshft * curvect.y;
  63675. positions[p + 2] = points[i].z + curshft * curvect.z;
  63676. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63677. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63678. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63679. p += 6;
  63680. j++;
  63681. }
  63682. }
  63683. while (p < positions.length) {
  63684. positions[p] = points[i].x;
  63685. positions[p + 1] = points[i].y;
  63686. positions[p + 2] = points[i].z;
  63687. p += 3;
  63688. }
  63689. };
  63690. instance.updateMeshPositions(positionFunction, false);
  63691. return instance;
  63692. }
  63693. // dashed lines creation
  63694. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63695. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63696. vertexData.applyToMesh(dashedLines, options.updatable);
  63697. dashedLines.dashSize = dashSize;
  63698. dashedLines.gapSize = gapSize;
  63699. return dashedLines;
  63700. };
  63701. /**
  63702. * 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.
  63703. * * 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.
  63704. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63705. * * 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.
  63706. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63707. * * 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
  63708. * * 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
  63709. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63710. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63711. * * 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
  63712. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63713. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63714. * @param name defines the name of the mesh
  63715. * @param options defines the options used to create the mesh
  63716. * @param scene defines the hosting scene
  63717. * @returns the extruded shape mesh
  63718. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63719. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63720. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63721. */
  63722. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63723. if (scene === void 0) { scene = null; }
  63724. var path = options.path;
  63725. var shape = options.shape;
  63726. var scale = options.scale || 1;
  63727. var rotation = options.rotation || 0;
  63728. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63729. var updatable = options.updatable;
  63730. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63731. var instance = options.instance || null;
  63732. var invertUV = options.invertUV || false;
  63733. 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);
  63734. };
  63735. /**
  63736. * Creates an custom extruded shape mesh.
  63737. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63738. * * 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.
  63739. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63740. * * 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
  63741. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63742. * * 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
  63743. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63744. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63745. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63746. * * 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
  63747. * * 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
  63748. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63749. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63750. * * 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
  63751. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63752. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63753. * @param name defines the name of the mesh
  63754. * @param options defines the options used to create the mesh
  63755. * @param scene defines the hosting scene
  63756. * @returns the custom extruded shape mesh
  63757. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63758. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63759. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63760. */
  63761. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63762. var path = options.path;
  63763. var shape = options.shape;
  63764. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63765. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63766. var ribbonCloseArray = options.ribbonCloseArray || false;
  63767. var ribbonClosePath = options.ribbonClosePath || false;
  63768. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63769. var updatable = options.updatable;
  63770. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63771. var instance = options.instance;
  63772. var invertUV = options.invertUV || false;
  63773. 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);
  63774. };
  63775. /**
  63776. * Creates lathe mesh.
  63777. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63778. * * 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
  63779. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63780. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63781. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63782. * * 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
  63783. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63784. * * 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
  63785. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63786. * * 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
  63787. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63788. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63789. * @param name defines the name of the mesh
  63790. * @param options defines the options used to create the mesh
  63791. * @param scene defines the hosting scene
  63792. * @returns the lathe mesh
  63793. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63794. */
  63795. MeshBuilder.CreateLathe = function (name, options, scene) {
  63796. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63797. var closed = (options.closed === undefined) ? true : options.closed;
  63798. var shape = options.shape;
  63799. var radius = options.radius || 1;
  63800. var tessellation = options.tessellation || 64;
  63801. var clip = options.clip || 0;
  63802. var updatable = options.updatable;
  63803. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63804. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63805. var pi2 = Math.PI * 2;
  63806. var paths = new Array();
  63807. var invertUV = options.invertUV || false;
  63808. var i = 0;
  63809. var p = 0;
  63810. var step = pi2 / tessellation * arc;
  63811. var rotated;
  63812. var path = new Array();
  63813. for (i = 0; i <= tessellation - clip; i++) {
  63814. var path = [];
  63815. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63816. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63817. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63818. }
  63819. for (p = 0; p < shape.length; p++) {
  63820. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63821. path.push(rotated);
  63822. }
  63823. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63824. 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));
  63825. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63826. }
  63827. paths.push(path);
  63828. }
  63829. // lathe ribbon
  63830. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63831. return lathe;
  63832. };
  63833. /**
  63834. * Creates a plane mesh
  63835. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63836. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63837. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63838. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63839. * * 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
  63840. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63841. * @param name defines the name of the mesh
  63842. * @param options defines the options used to create the mesh
  63843. * @param scene defines the hosting scene
  63844. * @returns the plane mesh
  63845. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63846. */
  63847. MeshBuilder.CreatePlane = function (name, options, scene) {
  63848. var plane = new BABYLON.Mesh(name, scene);
  63849. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63850. plane._originalBuilderSideOrientation = options.sideOrientation;
  63851. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63852. vertexData.applyToMesh(plane, options.updatable);
  63853. if (options.sourcePlane) {
  63854. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63855. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63856. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63857. plane.rotate(vectorProduct, product);
  63858. }
  63859. return plane;
  63860. };
  63861. /**
  63862. * Creates a ground mesh
  63863. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63864. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63865. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63866. * @param name defines the name of the mesh
  63867. * @param options defines the options used to create the mesh
  63868. * @param scene defines the hosting scene
  63869. * @returns the ground mesh
  63870. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63871. */
  63872. MeshBuilder.CreateGround = function (name, options, scene) {
  63873. var ground = new BABYLON.GroundMesh(name, scene);
  63874. ground._setReady(false);
  63875. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63876. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63877. ground._width = options.width || 1;
  63878. ground._height = options.height || 1;
  63879. ground._maxX = ground._width / 2;
  63880. ground._maxZ = ground._height / 2;
  63881. ground._minX = -ground._maxX;
  63882. ground._minZ = -ground._maxZ;
  63883. var vertexData = BABYLON.VertexData.CreateGround(options);
  63884. vertexData.applyToMesh(ground, options.updatable);
  63885. ground._setReady(true);
  63886. return ground;
  63887. };
  63888. /**
  63889. * Creates a tiled ground mesh
  63890. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63891. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63892. * * 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
  63893. * * 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
  63894. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63895. * @param name defines the name of the mesh
  63896. * @param options defines the options used to create the mesh
  63897. * @param scene defines the hosting scene
  63898. * @returns the tiled ground mesh
  63899. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63900. */
  63901. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63902. var tiledGround = new BABYLON.Mesh(name, scene);
  63903. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63904. vertexData.applyToMesh(tiledGround, options.updatable);
  63905. return tiledGround;
  63906. };
  63907. /**
  63908. * Creates a ground mesh from a height map
  63909. * * The parameter `url` sets the URL of the height map image resource.
  63910. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63911. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63912. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63913. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63914. * * 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.
  63915. * * 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).
  63916. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63917. * @param name defines the name of the mesh
  63918. * @param url defines the url to the height map
  63919. * @param options defines the options used to create the mesh
  63920. * @param scene defines the hosting scene
  63921. * @returns the ground mesh
  63922. * @see http://doc.babylonjs.com/babylon101/height_map
  63923. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63924. */
  63925. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63926. var width = options.width || 10.0;
  63927. var height = options.height || 10.0;
  63928. var subdivisions = options.subdivisions || 1 | 0;
  63929. var minHeight = options.minHeight || 0.0;
  63930. var maxHeight = options.maxHeight || 1.0;
  63931. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63932. var updatable = options.updatable;
  63933. var onReady = options.onReady;
  63934. var ground = new BABYLON.GroundMesh(name, scene);
  63935. ground._subdivisionsX = subdivisions;
  63936. ground._subdivisionsY = subdivisions;
  63937. ground._width = width;
  63938. ground._height = height;
  63939. ground._maxX = ground._width / 2.0;
  63940. ground._maxZ = ground._height / 2.0;
  63941. ground._minX = -ground._maxX;
  63942. ground._minZ = -ground._maxZ;
  63943. ground._setReady(false);
  63944. var onload = function (img) {
  63945. // Getting height map data
  63946. var canvas = document.createElement("canvas");
  63947. var context = canvas.getContext("2d");
  63948. if (!context) {
  63949. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63950. }
  63951. if (scene.isDisposed) {
  63952. return;
  63953. }
  63954. var bufferWidth = img.width;
  63955. var bufferHeight = img.height;
  63956. canvas.width = bufferWidth;
  63957. canvas.height = bufferHeight;
  63958. context.drawImage(img, 0, 0);
  63959. // Create VertexData from map data
  63960. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63961. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63962. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63963. width: width, height: height,
  63964. subdivisions: subdivisions,
  63965. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63966. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63967. });
  63968. vertexData.applyToMesh(ground, updatable);
  63969. //execute ready callback, if set
  63970. if (onReady) {
  63971. onReady(ground);
  63972. }
  63973. ground._setReady(true);
  63974. };
  63975. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63976. return ground;
  63977. };
  63978. /**
  63979. * Creates a polygon mesh
  63980. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63981. * * 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
  63982. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63983. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63984. * * 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)
  63985. * * Remember you can only change the shape positions, not their number when updating a polygon
  63986. * @param name defines the name of the mesh
  63987. * @param options defines the options used to create the mesh
  63988. * @param scene defines the hosting scene
  63989. * @returns the polygon mesh
  63990. */
  63991. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63992. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63993. var shape = options.shape;
  63994. var holes = options.holes || [];
  63995. var depth = options.depth || 0;
  63996. var contours = [];
  63997. var hole = [];
  63998. for (var i = 0; i < shape.length; i++) {
  63999. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64000. }
  64001. var epsilon = 0.00000001;
  64002. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64003. contours.pop();
  64004. }
  64005. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64006. for (var hNb = 0; hNb < holes.length; hNb++) {
  64007. hole = [];
  64008. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64009. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64010. }
  64011. polygonTriangulation.addHole(hole);
  64012. }
  64013. var polygon = polygonTriangulation.build(options.updatable, depth);
  64014. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64015. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64016. vertexData.applyToMesh(polygon, options.updatable);
  64017. return polygon;
  64018. };
  64019. ;
  64020. /**
  64021. * Creates an extruded polygon mesh, with depth in the Y direction.
  64022. * * 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)
  64023. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64024. * @param name defines the name of the mesh
  64025. * @param options defines the options used to create the mesh
  64026. * @param scene defines the hosting scene
  64027. * @returns the polygon mesh
  64028. */
  64029. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64030. return MeshBuilder.CreatePolygon(name, options, scene);
  64031. };
  64032. ;
  64033. /**
  64034. * Creates a tube mesh.
  64035. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64036. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64037. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64038. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64039. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64040. * * 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)
  64041. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64042. * * 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
  64043. * * 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
  64044. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64045. * * 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
  64046. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64047. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64048. * @param name defines the name of the mesh
  64049. * @param options defines the options used to create the mesh
  64050. * @param scene defines the hosting scene
  64051. * @returns the tube mesh
  64052. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64053. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64054. */
  64055. MeshBuilder.CreateTube = function (name, options, scene) {
  64056. var path = options.path;
  64057. var instance = options.instance;
  64058. var radius = 1.0;
  64059. if (instance) {
  64060. radius = instance.radius;
  64061. }
  64062. if (options.radius !== undefined) {
  64063. radius = options.radius;
  64064. }
  64065. ;
  64066. var tessellation = options.tessellation || 64 | 0;
  64067. var radiusFunction = options.radiusFunction || null;
  64068. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64069. var invertUV = options.invertUV || false;
  64070. var updatable = options.updatable;
  64071. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64072. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64073. // tube geometry
  64074. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64075. var tangents = path3D.getTangents();
  64076. var normals = path3D.getNormals();
  64077. var distances = path3D.getDistances();
  64078. var pi2 = Math.PI * 2;
  64079. var step = pi2 / tessellation * arc;
  64080. var returnRadius = function () { return radius; };
  64081. var radiusFunctionFinal = radiusFunction || returnRadius;
  64082. var circlePath;
  64083. var rad;
  64084. var normal;
  64085. var rotated;
  64086. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64087. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64088. for (var i = 0; i < path.length; i++) {
  64089. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64090. circlePath = Array(); // current circle array
  64091. normal = normals[i]; // current normal
  64092. for (var t = 0; t < tessellation; t++) {
  64093. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64094. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64095. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64096. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64097. circlePath[t] = rotated;
  64098. }
  64099. circlePaths[index] = circlePath;
  64100. index++;
  64101. }
  64102. // cap
  64103. var capPath = function (nbPoints, pathIndex) {
  64104. var pointCap = Array();
  64105. for (var i = 0; i < nbPoints; i++) {
  64106. pointCap.push(path[pathIndex]);
  64107. }
  64108. return pointCap;
  64109. };
  64110. switch (cap) {
  64111. case BABYLON.Mesh.NO_CAP:
  64112. break;
  64113. case BABYLON.Mesh.CAP_START:
  64114. circlePaths[0] = capPath(tessellation, 0);
  64115. circlePaths[1] = circlePaths[2].slice(0);
  64116. break;
  64117. case BABYLON.Mesh.CAP_END:
  64118. circlePaths[index] = circlePaths[index - 1].slice(0);
  64119. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64120. break;
  64121. case BABYLON.Mesh.CAP_ALL:
  64122. circlePaths[0] = capPath(tessellation, 0);
  64123. circlePaths[1] = circlePaths[2].slice(0);
  64124. circlePaths[index] = circlePaths[index - 1].slice(0);
  64125. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64126. break;
  64127. default:
  64128. break;
  64129. }
  64130. return circlePaths;
  64131. };
  64132. var path3D;
  64133. var pathArray;
  64134. if (instance) { // tube update
  64135. var arc = options.arc || instance.arc;
  64136. path3D = (instance.path3D).update(path);
  64137. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64138. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64139. instance.path3D = path3D;
  64140. instance.pathArray = pathArray;
  64141. instance.arc = arc;
  64142. instance.radius = radius;
  64143. return instance;
  64144. }
  64145. // tube creation
  64146. path3D = new BABYLON.Path3D(path);
  64147. var newPathArray = new Array();
  64148. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64149. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64150. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64151. tube.pathArray = pathArray;
  64152. tube.path3D = path3D;
  64153. tube.tessellation = tessellation;
  64154. tube.cap = cap;
  64155. tube.arc = options.arc;
  64156. tube.radius = radius;
  64157. return tube;
  64158. };
  64159. /**
  64160. * Creates a polyhedron mesh
  64161. * * 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
  64162. * * The parameter `size` (positive float, default 1) sets the polygon size
  64163. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64164. * * 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`
  64165. * * 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
  64166. * * 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)`)
  64167. * * 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
  64168. * * 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
  64169. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64170. * * 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
  64171. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64172. * @param name defines the name of the mesh
  64173. * @param options defines the options used to create the mesh
  64174. * @param scene defines the hosting scene
  64175. * @returns the polyhedron mesh
  64176. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64177. */
  64178. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64179. var polyhedron = new BABYLON.Mesh(name, scene);
  64180. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64181. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64182. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64183. vertexData.applyToMesh(polyhedron, options.updatable);
  64184. return polyhedron;
  64185. };
  64186. /**
  64187. * Creates a decal mesh.
  64188. * 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
  64189. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64190. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64191. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64192. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64193. * @param name defines the name of the mesh
  64194. * @param sourceMesh defines the mesh where the decal must be applied
  64195. * @param options defines the options used to create the mesh
  64196. * @param scene defines the hosting scene
  64197. * @returns the decal mesh
  64198. * @see http://doc.babylonjs.com/how_to/decals
  64199. */
  64200. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64201. var indices = sourceMesh.getIndices();
  64202. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64203. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64204. var position = options.position || BABYLON.Vector3.Zero();
  64205. var normal = options.normal || BABYLON.Vector3.Up();
  64206. var size = options.size || BABYLON.Vector3.One();
  64207. var angle = options.angle || 0;
  64208. // Getting correct rotation
  64209. if (!normal) {
  64210. var target = new BABYLON.Vector3(0, 0, 1);
  64211. var camera = sourceMesh.getScene().activeCamera;
  64212. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64213. normal = camera.globalPosition.subtract(cameraWorldTarget);
  64214. }
  64215. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  64216. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  64217. var pitch = Math.atan2(normal.y, len);
  64218. // Matrix
  64219. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  64220. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  64221. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  64222. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64223. var vertexData = new BABYLON.VertexData();
  64224. vertexData.indices = [];
  64225. vertexData.positions = [];
  64226. vertexData.normals = [];
  64227. vertexData.uvs = [];
  64228. var currentVertexDataIndex = 0;
  64229. var extractDecalVector3 = function (indexId) {
  64230. var result = new BABYLON.PositionNormalVertex();
  64231. if (!indices || !positions || !normals) {
  64232. return result;
  64233. }
  64234. var vertexId = indices[indexId];
  64235. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64236. // Send vector to decal local world
  64237. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64238. // Get normal
  64239. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64240. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64241. return result;
  64242. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64243. var clip = function (vertices, axis) {
  64244. if (vertices.length === 0) {
  64245. return vertices;
  64246. }
  64247. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64248. var clipVertices = function (v0, v1) {
  64249. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64250. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64251. };
  64252. var result = new Array();
  64253. for (var index = 0; index < vertices.length; index += 3) {
  64254. var v1Out;
  64255. var v2Out;
  64256. var v3Out;
  64257. var total = 0;
  64258. var nV1 = null;
  64259. var nV2 = null;
  64260. var nV3 = null;
  64261. var nV4 = null;
  64262. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64263. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64264. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64265. v1Out = d1 > 0;
  64266. v2Out = d2 > 0;
  64267. v3Out = d3 > 0;
  64268. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64269. switch (total) {
  64270. case 0:
  64271. result.push(vertices[index]);
  64272. result.push(vertices[index + 1]);
  64273. result.push(vertices[index + 2]);
  64274. break;
  64275. case 1:
  64276. if (v1Out) {
  64277. nV1 = vertices[index + 1];
  64278. nV2 = vertices[index + 2];
  64279. nV3 = clipVertices(vertices[index], nV1);
  64280. nV4 = clipVertices(vertices[index], nV2);
  64281. }
  64282. if (v2Out) {
  64283. nV1 = vertices[index];
  64284. nV2 = vertices[index + 2];
  64285. nV3 = clipVertices(vertices[index + 1], nV1);
  64286. nV4 = clipVertices(vertices[index + 1], nV2);
  64287. result.push(nV3);
  64288. result.push(nV2.clone());
  64289. result.push(nV1.clone());
  64290. result.push(nV2.clone());
  64291. result.push(nV3.clone());
  64292. result.push(nV4);
  64293. break;
  64294. }
  64295. if (v3Out) {
  64296. nV1 = vertices[index];
  64297. nV2 = vertices[index + 1];
  64298. nV3 = clipVertices(vertices[index + 2], nV1);
  64299. nV4 = clipVertices(vertices[index + 2], nV2);
  64300. }
  64301. if (nV1 && nV2 && nV3 && nV4) {
  64302. result.push(nV1.clone());
  64303. result.push(nV2.clone());
  64304. result.push(nV3);
  64305. result.push(nV4);
  64306. result.push(nV3.clone());
  64307. result.push(nV2.clone());
  64308. }
  64309. break;
  64310. case 2:
  64311. if (!v1Out) {
  64312. nV1 = vertices[index].clone();
  64313. nV2 = clipVertices(nV1, vertices[index + 1]);
  64314. nV3 = clipVertices(nV1, vertices[index + 2]);
  64315. result.push(nV1);
  64316. result.push(nV2);
  64317. result.push(nV3);
  64318. }
  64319. if (!v2Out) {
  64320. nV1 = vertices[index + 1].clone();
  64321. nV2 = clipVertices(nV1, vertices[index + 2]);
  64322. nV3 = clipVertices(nV1, vertices[index]);
  64323. result.push(nV1);
  64324. result.push(nV2);
  64325. result.push(nV3);
  64326. }
  64327. if (!v3Out) {
  64328. nV1 = vertices[index + 2].clone();
  64329. nV2 = clipVertices(nV1, vertices[index]);
  64330. nV3 = clipVertices(nV1, vertices[index + 1]);
  64331. result.push(nV1);
  64332. result.push(nV2);
  64333. result.push(nV3);
  64334. }
  64335. break;
  64336. case 3:
  64337. break;
  64338. }
  64339. }
  64340. return result;
  64341. };
  64342. for (var index = 0; index < indices.length; index += 3) {
  64343. var faceVertices = new Array();
  64344. faceVertices.push(extractDecalVector3(index));
  64345. faceVertices.push(extractDecalVector3(index + 1));
  64346. faceVertices.push(extractDecalVector3(index + 2));
  64347. // Clip
  64348. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64349. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64350. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64351. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64352. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64353. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64354. if (faceVertices.length === 0) {
  64355. continue;
  64356. }
  64357. // Add UVs and get back to world
  64358. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64359. var vertex = faceVertices[vIndex];
  64360. //TODO check for Int32Array | Uint32Array | Uint16Array
  64361. vertexData.indices.push(currentVertexDataIndex);
  64362. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64363. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64364. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64365. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64366. currentVertexDataIndex++;
  64367. }
  64368. }
  64369. // Return mesh
  64370. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64371. vertexData.applyToMesh(decal);
  64372. decal.position = position.clone();
  64373. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64374. return decal;
  64375. };
  64376. // Privates
  64377. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64378. // extrusion geometry
  64379. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64380. var tangents = path3D.getTangents();
  64381. var normals = path3D.getNormals();
  64382. var binormals = path3D.getBinormals();
  64383. var distances = path3D.getDistances();
  64384. var angle = 0;
  64385. var returnScale = function () { return scale !== null ? scale : 1; };
  64386. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64387. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64388. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64389. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64390. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64391. for (var i = 0; i < curve.length; i++) {
  64392. var shapePath = new Array();
  64393. var angleStep = rotate(i, distances[i]);
  64394. var scaleRatio = scl(i, distances[i]);
  64395. for (var p = 0; p < shape.length; p++) {
  64396. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64397. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64398. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64399. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64400. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64401. shapePath[p] = rotated;
  64402. }
  64403. shapePaths[index] = shapePath;
  64404. angle += angleStep;
  64405. index++;
  64406. }
  64407. // cap
  64408. var capPath = function (shapePath) {
  64409. var pointCap = Array();
  64410. var barycenter = BABYLON.Vector3.Zero();
  64411. var i;
  64412. for (i = 0; i < shapePath.length; i++) {
  64413. barycenter.addInPlace(shapePath[i]);
  64414. }
  64415. barycenter.scaleInPlace(1.0 / shapePath.length);
  64416. for (i = 0; i < shapePath.length; i++) {
  64417. pointCap.push(barycenter);
  64418. }
  64419. return pointCap;
  64420. };
  64421. switch (cap) {
  64422. case BABYLON.Mesh.NO_CAP:
  64423. break;
  64424. case BABYLON.Mesh.CAP_START:
  64425. shapePaths[0] = capPath(shapePaths[2]);
  64426. shapePaths[1] = shapePaths[2];
  64427. break;
  64428. case BABYLON.Mesh.CAP_END:
  64429. shapePaths[index] = shapePaths[index - 1];
  64430. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64431. break;
  64432. case BABYLON.Mesh.CAP_ALL:
  64433. shapePaths[0] = capPath(shapePaths[2]);
  64434. shapePaths[1] = shapePaths[2];
  64435. shapePaths[index] = shapePaths[index - 1];
  64436. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64437. break;
  64438. default:
  64439. break;
  64440. }
  64441. return shapePaths;
  64442. };
  64443. var path3D;
  64444. var pathArray;
  64445. if (instance) { // instance update
  64446. path3D = (instance.path3D).update(curve);
  64447. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64448. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64449. return instance;
  64450. }
  64451. // extruded shape creation
  64452. path3D = new BABYLON.Path3D(curve);
  64453. var newShapePaths = new Array();
  64454. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64455. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64456. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64457. extrudedGeneric.pathArray = pathArray;
  64458. extrudedGeneric.path3D = path3D;
  64459. extrudedGeneric.cap = cap;
  64460. return extrudedGeneric;
  64461. };
  64462. return MeshBuilder;
  64463. }());
  64464. BABYLON.MeshBuilder = MeshBuilder;
  64465. })(BABYLON || (BABYLON = {}));
  64466. //# sourceMappingURL=babylon.meshBuilder.js.map
  64467. var BABYLON;
  64468. (function (BABYLON) {
  64469. /**
  64470. * Draco compression (https://google.github.io/draco/)
  64471. *
  64472. * This class wraps the Draco module.
  64473. *
  64474. * **Encoder**
  64475. *
  64476. * The encoder is not currently implemented.
  64477. *
  64478. * **Decoder**
  64479. *
  64480. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64481. *
  64482. * To update the configuration, use the following code:
  64483. * ```javascript
  64484. * BABYLON.DracoCompression.Configuration = {
  64485. * decoder: {
  64486. * wasmUrl: "<url to the WebAssembly library>",
  64487. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64488. * fallbackUrl: "<url to the fallback JavaScript library>",
  64489. * }
  64490. * };
  64491. * ```
  64492. *
  64493. * 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.
  64494. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64495. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64496. *
  64497. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64498. * ```javascript
  64499. * var dracoCompression = new BABYLON.DracoCompression();
  64500. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64501. * [BABYLON.VertexBuffer.PositionKind]: 0
  64502. * });
  64503. * ```
  64504. *
  64505. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64506. */
  64507. var DracoCompression = /** @class */ (function () {
  64508. /**
  64509. * Constructor
  64510. */
  64511. function DracoCompression() {
  64512. }
  64513. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64514. /**
  64515. * Returns true if the decoder is available.
  64516. */
  64517. get: function () {
  64518. if (typeof DracoDecoderModule !== "undefined") {
  64519. return true;
  64520. }
  64521. var decoder = DracoCompression.Configuration.decoder;
  64522. if (decoder) {
  64523. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64524. return true;
  64525. }
  64526. if (decoder.fallbackUrl) {
  64527. return true;
  64528. }
  64529. }
  64530. return false;
  64531. },
  64532. enumerable: true,
  64533. configurable: true
  64534. });
  64535. /**
  64536. * Stop all async operations and release resources.
  64537. */
  64538. DracoCompression.prototype.dispose = function () {
  64539. };
  64540. /**
  64541. * Decode Draco compressed mesh data to vertex data.
  64542. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64543. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64544. * @returns A promise that resolves with the decoded vertex data
  64545. */
  64546. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64547. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64548. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64549. var module = wrappedModule.module;
  64550. var vertexData = new BABYLON.VertexData();
  64551. var buffer = new module.DecoderBuffer();
  64552. buffer.Init(dataView, dataView.byteLength);
  64553. var decoder = new module.Decoder();
  64554. var geometry;
  64555. var status;
  64556. try {
  64557. var type = decoder.GetEncodedGeometryType(buffer);
  64558. switch (type) {
  64559. case module.TRIANGULAR_MESH:
  64560. geometry = new module.Mesh();
  64561. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64562. break;
  64563. case module.POINT_CLOUD:
  64564. geometry = new module.PointCloud();
  64565. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64566. break;
  64567. default:
  64568. throw new Error("Invalid geometry type " + type);
  64569. }
  64570. if (!status.ok() || !geometry.ptr) {
  64571. throw new Error(status.error_msg());
  64572. }
  64573. var numPoints = geometry.num_points();
  64574. if (type === module.TRIANGULAR_MESH) {
  64575. var numFaces = geometry.num_faces();
  64576. var faceIndices = new module.DracoInt32Array();
  64577. try {
  64578. var indices = new Uint32Array(numFaces * 3);
  64579. for (var i = 0; i < numFaces; i++) {
  64580. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64581. var offset = i * 3;
  64582. indices[offset + 0] = faceIndices.GetValue(0);
  64583. indices[offset + 1] = faceIndices.GetValue(1);
  64584. indices[offset + 2] = faceIndices.GetValue(2);
  64585. }
  64586. vertexData.indices = indices;
  64587. }
  64588. finally {
  64589. module.destroy(faceIndices);
  64590. }
  64591. }
  64592. for (var kind in attributes) {
  64593. var uniqueId = attributes[kind];
  64594. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64595. var dracoData = new module.DracoFloat32Array();
  64596. try {
  64597. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64598. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64599. for (var i = 0; i < babylonData.length; i++) {
  64600. babylonData[i] = dracoData.GetValue(i);
  64601. }
  64602. vertexData.set(babylonData, kind);
  64603. }
  64604. finally {
  64605. module.destroy(dracoData);
  64606. }
  64607. }
  64608. }
  64609. finally {
  64610. if (geometry) {
  64611. module.destroy(geometry);
  64612. }
  64613. module.destroy(decoder);
  64614. module.destroy(buffer);
  64615. }
  64616. return vertexData;
  64617. });
  64618. };
  64619. DracoCompression._GetDecoderModule = function () {
  64620. if (!DracoCompression._DecoderModulePromise) {
  64621. var promise = null;
  64622. var config_1 = {};
  64623. if (typeof DracoDecoderModule !== "undefined") {
  64624. promise = Promise.resolve();
  64625. }
  64626. else {
  64627. var decoder = DracoCompression.Configuration.decoder;
  64628. if (decoder) {
  64629. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64630. promise = Promise.all([
  64631. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64632. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64633. config_1.wasmBinary = data;
  64634. })
  64635. ]);
  64636. }
  64637. else if (decoder.fallbackUrl) {
  64638. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64639. }
  64640. }
  64641. }
  64642. if (!promise) {
  64643. throw new Error("Draco decoder module is not available");
  64644. }
  64645. DracoCompression._DecoderModulePromise = promise.then(function () {
  64646. return new Promise(function (resolve) {
  64647. config_1.onModuleLoaded = function (decoderModule) {
  64648. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64649. resolve({ module: decoderModule });
  64650. };
  64651. DracoDecoderModule(config_1);
  64652. });
  64653. });
  64654. }
  64655. return DracoCompression._DecoderModulePromise;
  64656. };
  64657. DracoCompression._LoadScriptAsync = function (url) {
  64658. return new Promise(function (resolve, reject) {
  64659. BABYLON.Tools.LoadScript(url, function () {
  64660. resolve();
  64661. }, function (message) {
  64662. reject(new Error(message));
  64663. });
  64664. });
  64665. };
  64666. DracoCompression._LoadFileAsync = function (url) {
  64667. return new Promise(function (resolve, reject) {
  64668. BABYLON.Tools.LoadFile(url, function (data) {
  64669. resolve(data);
  64670. }, undefined, undefined, true, function (request, exception) {
  64671. reject(exception);
  64672. });
  64673. });
  64674. };
  64675. /**
  64676. * The configuration. Defaults to the following urls:
  64677. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64678. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64679. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64680. */
  64681. DracoCompression.Configuration = {
  64682. decoder: {
  64683. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64684. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64685. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64686. }
  64687. };
  64688. return DracoCompression;
  64689. }());
  64690. BABYLON.DracoCompression = DracoCompression;
  64691. })(BABYLON || (BABYLON = {}));
  64692. //# sourceMappingURL=babylon.dracoCompression.js.map
  64693. var BABYLON;
  64694. (function (BABYLON) {
  64695. var AudioEngine = /** @class */ (function () {
  64696. function AudioEngine() {
  64697. this._audioContext = null;
  64698. this._audioContextInitialized = false;
  64699. this.canUseWebAudio = false;
  64700. this.WarnedWebAudioUnsupported = false;
  64701. this.unlocked = false;
  64702. this.isMP3supported = false;
  64703. this.isOGGsupported = false;
  64704. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64705. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64706. this.canUseWebAudio = true;
  64707. }
  64708. var audioElem = document.createElement('audio');
  64709. try {
  64710. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64711. this.isMP3supported = true;
  64712. }
  64713. }
  64714. catch (e) {
  64715. // protect error during capability check.
  64716. }
  64717. try {
  64718. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64719. this.isOGGsupported = true;
  64720. }
  64721. }
  64722. catch (e) {
  64723. // protect error during capability check.
  64724. }
  64725. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64726. this._unlockiOSaudio();
  64727. }
  64728. else {
  64729. this.unlocked = true;
  64730. }
  64731. }
  64732. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64733. get: function () {
  64734. if (!this._audioContextInitialized) {
  64735. this._initializeAudioContext();
  64736. }
  64737. return this._audioContext;
  64738. },
  64739. enumerable: true,
  64740. configurable: true
  64741. });
  64742. AudioEngine.prototype._unlockiOSaudio = function () {
  64743. var _this = this;
  64744. var unlockaudio = function () {
  64745. if (!_this.audioContext) {
  64746. return;
  64747. }
  64748. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64749. var source = _this.audioContext.createBufferSource();
  64750. source.buffer = buffer;
  64751. source.connect(_this.audioContext.destination);
  64752. source.start(0);
  64753. setTimeout(function () {
  64754. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64755. _this.unlocked = true;
  64756. window.removeEventListener('touchend', unlockaudio, false);
  64757. if (_this.onAudioUnlocked) {
  64758. _this.onAudioUnlocked();
  64759. }
  64760. }
  64761. }, 0);
  64762. };
  64763. window.addEventListener('touchend', unlockaudio, false);
  64764. };
  64765. AudioEngine.prototype._initializeAudioContext = function () {
  64766. try {
  64767. if (this.canUseWebAudio) {
  64768. this._audioContext = new AudioContext();
  64769. // create a global volume gain node
  64770. this.masterGain = this._audioContext.createGain();
  64771. this.masterGain.gain.value = 1;
  64772. this.masterGain.connect(this._audioContext.destination);
  64773. this._audioContextInitialized = true;
  64774. }
  64775. }
  64776. catch (e) {
  64777. this.canUseWebAudio = false;
  64778. BABYLON.Tools.Error("Web Audio: " + e.message);
  64779. }
  64780. };
  64781. AudioEngine.prototype.dispose = function () {
  64782. if (this.canUseWebAudio && this._audioContextInitialized) {
  64783. if (this._connectedAnalyser && this._audioContext) {
  64784. this._connectedAnalyser.stopDebugCanvas();
  64785. this._connectedAnalyser.dispose();
  64786. this.masterGain.disconnect();
  64787. this.masterGain.connect(this._audioContext.destination);
  64788. this._connectedAnalyser = null;
  64789. }
  64790. this.masterGain.gain.value = 1;
  64791. }
  64792. this.WarnedWebAudioUnsupported = false;
  64793. };
  64794. AudioEngine.prototype.getGlobalVolume = function () {
  64795. if (this.canUseWebAudio && this._audioContextInitialized) {
  64796. return this.masterGain.gain.value;
  64797. }
  64798. else {
  64799. return -1;
  64800. }
  64801. };
  64802. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64803. if (this.canUseWebAudio && this._audioContextInitialized) {
  64804. this.masterGain.gain.value = newVolume;
  64805. }
  64806. };
  64807. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64808. if (this._connectedAnalyser) {
  64809. this._connectedAnalyser.stopDebugCanvas();
  64810. }
  64811. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64812. this._connectedAnalyser = analyser;
  64813. this.masterGain.disconnect();
  64814. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64815. }
  64816. };
  64817. return AudioEngine;
  64818. }());
  64819. BABYLON.AudioEngine = AudioEngine;
  64820. })(BABYLON || (BABYLON = {}));
  64821. //# sourceMappingURL=babylon.audioEngine.js.map
  64822. var BABYLON;
  64823. (function (BABYLON) {
  64824. var Sound = /** @class */ (function () {
  64825. /**
  64826. * Create a sound and attach it to a scene
  64827. * @param name Name of your sound
  64828. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64829. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64830. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64831. */
  64832. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64833. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64834. var _this = this;
  64835. this.autoplay = false;
  64836. this.loop = false;
  64837. this.useCustomAttenuation = false;
  64838. this.spatialSound = false;
  64839. this.refDistance = 1;
  64840. this.rolloffFactor = 1;
  64841. this.maxDistance = 100;
  64842. this.distanceModel = "linear";
  64843. this._panningModel = "equalpower";
  64844. /**
  64845. * Observable event when the current playing sound finishes.
  64846. */
  64847. this.onEndedObservable = new BABYLON.Observable();
  64848. this._playbackRate = 1;
  64849. this._streaming = false;
  64850. this._startTime = 0;
  64851. this._startOffset = 0;
  64852. this._position = BABYLON.Vector3.Zero();
  64853. /** @hidden */
  64854. this._positionInEmitterSpace = false;
  64855. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64856. this._volume = 1;
  64857. this._isReadyToPlay = false;
  64858. this.isPlaying = false;
  64859. this.isPaused = false;
  64860. this._isDirectional = false;
  64861. // Used if you'd like to create a directional sound.
  64862. // If not set, the sound will be omnidirectional
  64863. this._coneInnerAngle = 360;
  64864. this._coneOuterAngle = 360;
  64865. this._coneOuterGain = 0;
  64866. this._isOutputConnected = false;
  64867. this._urlType = "Unknown";
  64868. this.name = name;
  64869. this._scene = scene;
  64870. this._readyToPlayCallback = readyToPlayCallback;
  64871. // Default custom attenuation function is a linear attenuation
  64872. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64873. if (currentDistance < maxDistance) {
  64874. return currentVolume * (1 - currentDistance / maxDistance);
  64875. }
  64876. else {
  64877. return 0;
  64878. }
  64879. };
  64880. if (options) {
  64881. this.autoplay = options.autoplay || false;
  64882. this.loop = options.loop || false;
  64883. // if volume === 0, we need another way to check this option
  64884. if (options.volume !== undefined) {
  64885. this._volume = options.volume;
  64886. }
  64887. this.spatialSound = options.spatialSound || false;
  64888. this.maxDistance = options.maxDistance || 100;
  64889. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64890. this.rolloffFactor = options.rolloffFactor || 1;
  64891. this.refDistance = options.refDistance || 1;
  64892. this.distanceModel = options.distanceModel || "linear";
  64893. this._playbackRate = options.playbackRate || 1;
  64894. this._streaming = options.streaming || false;
  64895. }
  64896. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64897. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64898. this._soundGain.gain.value = this._volume;
  64899. this._inputAudioNode = this._soundGain;
  64900. this._outputAudioNode = this._soundGain;
  64901. if (this.spatialSound) {
  64902. this._createSpatialParameters();
  64903. }
  64904. this._scene.mainSoundTrack.AddSound(this);
  64905. var validParameter = true;
  64906. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64907. if (urlOrArrayBuffer) {
  64908. try {
  64909. if (typeof (urlOrArrayBuffer) === "string") {
  64910. this._urlType = "String";
  64911. }
  64912. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64913. this._urlType = "ArrayBuffer";
  64914. }
  64915. else if (urlOrArrayBuffer instanceof MediaStream) {
  64916. this._urlType = "MediaStream";
  64917. }
  64918. else if (Array.isArray(urlOrArrayBuffer)) {
  64919. this._urlType = "Array";
  64920. }
  64921. var urls = [];
  64922. var codecSupportedFound = false;
  64923. switch (this._urlType) {
  64924. case "MediaStream":
  64925. this._streaming = true;
  64926. this._isReadyToPlay = true;
  64927. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  64928. if (this.autoplay) {
  64929. this.play();
  64930. }
  64931. if (this._readyToPlayCallback) {
  64932. this._readyToPlayCallback();
  64933. }
  64934. break;
  64935. case "ArrayBuffer":
  64936. if (urlOrArrayBuffer.byteLength > 0) {
  64937. codecSupportedFound = true;
  64938. this._soundLoaded(urlOrArrayBuffer);
  64939. }
  64940. break;
  64941. case "String":
  64942. urls.push(urlOrArrayBuffer);
  64943. case "Array":
  64944. if (urls.length === 0)
  64945. urls = urlOrArrayBuffer;
  64946. // If we found a supported format, we load it immediately and stop the loop
  64947. for (var i = 0; i < urls.length; i++) {
  64948. var url = urls[i];
  64949. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64950. codecSupportedFound = true;
  64951. }
  64952. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64953. codecSupportedFound = true;
  64954. }
  64955. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64956. codecSupportedFound = true;
  64957. }
  64958. if (url.indexOf("blob:") !== -1) {
  64959. codecSupportedFound = true;
  64960. }
  64961. if (codecSupportedFound) {
  64962. // Loading sound using XHR2
  64963. if (!this._streaming) {
  64964. this._scene._loadFile(url, function (data) {
  64965. _this._soundLoaded(data);
  64966. }, undefined, true, true, function (exception) {
  64967. if (exception) {
  64968. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64969. }
  64970. BABYLON.Tools.Error("Sound creation aborted.");
  64971. _this._scene.mainSoundTrack.RemoveSound(_this);
  64972. });
  64973. }
  64974. // Streaming sound using HTML5 Audio tag
  64975. else {
  64976. this._htmlAudioElement = new Audio(url);
  64977. this._htmlAudioElement.controls = false;
  64978. this._htmlAudioElement.loop = this.loop;
  64979. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64980. this._htmlAudioElement.preload = "auto";
  64981. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64982. _this._isReadyToPlay = true;
  64983. if (_this.autoplay) {
  64984. _this.play();
  64985. }
  64986. if (_this._readyToPlayCallback) {
  64987. _this._readyToPlayCallback();
  64988. }
  64989. });
  64990. document.body.appendChild(this._htmlAudioElement);
  64991. }
  64992. break;
  64993. }
  64994. }
  64995. break;
  64996. default:
  64997. validParameter = false;
  64998. break;
  64999. }
  65000. if (!validParameter) {
  65001. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65002. }
  65003. else {
  65004. if (!codecSupportedFound) {
  65005. this._isReadyToPlay = true;
  65006. // Simulating a ready to play event to avoid breaking code path
  65007. if (this._readyToPlayCallback) {
  65008. window.setTimeout(function () {
  65009. if (_this._readyToPlayCallback) {
  65010. _this._readyToPlayCallback();
  65011. }
  65012. }, 1000);
  65013. }
  65014. }
  65015. }
  65016. }
  65017. catch (ex) {
  65018. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65019. this._scene.mainSoundTrack.RemoveSound(this);
  65020. }
  65021. }
  65022. }
  65023. else {
  65024. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65025. this._scene.mainSoundTrack.AddSound(this);
  65026. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65027. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65028. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65029. }
  65030. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65031. if (this._readyToPlayCallback) {
  65032. window.setTimeout(function () {
  65033. if (_this._readyToPlayCallback) {
  65034. _this._readyToPlayCallback();
  65035. }
  65036. }, 1000);
  65037. }
  65038. }
  65039. }
  65040. Sound.prototype.dispose = function () {
  65041. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65042. if (this.isPlaying) {
  65043. this.stop();
  65044. }
  65045. this._isReadyToPlay = false;
  65046. if (this.soundTrackId === -1) {
  65047. this._scene.mainSoundTrack.RemoveSound(this);
  65048. }
  65049. else {
  65050. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65051. }
  65052. if (this._soundGain) {
  65053. this._soundGain.disconnect();
  65054. this._soundGain = null;
  65055. }
  65056. if (this._soundPanner) {
  65057. this._soundPanner.disconnect();
  65058. this._soundPanner = null;
  65059. }
  65060. if (this._soundSource) {
  65061. this._soundSource.disconnect();
  65062. this._soundSource = null;
  65063. }
  65064. this._audioBuffer = null;
  65065. if (this._htmlAudioElement) {
  65066. this._htmlAudioElement.pause();
  65067. this._htmlAudioElement.src = "";
  65068. document.body.removeChild(this._htmlAudioElement);
  65069. }
  65070. if (this._streamingSource) {
  65071. this._streamingSource.disconnect();
  65072. }
  65073. if (this._connectedMesh && this._registerFunc) {
  65074. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65075. this._connectedMesh = null;
  65076. }
  65077. }
  65078. };
  65079. Sound.prototype.isReady = function () {
  65080. return this._isReadyToPlay;
  65081. };
  65082. Sound.prototype._soundLoaded = function (audioData) {
  65083. var _this = this;
  65084. if (!BABYLON.Engine.audioEngine.audioContext) {
  65085. return;
  65086. }
  65087. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65088. _this._audioBuffer = buffer;
  65089. _this._isReadyToPlay = true;
  65090. if (_this.autoplay) {
  65091. _this.play();
  65092. }
  65093. if (_this._readyToPlayCallback) {
  65094. _this._readyToPlayCallback();
  65095. }
  65096. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65097. };
  65098. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65099. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65100. this._audioBuffer = audioBuffer;
  65101. this._isReadyToPlay = true;
  65102. }
  65103. };
  65104. Sound.prototype.updateOptions = function (options) {
  65105. if (options) {
  65106. this.loop = options.loop || this.loop;
  65107. this.maxDistance = options.maxDistance || this.maxDistance;
  65108. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65109. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65110. this.refDistance = options.refDistance || this.refDistance;
  65111. this.distanceModel = options.distanceModel || this.distanceModel;
  65112. this._playbackRate = options.playbackRate || this._playbackRate;
  65113. this._updateSpatialParameters();
  65114. if (this.isPlaying) {
  65115. if (this._streaming && this._htmlAudioElement) {
  65116. this._htmlAudioElement.playbackRate = this._playbackRate;
  65117. }
  65118. else {
  65119. if (this._soundSource) {
  65120. this._soundSource.playbackRate.value = this._playbackRate;
  65121. }
  65122. }
  65123. }
  65124. }
  65125. };
  65126. Sound.prototype._createSpatialParameters = function () {
  65127. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65128. if (this._scene.headphone) {
  65129. this._panningModel = "HRTF";
  65130. }
  65131. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65132. this._updateSpatialParameters();
  65133. this._soundPanner.connect(this._outputAudioNode);
  65134. this._inputAudioNode = this._soundPanner;
  65135. }
  65136. };
  65137. Sound.prototype._updateSpatialParameters = function () {
  65138. if (this.spatialSound && this._soundPanner) {
  65139. if (this.useCustomAttenuation) {
  65140. // Tricks to disable in a way embedded Web Audio attenuation
  65141. this._soundPanner.distanceModel = "linear";
  65142. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65143. this._soundPanner.refDistance = 1;
  65144. this._soundPanner.rolloffFactor = 1;
  65145. this._soundPanner.panningModel = this._panningModel;
  65146. }
  65147. else {
  65148. this._soundPanner.distanceModel = this.distanceModel;
  65149. this._soundPanner.maxDistance = this.maxDistance;
  65150. this._soundPanner.refDistance = this.refDistance;
  65151. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65152. this._soundPanner.panningModel = this._panningModel;
  65153. }
  65154. }
  65155. };
  65156. Sound.prototype.switchPanningModelToHRTF = function () {
  65157. this._panningModel = "HRTF";
  65158. this._switchPanningModel();
  65159. };
  65160. Sound.prototype.switchPanningModelToEqualPower = function () {
  65161. this._panningModel = "equalpower";
  65162. this._switchPanningModel();
  65163. };
  65164. Sound.prototype._switchPanningModel = function () {
  65165. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65166. this._soundPanner.panningModel = this._panningModel;
  65167. }
  65168. };
  65169. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65170. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65171. if (this._isOutputConnected) {
  65172. this._outputAudioNode.disconnect();
  65173. }
  65174. this._outputAudioNode.connect(soundTrackAudioNode);
  65175. this._isOutputConnected = true;
  65176. }
  65177. };
  65178. /**
  65179. * Transform this sound into a directional source
  65180. * @param coneInnerAngle Size of the inner cone in degree
  65181. * @param coneOuterAngle Size of the outer cone in degree
  65182. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65183. */
  65184. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65185. if (coneOuterAngle < coneInnerAngle) {
  65186. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65187. return;
  65188. }
  65189. this._coneInnerAngle = coneInnerAngle;
  65190. this._coneOuterAngle = coneOuterAngle;
  65191. this._coneOuterGain = coneOuterGain;
  65192. this._isDirectional = true;
  65193. if (this.isPlaying && this.loop) {
  65194. this.stop();
  65195. this.play();
  65196. }
  65197. };
  65198. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65199. /**
  65200. * Gets or sets the inner angle for the directional cone.
  65201. */
  65202. get: function () {
  65203. return this._coneInnerAngle;
  65204. },
  65205. /**
  65206. * Gets or sets the inner angle for the directional cone.
  65207. */
  65208. set: function (value) {
  65209. if (value != this._coneInnerAngle) {
  65210. if (this._coneOuterAngle < value) {
  65211. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65212. return;
  65213. }
  65214. this._coneInnerAngle = value;
  65215. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65216. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65217. }
  65218. }
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65224. /**
  65225. * Gets or sets the outer angle for the directional cone.
  65226. */
  65227. get: function () {
  65228. return this._coneOuterAngle;
  65229. },
  65230. /**
  65231. * Gets or sets the outer angle for the directional cone.
  65232. */
  65233. set: function (value) {
  65234. if (value != this._coneOuterAngle) {
  65235. if (value < this._coneInnerAngle) {
  65236. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65237. return;
  65238. }
  65239. this._coneOuterAngle = value;
  65240. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65241. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65242. }
  65243. }
  65244. },
  65245. enumerable: true,
  65246. configurable: true
  65247. });
  65248. Sound.prototype.setPosition = function (newPosition) {
  65249. this._position = newPosition;
  65250. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65251. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65252. }
  65253. };
  65254. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65255. this._localDirection = newLocalDirection;
  65256. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65257. this._updateDirection();
  65258. }
  65259. };
  65260. Sound.prototype._updateDirection = function () {
  65261. if (!this._connectedMesh || !this._soundPanner) {
  65262. return;
  65263. }
  65264. var mat = this._connectedMesh.getWorldMatrix();
  65265. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65266. direction.normalize();
  65267. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65268. };
  65269. Sound.prototype.updateDistanceFromListener = function () {
  65270. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65271. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65272. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65273. }
  65274. };
  65275. Sound.prototype.setAttenuationFunction = function (callback) {
  65276. this._customAttenuationFunction = callback;
  65277. };
  65278. /**
  65279. * Play the sound
  65280. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65281. * @param offset (optional) Start the sound setting it at a specific time
  65282. */
  65283. Sound.prototype.play = function (time, offset) {
  65284. var _this = this;
  65285. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65286. try {
  65287. if (this._startOffset < 0) {
  65288. time = -this._startOffset;
  65289. this._startOffset = 0;
  65290. }
  65291. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65292. if (!this._soundSource || !this._streamingSource) {
  65293. if (this.spatialSound && this._soundPanner) {
  65294. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65295. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65296. }
  65297. if (this._isDirectional) {
  65298. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65299. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65300. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65301. if (this._connectedMesh) {
  65302. this._updateDirection();
  65303. }
  65304. else {
  65305. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65306. }
  65307. }
  65308. }
  65309. }
  65310. if (this._streaming) {
  65311. if (!this._streamingSource) {
  65312. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65313. this._htmlAudioElement.onended = function () { _this._onended(); };
  65314. this._htmlAudioElement.playbackRate = this._playbackRate;
  65315. }
  65316. this._streamingSource.disconnect();
  65317. this._streamingSource.connect(this._inputAudioNode);
  65318. if (this._htmlAudioElement) {
  65319. this._htmlAudioElement.play();
  65320. }
  65321. }
  65322. else {
  65323. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65324. this._soundSource.buffer = this._audioBuffer;
  65325. this._soundSource.connect(this._inputAudioNode);
  65326. this._soundSource.loop = this.loop;
  65327. this._soundSource.playbackRate.value = this._playbackRate;
  65328. this._soundSource.onended = function () { _this._onended(); };
  65329. if (this._soundSource.buffer) {
  65330. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65331. }
  65332. }
  65333. this._startTime = startTime;
  65334. this.isPlaying = true;
  65335. this.isPaused = false;
  65336. }
  65337. catch (ex) {
  65338. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65339. }
  65340. }
  65341. };
  65342. Sound.prototype._onended = function () {
  65343. this.isPlaying = false;
  65344. if (this.onended) {
  65345. this.onended();
  65346. }
  65347. this.onEndedObservable.notifyObservers(this);
  65348. };
  65349. /**
  65350. * Stop the sound
  65351. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65352. */
  65353. Sound.prototype.stop = function (time) {
  65354. if (this.isPlaying) {
  65355. if (this._streaming) {
  65356. if (this._htmlAudioElement) {
  65357. this._htmlAudioElement.pause();
  65358. // Test needed for Firefox or it will generate an Invalid State Error
  65359. if (this._htmlAudioElement.currentTime > 0) {
  65360. this._htmlAudioElement.currentTime = 0;
  65361. }
  65362. }
  65363. else {
  65364. this._streamingSource.disconnect();
  65365. }
  65366. }
  65367. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65368. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65369. this._soundSource.stop(stopTime);
  65370. this._soundSource.onended = function () { };
  65371. if (!this.isPaused) {
  65372. this._startOffset = 0;
  65373. }
  65374. }
  65375. this.isPlaying = false;
  65376. }
  65377. };
  65378. Sound.prototype.pause = function () {
  65379. if (this.isPlaying) {
  65380. this.isPaused = true;
  65381. if (this._streaming) {
  65382. if (this._htmlAudioElement) {
  65383. this._htmlAudioElement.pause();
  65384. }
  65385. else {
  65386. this._streamingSource.disconnect();
  65387. }
  65388. }
  65389. else if (BABYLON.Engine.audioEngine.audioContext) {
  65390. this.stop(0);
  65391. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65392. }
  65393. }
  65394. };
  65395. Sound.prototype.setVolume = function (newVolume, time) {
  65396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65397. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65398. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65399. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65400. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65401. }
  65402. else {
  65403. this._soundGain.gain.value = newVolume;
  65404. }
  65405. }
  65406. this._volume = newVolume;
  65407. };
  65408. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65409. this._playbackRate = newPlaybackRate;
  65410. if (this.isPlaying) {
  65411. if (this._streaming && this._htmlAudioElement) {
  65412. this._htmlAudioElement.playbackRate = this._playbackRate;
  65413. }
  65414. else if (this._soundSource) {
  65415. this._soundSource.playbackRate.value = this._playbackRate;
  65416. }
  65417. }
  65418. };
  65419. Sound.prototype.getVolume = function () {
  65420. return this._volume;
  65421. };
  65422. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65423. var _this = this;
  65424. if (this._connectedMesh && this._registerFunc) {
  65425. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65426. this._registerFunc = null;
  65427. }
  65428. this._connectedMesh = meshToConnectTo;
  65429. if (!this.spatialSound) {
  65430. this.spatialSound = true;
  65431. this._createSpatialParameters();
  65432. if (this.isPlaying && this.loop) {
  65433. this.stop();
  65434. this.play();
  65435. }
  65436. }
  65437. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65438. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65439. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65440. };
  65441. Sound.prototype.detachFromMesh = function () {
  65442. if (this._connectedMesh && this._registerFunc) {
  65443. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65444. this._registerFunc = null;
  65445. this._connectedMesh = null;
  65446. }
  65447. };
  65448. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65449. if (!node.getBoundingInfo) {
  65450. return;
  65451. }
  65452. var mesh = node;
  65453. if (this._positionInEmitterSpace) {
  65454. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65455. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65456. }
  65457. else {
  65458. var boundingInfo = mesh.getBoundingInfo();
  65459. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65460. }
  65461. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65462. this._updateDirection();
  65463. }
  65464. };
  65465. Sound.prototype.clone = function () {
  65466. var _this = this;
  65467. if (!this._streaming) {
  65468. var setBufferAndRun = function () {
  65469. if (_this._isReadyToPlay) {
  65470. clonedSound._audioBuffer = _this.getAudioBuffer();
  65471. clonedSound._isReadyToPlay = true;
  65472. if (clonedSound.autoplay) {
  65473. clonedSound.play();
  65474. }
  65475. }
  65476. else {
  65477. window.setTimeout(setBufferAndRun, 300);
  65478. }
  65479. };
  65480. var currentOptions = {
  65481. autoplay: this.autoplay, loop: this.loop,
  65482. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65483. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65484. refDistance: this.refDistance, distanceModel: this.distanceModel
  65485. };
  65486. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65487. if (this.useCustomAttenuation) {
  65488. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65489. }
  65490. clonedSound.setPosition(this._position);
  65491. clonedSound.setPlaybackRate(this._playbackRate);
  65492. setBufferAndRun();
  65493. return clonedSound;
  65494. }
  65495. // Can't clone a streaming sound
  65496. else {
  65497. return null;
  65498. }
  65499. };
  65500. Sound.prototype.getAudioBuffer = function () {
  65501. return this._audioBuffer;
  65502. };
  65503. Sound.prototype.serialize = function () {
  65504. var serializationObject = {
  65505. name: this.name,
  65506. url: this.name,
  65507. autoplay: this.autoplay,
  65508. loop: this.loop,
  65509. volume: this._volume,
  65510. spatialSound: this.spatialSound,
  65511. maxDistance: this.maxDistance,
  65512. rolloffFactor: this.rolloffFactor,
  65513. refDistance: this.refDistance,
  65514. distanceModel: this.distanceModel,
  65515. playbackRate: this._playbackRate,
  65516. panningModel: this._panningModel,
  65517. soundTrackId: this.soundTrackId
  65518. };
  65519. if (this.spatialSound) {
  65520. if (this._connectedMesh)
  65521. serializationObject.connectedMeshId = this._connectedMesh.id;
  65522. serializationObject.position = this._position.asArray();
  65523. serializationObject.refDistance = this.refDistance;
  65524. serializationObject.distanceModel = this.distanceModel;
  65525. serializationObject.isDirectional = this._isDirectional;
  65526. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65527. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65528. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65529. serializationObject.coneOuterGain = this._coneOuterGain;
  65530. }
  65531. return serializationObject;
  65532. };
  65533. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65534. var soundName = parsedSound.name;
  65535. var soundUrl;
  65536. if (parsedSound.url) {
  65537. soundUrl = rootUrl + parsedSound.url;
  65538. }
  65539. else {
  65540. soundUrl = rootUrl + soundName;
  65541. }
  65542. var options = {
  65543. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65544. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65545. rolloffFactor: parsedSound.rolloffFactor,
  65546. refDistance: parsedSound.refDistance,
  65547. distanceModel: parsedSound.distanceModel,
  65548. playbackRate: parsedSound.playbackRate
  65549. };
  65550. var newSound;
  65551. if (!sourceSound) {
  65552. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65553. scene._addPendingData(newSound);
  65554. }
  65555. else {
  65556. var setBufferAndRun = function () {
  65557. if (sourceSound._isReadyToPlay) {
  65558. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65559. newSound._isReadyToPlay = true;
  65560. if (newSound.autoplay) {
  65561. newSound.play();
  65562. }
  65563. }
  65564. else {
  65565. window.setTimeout(setBufferAndRun, 300);
  65566. }
  65567. };
  65568. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65569. setBufferAndRun();
  65570. }
  65571. if (parsedSound.position) {
  65572. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65573. newSound.setPosition(soundPosition);
  65574. }
  65575. if (parsedSound.isDirectional) {
  65576. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65577. if (parsedSound.localDirectionToMesh) {
  65578. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65579. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65580. }
  65581. }
  65582. if (parsedSound.connectedMeshId) {
  65583. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65584. if (connectedMesh) {
  65585. newSound.attachToMesh(connectedMesh);
  65586. }
  65587. }
  65588. return newSound;
  65589. };
  65590. return Sound;
  65591. }());
  65592. BABYLON.Sound = Sound;
  65593. })(BABYLON || (BABYLON = {}));
  65594. //# sourceMappingURL=babylon.sound.js.map
  65595. var BABYLON;
  65596. (function (BABYLON) {
  65597. var SoundTrack = /** @class */ (function () {
  65598. function SoundTrack(scene, options) {
  65599. this.id = -1;
  65600. this._isMainTrack = false;
  65601. this._isInitialized = false;
  65602. this._scene = scene;
  65603. this.soundCollection = new Array();
  65604. this._options = options;
  65605. if (!this._isMainTrack) {
  65606. this._scene.soundTracks.push(this);
  65607. this.id = this._scene.soundTracks.length - 1;
  65608. }
  65609. }
  65610. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65611. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65612. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65613. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65614. if (this._options) {
  65615. if (this._options.volume) {
  65616. this._outputAudioNode.gain.value = this._options.volume;
  65617. }
  65618. if (this._options.mainTrack) {
  65619. this._isMainTrack = this._options.mainTrack;
  65620. }
  65621. }
  65622. this._isInitialized = true;
  65623. }
  65624. };
  65625. SoundTrack.prototype.dispose = function () {
  65626. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65627. if (this._connectedAnalyser) {
  65628. this._connectedAnalyser.stopDebugCanvas();
  65629. }
  65630. while (this.soundCollection.length) {
  65631. this.soundCollection[0].dispose();
  65632. }
  65633. if (this._outputAudioNode) {
  65634. this._outputAudioNode.disconnect();
  65635. }
  65636. this._outputAudioNode = null;
  65637. }
  65638. };
  65639. SoundTrack.prototype.AddSound = function (sound) {
  65640. if (!this._isInitialized) {
  65641. this._initializeSoundTrackAudioGraph();
  65642. }
  65643. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65644. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65645. }
  65646. if (sound.soundTrackId) {
  65647. if (sound.soundTrackId === -1) {
  65648. this._scene.mainSoundTrack.RemoveSound(sound);
  65649. }
  65650. else {
  65651. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65652. }
  65653. }
  65654. this.soundCollection.push(sound);
  65655. sound.soundTrackId = this.id;
  65656. };
  65657. SoundTrack.prototype.RemoveSound = function (sound) {
  65658. var index = this.soundCollection.indexOf(sound);
  65659. if (index !== -1) {
  65660. this.soundCollection.splice(index, 1);
  65661. }
  65662. };
  65663. SoundTrack.prototype.setVolume = function (newVolume) {
  65664. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65665. this._outputAudioNode.gain.value = newVolume;
  65666. }
  65667. };
  65668. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65669. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65670. for (var i = 0; i < this.soundCollection.length; i++) {
  65671. this.soundCollection[i].switchPanningModelToHRTF();
  65672. }
  65673. }
  65674. };
  65675. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65676. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65677. for (var i = 0; i < this.soundCollection.length; i++) {
  65678. this.soundCollection[i].switchPanningModelToEqualPower();
  65679. }
  65680. }
  65681. };
  65682. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65683. if (this._connectedAnalyser) {
  65684. this._connectedAnalyser.stopDebugCanvas();
  65685. }
  65686. this._connectedAnalyser = analyser;
  65687. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65688. this._outputAudioNode.disconnect();
  65689. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65690. }
  65691. };
  65692. return SoundTrack;
  65693. }());
  65694. BABYLON.SoundTrack = SoundTrack;
  65695. })(BABYLON || (BABYLON = {}));
  65696. //# sourceMappingURL=babylon.soundtrack.js.map
  65697. var BABYLON;
  65698. (function (BABYLON) {
  65699. /**
  65700. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65701. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65702. */
  65703. var Analyser = /** @class */ (function () {
  65704. /**
  65705. * Creates a new analyser
  65706. * @param scene defines hosting scene
  65707. */
  65708. function Analyser(scene) {
  65709. /**
  65710. * Gets or sets the smoothing
  65711. * @ignorenaming
  65712. */
  65713. this.SMOOTHING = 0.75;
  65714. /**
  65715. * Gets or sets the FFT table size
  65716. * @ignorenaming
  65717. */
  65718. this.FFT_SIZE = 512;
  65719. /**
  65720. * Gets or sets the bar graph amplitude
  65721. * @ignorenaming
  65722. */
  65723. this.BARGRAPHAMPLITUDE = 256;
  65724. /**
  65725. * Gets or sets the position of the debug canvas
  65726. * @ignorenaming
  65727. */
  65728. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65729. /**
  65730. * Gets or sets the debug canvas size
  65731. * @ignorenaming
  65732. */
  65733. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65734. this._scene = scene;
  65735. this._audioEngine = BABYLON.Engine.audioEngine;
  65736. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65737. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65738. this._webAudioAnalyser.minDecibels = -140;
  65739. this._webAudioAnalyser.maxDecibels = 0;
  65740. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65741. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65742. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65743. }
  65744. }
  65745. /**
  65746. * Get the number of data values you will have to play with for the visualization
  65747. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65748. * @returns a number
  65749. */
  65750. Analyser.prototype.getFrequencyBinCount = function () {
  65751. if (this._audioEngine.canUseWebAudio) {
  65752. return this._webAudioAnalyser.frequencyBinCount;
  65753. }
  65754. else {
  65755. return 0;
  65756. }
  65757. };
  65758. /**
  65759. * Gets the current frequency data as a byte array
  65760. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65761. * @returns a Uint8Array
  65762. */
  65763. Analyser.prototype.getByteFrequencyData = function () {
  65764. if (this._audioEngine.canUseWebAudio) {
  65765. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65766. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65767. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65768. }
  65769. return this._byteFreqs;
  65770. };
  65771. /**
  65772. * Gets the current waveform as a byte array
  65773. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65774. * @returns a Uint8Array
  65775. */
  65776. Analyser.prototype.getByteTimeDomainData = function () {
  65777. if (this._audioEngine.canUseWebAudio) {
  65778. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65779. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65780. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65781. }
  65782. return this._byteTime;
  65783. };
  65784. /**
  65785. * Gets the current frequency data as a float array
  65786. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65787. * @returns a Float32Array
  65788. */
  65789. Analyser.prototype.getFloatFrequencyData = function () {
  65790. if (this._audioEngine.canUseWebAudio) {
  65791. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65792. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65793. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65794. }
  65795. return this._floatFreqs;
  65796. };
  65797. /**
  65798. * Renders the debug canvas
  65799. */
  65800. Analyser.prototype.drawDebugCanvas = function () {
  65801. var _this = this;
  65802. if (this._audioEngine.canUseWebAudio) {
  65803. if (!this._debugCanvas) {
  65804. this._debugCanvas = document.createElement("canvas");
  65805. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65806. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65807. this._debugCanvas.style.position = "absolute";
  65808. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65809. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65810. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65811. document.body.appendChild(this._debugCanvas);
  65812. this._registerFunc = function () {
  65813. _this.drawDebugCanvas();
  65814. };
  65815. this._scene.registerBeforeRender(this._registerFunc);
  65816. }
  65817. if (this._registerFunc && this._debugCanvasContext) {
  65818. var workingArray = this.getByteFrequencyData();
  65819. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65820. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65821. // Draw the frequency domain chart.
  65822. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65823. var value = workingArray[i];
  65824. var percent = value / this.BARGRAPHAMPLITUDE;
  65825. var height = this.DEBUGCANVASSIZE.height * percent;
  65826. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65827. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65828. var hue = i / this.getFrequencyBinCount() * 360;
  65829. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65830. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65831. }
  65832. }
  65833. }
  65834. };
  65835. /**
  65836. * Stops rendering the debug canvas and removes it
  65837. */
  65838. Analyser.prototype.stopDebugCanvas = function () {
  65839. if (this._debugCanvas) {
  65840. if (this._registerFunc) {
  65841. this._scene.unregisterBeforeRender(this._registerFunc);
  65842. this._registerFunc = null;
  65843. }
  65844. document.body.removeChild(this._debugCanvas);
  65845. this._debugCanvas = null;
  65846. this._debugCanvasContext = null;
  65847. }
  65848. };
  65849. /**
  65850. * Connects two audio nodes
  65851. * @param inputAudioNode defines first node to connect
  65852. * @param outputAudioNode defines second node to connect
  65853. */
  65854. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65855. if (this._audioEngine.canUseWebAudio) {
  65856. inputAudioNode.connect(this._webAudioAnalyser);
  65857. this._webAudioAnalyser.connect(outputAudioNode);
  65858. }
  65859. };
  65860. /**
  65861. * Releases all associated resources
  65862. */
  65863. Analyser.prototype.dispose = function () {
  65864. if (this._audioEngine.canUseWebAudio) {
  65865. this._webAudioAnalyser.disconnect();
  65866. }
  65867. };
  65868. return Analyser;
  65869. }());
  65870. BABYLON.Analyser = Analyser;
  65871. })(BABYLON || (BABYLON = {}));
  65872. //# sourceMappingURL=babylon.analyser.js.map
  65873. var BABYLON;
  65874. (function (BABYLON) {
  65875. /**
  65876. * Wraps one or more Sound objects and selects one with random weight for playback.
  65877. */
  65878. var WeightedSound = /** @class */ (function () {
  65879. /**
  65880. * Creates a new WeightedSound from the list of sounds given.
  65881. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  65882. * @param sounds Array of Sounds that will be selected from.
  65883. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  65884. */
  65885. function WeightedSound(loop, sounds, weights) {
  65886. var _this = this;
  65887. /** When true a Sound will be selected and played when the current playing Sound completes. */
  65888. this.loop = false;
  65889. this._coneInnerAngle = 360;
  65890. this._coneOuterAngle = 360;
  65891. this._volume = 1;
  65892. /** A Sound is currently playing. */
  65893. this.isPlaying = false;
  65894. /** A Sound is currently paused. */
  65895. this.isPaused = false;
  65896. this._sounds = [];
  65897. this._weights = [];
  65898. if (sounds.length !== weights.length) {
  65899. throw new Error('Sounds length does not equal weights length');
  65900. }
  65901. this.loop = loop;
  65902. this._weights = weights;
  65903. // Normalize the weights
  65904. var weightSum = 0;
  65905. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65906. var weight = weights_1[_i];
  65907. weightSum += weight;
  65908. }
  65909. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65910. for (var i = 0; i < this._weights.length; i++) {
  65911. this._weights[i] *= invWeightSum;
  65912. }
  65913. this._sounds = sounds;
  65914. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65915. var sound = _b[_a];
  65916. sound.onEndedObservable.add(function () { _this._onended(); });
  65917. }
  65918. }
  65919. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65920. /**
  65921. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65922. */
  65923. get: function () {
  65924. return this._coneInnerAngle;
  65925. },
  65926. /**
  65927. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65928. */
  65929. set: function (value) {
  65930. if (value !== this._coneInnerAngle) {
  65931. if (this._coneOuterAngle < value) {
  65932. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65933. return;
  65934. }
  65935. this._coneInnerAngle = value;
  65936. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65937. var sound = _a[_i];
  65938. sound.directionalConeInnerAngle = value;
  65939. }
  65940. }
  65941. },
  65942. enumerable: true,
  65943. configurable: true
  65944. });
  65945. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65946. /**
  65947. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65948. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65949. */
  65950. get: function () {
  65951. return this._coneOuterAngle;
  65952. },
  65953. /**
  65954. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65955. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65956. */
  65957. set: function (value) {
  65958. if (value !== this._coneOuterAngle) {
  65959. if (value < this._coneInnerAngle) {
  65960. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65961. return;
  65962. }
  65963. this._coneOuterAngle = value;
  65964. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65965. var sound = _a[_i];
  65966. sound.directionalConeOuterAngle = value;
  65967. }
  65968. }
  65969. },
  65970. enumerable: true,
  65971. configurable: true
  65972. });
  65973. Object.defineProperty(WeightedSound.prototype, "volume", {
  65974. /**
  65975. * Playback volume.
  65976. */
  65977. get: function () {
  65978. return this._volume;
  65979. },
  65980. /**
  65981. * Playback volume.
  65982. */
  65983. set: function (value) {
  65984. if (value !== this._volume) {
  65985. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65986. var sound = _a[_i];
  65987. sound.setVolume(value);
  65988. }
  65989. }
  65990. },
  65991. enumerable: true,
  65992. configurable: true
  65993. });
  65994. WeightedSound.prototype._onended = function () {
  65995. if (this._currentIndex !== undefined) {
  65996. this._sounds[this._currentIndex].autoplay = false;
  65997. }
  65998. if (this.loop && this.isPlaying) {
  65999. this.play();
  66000. }
  66001. else {
  66002. this.isPlaying = false;
  66003. }
  66004. };
  66005. /**
  66006. * Suspend playback
  66007. */
  66008. WeightedSound.prototype.pause = function () {
  66009. this.isPaused = true;
  66010. if (this._currentIndex !== undefined) {
  66011. this._sounds[this._currentIndex].pause();
  66012. }
  66013. };
  66014. /**
  66015. * Stop playback
  66016. */
  66017. WeightedSound.prototype.stop = function () {
  66018. this.isPlaying = false;
  66019. if (this._currentIndex !== undefined) {
  66020. this._sounds[this._currentIndex].stop();
  66021. }
  66022. };
  66023. /**
  66024. * Start playback.
  66025. * @param startOffset Position the clip head at a specific time in seconds.
  66026. */
  66027. WeightedSound.prototype.play = function (startOffset) {
  66028. if (!this.isPaused) {
  66029. this.stop();
  66030. var randomValue = Math.random();
  66031. var total = 0;
  66032. for (var i = 0; i < this._weights.length; i++) {
  66033. total += this._weights[i];
  66034. if (randomValue <= total) {
  66035. this._currentIndex = i;
  66036. break;
  66037. }
  66038. }
  66039. }
  66040. var sound = this._sounds[this._currentIndex];
  66041. if (sound.isReady()) {
  66042. sound.play(0, this.isPaused ? undefined : startOffset);
  66043. }
  66044. else {
  66045. sound.autoplay = true;
  66046. }
  66047. this.isPlaying = true;
  66048. this.isPaused = false;
  66049. };
  66050. return WeightedSound;
  66051. }());
  66052. BABYLON.WeightedSound = WeightedSound;
  66053. })(BABYLON || (BABYLON = {}));
  66054. //# sourceMappingURL=babylon.weightedsound.js.map
  66055. var BABYLON;
  66056. (function (BABYLON) {
  66057. var CubeTexture = /** @class */ (function (_super) {
  66058. __extends(CubeTexture, _super);
  66059. /**
  66060. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66061. * as prefiltered data.
  66062. * @param rootUrl defines the url of the texture or the root name of the six images
  66063. * @param scene defines the scene the texture is attached to
  66064. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66065. * @param noMipmap defines if mipmaps should be created or not
  66066. * @param files defines the six files to load for the different faces
  66067. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66068. * @param onError defines a callback triggered in case of error during load
  66069. * @param format defines the internal format to use for the texture once loaded
  66070. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66071. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66072. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66073. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66074. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66075. * @return the cube texture
  66076. */
  66077. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66078. if (extensions === void 0) { extensions = null; }
  66079. if (noMipmap === void 0) { noMipmap = false; }
  66080. if (files === void 0) { files = null; }
  66081. if (onLoad === void 0) { onLoad = null; }
  66082. if (onError === void 0) { onError = null; }
  66083. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66084. if (prefiltered === void 0) { prefiltered = false; }
  66085. if (forcedExtension === void 0) { forcedExtension = null; }
  66086. if (createPolynomials === void 0) { createPolynomials = false; }
  66087. if (lodScale === void 0) { lodScale = 0.8; }
  66088. if (lodOffset === void 0) { lodOffset = 0; }
  66089. var _this = _super.call(this, scene) || this;
  66090. /**
  66091. * Gets or sets the center of the bounding box associated with the cube texture
  66092. * It must define where the camera used to render the texture was set
  66093. */
  66094. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66095. _this._rotationY = 0;
  66096. /** @hidden */
  66097. _this._prefiltered = false;
  66098. _this.name = rootUrl;
  66099. _this.url = rootUrl;
  66100. _this._noMipmap = noMipmap;
  66101. _this.hasAlpha = false;
  66102. _this._format = format;
  66103. _this.isCube = true;
  66104. _this._textureMatrix = BABYLON.Matrix.Identity();
  66105. _this._createPolynomials = createPolynomials;
  66106. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66107. if (!rootUrl && !files) {
  66108. return _this;
  66109. }
  66110. var lastDot = rootUrl.lastIndexOf(".");
  66111. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66112. var isDDS = (extension === ".dds");
  66113. var isEnv = (extension === ".env");
  66114. if (isEnv) {
  66115. _this.gammaSpace = false;
  66116. _this._prefiltered = false;
  66117. }
  66118. else {
  66119. _this._prefiltered = prefiltered;
  66120. if (prefiltered) {
  66121. _this.gammaSpace = false;
  66122. }
  66123. }
  66124. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  66125. if (!files) {
  66126. if (!isEnv && !isDDS && !extensions) {
  66127. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  66128. }
  66129. files = [];
  66130. if (extensions) {
  66131. for (var index = 0; index < extensions.length; index++) {
  66132. files.push(rootUrl + extensions[index]);
  66133. }
  66134. }
  66135. }
  66136. _this._files = files;
  66137. if (!_this._texture) {
  66138. if (!scene.useDelayedTextureLoading) {
  66139. if (prefiltered) {
  66140. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  66141. }
  66142. else {
  66143. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  66144. }
  66145. }
  66146. else {
  66147. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  66148. }
  66149. }
  66150. else if (onLoad) {
  66151. if (_this._texture.isReady) {
  66152. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  66153. }
  66154. else {
  66155. _this._texture.onLoadedObservable.add(onLoad);
  66156. }
  66157. }
  66158. return _this;
  66159. }
  66160. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  66161. get: function () {
  66162. return this._boundingBoxSize;
  66163. },
  66164. /**
  66165. * Gets or sets the size of the bounding box associated with the cube texture
  66166. * When defined, the cubemap will switch to local mode
  66167. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66168. * @example https://www.babylonjs-playground.com/#RNASML
  66169. */
  66170. set: function (value) {
  66171. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66172. return;
  66173. }
  66174. this._boundingBoxSize = value;
  66175. var scene = this.getScene();
  66176. if (scene) {
  66177. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66178. }
  66179. },
  66180. enumerable: true,
  66181. configurable: true
  66182. });
  66183. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  66184. /**
  66185. * Gets texture matrix rotation angle around Y axis radians.
  66186. */
  66187. get: function () {
  66188. return this._rotationY;
  66189. },
  66190. /**
  66191. * Sets texture matrix rotation angle around Y axis in radians.
  66192. */
  66193. set: function (value) {
  66194. this._rotationY = value;
  66195. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  66196. },
  66197. enumerable: true,
  66198. configurable: true
  66199. });
  66200. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  66201. var rootUrlKey = "";
  66202. files.forEach(function (url) { return rootUrlKey += url; });
  66203. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  66204. };
  66205. /**
  66206. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  66207. * @param url defines the url of the prefiltered texture
  66208. * @param scene defines the scene the texture is attached to
  66209. * @param forcedExtension defines the extension of the file if different from the url
  66210. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66211. * @return the prefiltered texture
  66212. */
  66213. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  66214. if (forcedExtension === void 0) { forcedExtension = null; }
  66215. if (createPolynomials === void 0) { createPolynomials = true; }
  66216. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  66217. };
  66218. // Methods
  66219. CubeTexture.prototype.delayLoad = function () {
  66220. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66221. return;
  66222. }
  66223. var scene = this.getScene();
  66224. if (!scene) {
  66225. return;
  66226. }
  66227. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66228. this._texture = this._getFromCache(this.url, this._noMipmap);
  66229. if (!this._texture) {
  66230. if (this._prefiltered) {
  66231. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66232. }
  66233. else {
  66234. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66235. }
  66236. }
  66237. };
  66238. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66239. return this._textureMatrix;
  66240. };
  66241. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66242. this._textureMatrix = value;
  66243. };
  66244. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66245. var texture = BABYLON.SerializationHelper.Parse(function () {
  66246. var prefiltered = false;
  66247. if (parsedTexture.prefiltered) {
  66248. prefiltered = parsedTexture.prefiltered;
  66249. }
  66250. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66251. }, parsedTexture, scene);
  66252. // Local Cubemaps
  66253. if (parsedTexture.boundingBoxPosition) {
  66254. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66255. }
  66256. if (parsedTexture.boundingBoxSize) {
  66257. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66258. }
  66259. // Animations
  66260. if (parsedTexture.animations) {
  66261. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66262. var parsedAnimation = parsedTexture.animations[animationIndex];
  66263. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66264. }
  66265. }
  66266. return texture;
  66267. };
  66268. CubeTexture.prototype.clone = function () {
  66269. var _this = this;
  66270. return BABYLON.SerializationHelper.Clone(function () {
  66271. var scene = _this.getScene();
  66272. if (!scene) {
  66273. return _this;
  66274. }
  66275. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66276. }, this);
  66277. };
  66278. __decorate([
  66279. BABYLON.serialize("rotationY")
  66280. ], CubeTexture.prototype, "rotationY", null);
  66281. return CubeTexture;
  66282. }(BABYLON.BaseTexture));
  66283. BABYLON.CubeTexture = CubeTexture;
  66284. })(BABYLON || (BABYLON = {}));
  66285. //# sourceMappingURL=babylon.cubeTexture.js.map
  66286. var BABYLON;
  66287. (function (BABYLON) {
  66288. /**
  66289. * Raw cube texture where the raw buffers are passed in
  66290. */
  66291. var RawCubeTexture = /** @class */ (function (_super) {
  66292. __extends(RawCubeTexture, _super);
  66293. /**
  66294. * Creates a cube texture where the raw buffers are passed in.
  66295. * @param scene defines the scene the texture is attached to
  66296. * @param data defines the array of data to use to create each face
  66297. * @param size defines the size of the textures
  66298. * @param format defines the format of the data
  66299. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66300. * @param generateMipMaps defines if the engine should generate the mip levels
  66301. * @param invertY defines if data must be stored with Y axis inverted
  66302. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66303. * @param compression defines the compression used (null by default)
  66304. */
  66305. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66306. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66307. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66308. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66309. if (invertY === void 0) { invertY = false; }
  66310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66311. if (compression === void 0) { compression = null; }
  66312. var _this = _super.call(this, "", scene) || this;
  66313. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66314. return _this;
  66315. }
  66316. /**
  66317. * Updates the raw cube texture.
  66318. * @param data defines the data to store
  66319. * @param format defines the data format
  66320. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66321. * @param invertY defines if data must be stored with Y axis inverted
  66322. * @param compression defines the compression used (null by default)
  66323. * @param level defines which level of the texture to update
  66324. */
  66325. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66326. if (compression === void 0) { compression = null; }
  66327. if (level === void 0) { level = 0; }
  66328. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66329. };
  66330. /**
  66331. * Updates a raw cube texture with RGBD encoded data.
  66332. * @param data defines the array of data [mipmap][face] to use to create each face
  66333. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66334. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66335. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66336. * @returns a promsie that resolves when the operation is complete
  66337. */
  66338. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66339. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66340. if (lodScale === void 0) { lodScale = 0.8; }
  66341. if (lodOffset === void 0) { lodOffset = 0; }
  66342. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66343. };
  66344. /**
  66345. * Clones the raw cube texture.
  66346. * @return a new cube texture
  66347. */
  66348. RawCubeTexture.prototype.clone = function () {
  66349. var _this = this;
  66350. return BABYLON.SerializationHelper.Clone(function () {
  66351. var scene = _this.getScene();
  66352. var internalTexture = _this._texture;
  66353. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66354. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66355. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66356. }
  66357. return texture;
  66358. }, this);
  66359. };
  66360. /** @hidden */
  66361. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66362. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66363. internalTexture._bufferViewArrayArray = data;
  66364. internalTexture._lodGenerationScale = lodScale;
  66365. internalTexture._lodGenerationOffset = lodOffset;
  66366. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66367. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66368. internalTexture.isReady = true;
  66369. });
  66370. };
  66371. return RawCubeTexture;
  66372. }(BABYLON.CubeTexture));
  66373. BABYLON.RawCubeTexture = RawCubeTexture;
  66374. })(BABYLON || (BABYLON = {}));
  66375. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66376. var BABYLON;
  66377. (function (BABYLON) {
  66378. var RenderTargetTexture = /** @class */ (function (_super) {
  66379. __extends(RenderTargetTexture, _super);
  66380. /**
  66381. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66382. * or used a shadow, depth texture...
  66383. * @param name The friendly name of the texture
  66384. * @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)
  66385. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66386. * @param generateMipMaps True if mip maps need to be generated after render.
  66387. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66388. * @param type The type of the buffer in the RTT (int, half float, float...)
  66389. * @param isCube True if a cube texture needs to be created
  66390. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66391. * @param generateDepthBuffer True to generate a depth buffer
  66392. * @param generateStencilBuffer True to generate a stencil buffer
  66393. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66394. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66395. */
  66396. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66397. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66398. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66399. if (isCube === void 0) { isCube = false; }
  66400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66401. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66402. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66403. if (isMulti === void 0) { isMulti = false; }
  66404. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66405. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66406. _this.isCube = isCube;
  66407. _this.renderParticles = true;
  66408. _this.renderSprites = false;
  66409. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66410. _this.ignoreCameraViewport = false;
  66411. // Events
  66412. /**
  66413. * An event triggered when the texture is unbind.
  66414. */
  66415. _this.onBeforeBindObservable = new BABYLON.Observable();
  66416. /**
  66417. * An event triggered when the texture is unbind.
  66418. */
  66419. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66420. /**
  66421. * An event triggered before rendering the texture
  66422. */
  66423. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66424. /**
  66425. * An event triggered after rendering the texture
  66426. */
  66427. _this.onAfterRenderObservable = new BABYLON.Observable();
  66428. /**
  66429. * An event triggered after the texture clear
  66430. */
  66431. _this.onClearObservable = new BABYLON.Observable();
  66432. _this._currentRefreshId = -1;
  66433. _this._refreshRate = 1;
  66434. _this._samples = 1;
  66435. /**
  66436. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66437. * It must define where the camera used to render the texture is set
  66438. */
  66439. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66440. scene = _this.getScene();
  66441. if (!scene) {
  66442. return _this;
  66443. }
  66444. _this.renderList = new Array();
  66445. _this._engine = scene.getEngine();
  66446. _this.name = name;
  66447. _this.isRenderTarget = true;
  66448. _this._initialSizeParameter = size;
  66449. _this._processSizeParameter(size);
  66450. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66451. });
  66452. _this._generateMipMaps = generateMipMaps ? true : false;
  66453. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66454. // Rendering groups
  66455. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66456. _this._renderingManager._useSceneAutoClearSetup = true;
  66457. if (isMulti) {
  66458. return _this;
  66459. }
  66460. _this._renderTargetOptions = {
  66461. generateMipMaps: generateMipMaps,
  66462. type: type,
  66463. format: format,
  66464. samplingMode: samplingMode,
  66465. generateDepthBuffer: generateDepthBuffer,
  66466. generateStencilBuffer: generateStencilBuffer
  66467. };
  66468. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66469. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66470. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66471. }
  66472. if (isCube) {
  66473. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66474. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66475. _this._textureMatrix = BABYLON.Matrix.Identity();
  66476. }
  66477. else {
  66478. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66479. }
  66480. return _this;
  66481. }
  66482. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66483. get: function () {
  66484. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66485. },
  66486. enumerable: true,
  66487. configurable: true
  66488. });
  66489. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66490. get: function () {
  66491. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66492. },
  66493. enumerable: true,
  66494. configurable: true
  66495. });
  66496. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66497. get: function () {
  66498. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66499. },
  66500. enumerable: true,
  66501. configurable: true
  66502. });
  66503. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66504. /**
  66505. * Use this list to define the list of mesh you want to render.
  66506. */
  66507. get: function () {
  66508. return this._renderList;
  66509. },
  66510. set: function (value) {
  66511. this._renderList = value;
  66512. if (this._renderList) {
  66513. this._hookArray(this._renderList);
  66514. }
  66515. },
  66516. enumerable: true,
  66517. configurable: true
  66518. });
  66519. RenderTargetTexture.prototype._hookArray = function (array) {
  66520. var _this = this;
  66521. var oldPush = array.push;
  66522. array.push = function () {
  66523. var items = [];
  66524. for (var _i = 0; _i < arguments.length; _i++) {
  66525. items[_i] = arguments[_i];
  66526. }
  66527. var result = oldPush.apply(array, items);
  66528. _this.getScene().meshes.forEach(function (mesh) {
  66529. mesh._markSubMeshesAsLightDirty();
  66530. });
  66531. return result;
  66532. };
  66533. var oldSplice = array.splice;
  66534. array.splice = function (index, deleteCount) {
  66535. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66536. _this.getScene().meshes.forEach(function (mesh) {
  66537. mesh._markSubMeshesAsLightDirty();
  66538. });
  66539. return deleted;
  66540. };
  66541. };
  66542. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66543. set: function (callback) {
  66544. if (this._onAfterUnbindObserver) {
  66545. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66546. }
  66547. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66548. },
  66549. enumerable: true,
  66550. configurable: true
  66551. });
  66552. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66553. set: function (callback) {
  66554. if (this._onBeforeRenderObserver) {
  66555. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66556. }
  66557. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66558. },
  66559. enumerable: true,
  66560. configurable: true
  66561. });
  66562. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66563. set: function (callback) {
  66564. if (this._onAfterRenderObserver) {
  66565. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66566. }
  66567. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66568. },
  66569. enumerable: true,
  66570. configurable: true
  66571. });
  66572. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66573. set: function (callback) {
  66574. if (this._onClearObserver) {
  66575. this.onClearObservable.remove(this._onClearObserver);
  66576. }
  66577. this._onClearObserver = this.onClearObservable.add(callback);
  66578. },
  66579. enumerable: true,
  66580. configurable: true
  66581. });
  66582. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66583. get: function () {
  66584. return this._renderTargetOptions;
  66585. },
  66586. enumerable: true,
  66587. configurable: true
  66588. });
  66589. RenderTargetTexture.prototype._onRatioRescale = function () {
  66590. if (this._sizeRatio) {
  66591. this.resize(this._initialSizeParameter);
  66592. }
  66593. };
  66594. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66595. get: function () {
  66596. return this._boundingBoxSize;
  66597. },
  66598. /**
  66599. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66600. * When defined, the cubemap will switch to local mode
  66601. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66602. * @example https://www.babylonjs-playground.com/#RNASML
  66603. */
  66604. set: function (value) {
  66605. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66606. return;
  66607. }
  66608. this._boundingBoxSize = value;
  66609. var scene = this.getScene();
  66610. if (scene) {
  66611. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66612. }
  66613. },
  66614. enumerable: true,
  66615. configurable: true
  66616. });
  66617. /**
  66618. * Creates a depth stencil texture.
  66619. * This is only available in WebGL 2 or with the depth texture extension available.
  66620. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66621. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66622. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66623. */
  66624. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66625. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66626. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66627. if (generateStencil === void 0) { generateStencil = false; }
  66628. if (!this.getScene()) {
  66629. return;
  66630. }
  66631. var engine = this.getScene().getEngine();
  66632. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66633. bilinearFiltering: bilinearFiltering,
  66634. comparisonFunction: comparisonFunction,
  66635. generateStencil: generateStencil,
  66636. isCube: this.isCube
  66637. });
  66638. engine.setFrameBufferDepthStencilTexture(this);
  66639. };
  66640. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66641. if (size.ratio) {
  66642. this._sizeRatio = size.ratio;
  66643. this._size = {
  66644. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66645. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66646. };
  66647. }
  66648. else {
  66649. this._size = size;
  66650. }
  66651. };
  66652. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66653. get: function () {
  66654. return this._samples;
  66655. },
  66656. set: function (value) {
  66657. if (this._samples === value) {
  66658. return;
  66659. }
  66660. var scene = this.getScene();
  66661. if (!scene) {
  66662. return;
  66663. }
  66664. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66665. },
  66666. enumerable: true,
  66667. configurable: true
  66668. });
  66669. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66670. this._currentRefreshId = -1;
  66671. };
  66672. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66673. get: function () {
  66674. return this._refreshRate;
  66675. },
  66676. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66677. set: function (value) {
  66678. this._refreshRate = value;
  66679. this.resetRefreshCounter();
  66680. },
  66681. enumerable: true,
  66682. configurable: true
  66683. });
  66684. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66685. if (!this._postProcessManager) {
  66686. var scene = this.getScene();
  66687. if (!scene) {
  66688. return;
  66689. }
  66690. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66691. this._postProcesses = new Array();
  66692. }
  66693. this._postProcesses.push(postProcess);
  66694. this._postProcesses[0].autoClear = false;
  66695. };
  66696. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66697. if (!this._postProcesses) {
  66698. return;
  66699. }
  66700. if (dispose) {
  66701. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66702. var postProcess = _a[_i];
  66703. postProcess.dispose();
  66704. }
  66705. }
  66706. this._postProcesses = [];
  66707. };
  66708. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66709. if (!this._postProcesses) {
  66710. return;
  66711. }
  66712. var index = this._postProcesses.indexOf(postProcess);
  66713. if (index === -1) {
  66714. return;
  66715. }
  66716. this._postProcesses.splice(index, 1);
  66717. if (this._postProcesses.length > 0) {
  66718. this._postProcesses[0].autoClear = false;
  66719. }
  66720. };
  66721. /** @hidden */
  66722. RenderTargetTexture.prototype._shouldRender = function () {
  66723. if (this._currentRefreshId === -1) { // At least render once
  66724. this._currentRefreshId = 1;
  66725. return true;
  66726. }
  66727. if (this.refreshRate === this._currentRefreshId) {
  66728. this._currentRefreshId = 1;
  66729. return true;
  66730. }
  66731. this._currentRefreshId++;
  66732. return false;
  66733. };
  66734. RenderTargetTexture.prototype.getRenderSize = function () {
  66735. if (this._size.width) {
  66736. return this._size.width;
  66737. }
  66738. return this._size;
  66739. };
  66740. RenderTargetTexture.prototype.getRenderWidth = function () {
  66741. if (this._size.width) {
  66742. return this._size.width;
  66743. }
  66744. return this._size;
  66745. };
  66746. RenderTargetTexture.prototype.getRenderHeight = function () {
  66747. if (this._size.width) {
  66748. return this._size.height;
  66749. }
  66750. return this._size;
  66751. };
  66752. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66753. get: function () {
  66754. return true;
  66755. },
  66756. enumerable: true,
  66757. configurable: true
  66758. });
  66759. RenderTargetTexture.prototype.scale = function (ratio) {
  66760. var newSize = this.getRenderSize() * ratio;
  66761. this.resize(newSize);
  66762. };
  66763. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66764. if (this.isCube) {
  66765. return this._textureMatrix;
  66766. }
  66767. return _super.prototype.getReflectionTextureMatrix.call(this);
  66768. };
  66769. RenderTargetTexture.prototype.resize = function (size) {
  66770. this.releaseInternalTexture();
  66771. var scene = this.getScene();
  66772. if (!scene) {
  66773. return;
  66774. }
  66775. this._processSizeParameter(size);
  66776. if (this.isCube) {
  66777. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66778. }
  66779. else {
  66780. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66781. }
  66782. };
  66783. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66784. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66785. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66786. var scene = this.getScene();
  66787. if (!scene) {
  66788. return;
  66789. }
  66790. var engine = scene.getEngine();
  66791. if (this.useCameraPostProcesses !== undefined) {
  66792. useCameraPostProcess = this.useCameraPostProcesses;
  66793. }
  66794. if (this._waitingRenderList) {
  66795. this.renderList = [];
  66796. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66797. var id = this._waitingRenderList[index];
  66798. var mesh_1 = scene.getMeshByID(id);
  66799. if (mesh_1) {
  66800. this.renderList.push(mesh_1);
  66801. }
  66802. }
  66803. delete this._waitingRenderList;
  66804. }
  66805. // Is predicate defined?
  66806. if (this.renderListPredicate) {
  66807. if (this.renderList) {
  66808. this.renderList.splice(0); // Clear previous renderList
  66809. }
  66810. else {
  66811. this.renderList = [];
  66812. }
  66813. var scene = this.getScene();
  66814. if (!scene) {
  66815. return;
  66816. }
  66817. var sceneMeshes = scene.meshes;
  66818. for (var index = 0; index < sceneMeshes.length; index++) {
  66819. var mesh = sceneMeshes[index];
  66820. if (this.renderListPredicate(mesh)) {
  66821. this.renderList.push(mesh);
  66822. }
  66823. }
  66824. }
  66825. this.onBeforeBindObservable.notifyObservers(this);
  66826. // Set custom projection.
  66827. // Needs to be before binding to prevent changing the aspect ratio.
  66828. var camera;
  66829. if (this.activeCamera) {
  66830. camera = this.activeCamera;
  66831. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66832. if (this.activeCamera !== scene.activeCamera) {
  66833. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66834. }
  66835. }
  66836. else {
  66837. camera = scene.activeCamera;
  66838. if (camera) {
  66839. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66840. }
  66841. }
  66842. // Prepare renderingManager
  66843. this._renderingManager.reset();
  66844. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  66845. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  66846. var sceneRenderId = scene.getRenderId();
  66847. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  66848. var mesh = currentRenderList[meshIndex];
  66849. if (mesh) {
  66850. if (!mesh.isReady(this.refreshRate === 0)) {
  66851. this.resetRefreshCounter();
  66852. continue;
  66853. }
  66854. mesh._preActivateForIntermediateRendering(sceneRenderId);
  66855. var isMasked = void 0;
  66856. if (!this.renderList && camera) {
  66857. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  66858. }
  66859. else {
  66860. isMasked = false;
  66861. }
  66862. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  66863. mesh._activate(sceneRenderId);
  66864. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  66865. var subMesh = mesh.subMeshes[subIndex];
  66866. scene._activeIndices.addCount(subMesh.indexCount, false);
  66867. this._renderingManager.dispatch(subMesh, mesh);
  66868. }
  66869. }
  66870. }
  66871. }
  66872. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  66873. var particleSystem = scene.particleSystems[particleIndex];
  66874. var emitter = particleSystem.emitter;
  66875. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  66876. continue;
  66877. }
  66878. if (currentRenderList.indexOf(emitter) >= 0) {
  66879. this._renderingManager.dispatchParticles(particleSystem);
  66880. }
  66881. }
  66882. if (this.isCube) {
  66883. for (var face = 0; face < 6; face++) {
  66884. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66885. scene.incrementRenderId();
  66886. scene.resetCachedMaterial();
  66887. }
  66888. }
  66889. else {
  66890. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66891. }
  66892. this.onAfterUnbindObservable.notifyObservers(this);
  66893. if (scene.activeCamera) {
  66894. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  66895. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  66896. }
  66897. engine.setViewport(scene.activeCamera.viewport);
  66898. }
  66899. scene.resetCachedMaterial();
  66900. };
  66901. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  66902. var minimum = 128;
  66903. var x = renderDimension * scale;
  66904. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66905. // Ensure we don't exceed the render dimension (while staying POT)
  66906. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66907. };
  66908. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66909. var _this = this;
  66910. if (!this._texture) {
  66911. return;
  66912. }
  66913. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66914. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66915. });
  66916. };
  66917. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66918. var scene = this.getScene();
  66919. if (!scene) {
  66920. return;
  66921. }
  66922. var engine = scene.getEngine();
  66923. if (!this._texture) {
  66924. return;
  66925. }
  66926. // Bind
  66927. if (this._postProcessManager) {
  66928. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66929. }
  66930. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66931. if (this._texture) {
  66932. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66933. }
  66934. }
  66935. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66936. // Clear
  66937. if (this.onClearObservable.hasObservers()) {
  66938. this.onClearObservable.notifyObservers(engine);
  66939. }
  66940. else {
  66941. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66942. }
  66943. if (!this._doNotChangeAspectRatio) {
  66944. scene.updateTransformMatrix(true);
  66945. }
  66946. // Render
  66947. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66948. if (this._postProcessManager) {
  66949. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66950. }
  66951. else if (useCameraPostProcess) {
  66952. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66953. }
  66954. if (!this._doNotChangeAspectRatio) {
  66955. scene.updateTransformMatrix(true);
  66956. }
  66957. // Dump ?
  66958. if (dumpForDebug) {
  66959. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66960. }
  66961. // Unbind
  66962. if (!this.isCube || faceIndex === 5) {
  66963. if (this.isCube) {
  66964. if (faceIndex === 5) {
  66965. engine.generateMipMapsForCubemap(this._texture);
  66966. }
  66967. }
  66968. this.unbindFrameBuffer(engine, faceIndex);
  66969. }
  66970. else {
  66971. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66972. }
  66973. };
  66974. /**
  66975. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66976. * This allowed control for front to back rendering or reversly depending of the special needs.
  66977. *
  66978. * @param renderingGroupId The rendering group id corresponding to its index
  66979. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  66980. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  66981. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  66982. */
  66983. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  66984. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  66985. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  66986. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  66987. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  66988. };
  66989. /**
  66990. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  66991. *
  66992. * @param renderingGroupId The rendering group id corresponding to its index
  66993. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  66994. */
  66995. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  66996. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  66997. this._renderingManager._useSceneAutoClearSetup = false;
  66998. };
  66999. RenderTargetTexture.prototype.clone = function () {
  67000. var textureSize = this.getSize();
  67001. 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);
  67002. // Base texture
  67003. newTexture.hasAlpha = this.hasAlpha;
  67004. newTexture.level = this.level;
  67005. // RenderTarget Texture
  67006. newTexture.coordinatesMode = this.coordinatesMode;
  67007. if (this.renderList) {
  67008. newTexture.renderList = this.renderList.slice(0);
  67009. }
  67010. return newTexture;
  67011. };
  67012. RenderTargetTexture.prototype.serialize = function () {
  67013. if (!this.name) {
  67014. return null;
  67015. }
  67016. var serializationObject = _super.prototype.serialize.call(this);
  67017. serializationObject.renderTargetSize = this.getRenderSize();
  67018. serializationObject.renderList = [];
  67019. if (this.renderList) {
  67020. for (var index = 0; index < this.renderList.length; index++) {
  67021. serializationObject.renderList.push(this.renderList[index].id);
  67022. }
  67023. }
  67024. return serializationObject;
  67025. };
  67026. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67027. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67028. var objBuffer = this.getInternalTexture();
  67029. var scene = this.getScene();
  67030. if (objBuffer && scene) {
  67031. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67032. }
  67033. };
  67034. RenderTargetTexture.prototype.dispose = function () {
  67035. if (this._postProcessManager) {
  67036. this._postProcessManager.dispose();
  67037. this._postProcessManager = null;
  67038. }
  67039. this.clearPostProcesses(true);
  67040. if (this._resizeObserver) {
  67041. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67042. this._resizeObserver = null;
  67043. }
  67044. this.renderList = null;
  67045. // Remove from custom render targets
  67046. var scene = this.getScene();
  67047. if (!scene) {
  67048. return;
  67049. }
  67050. var index = scene.customRenderTargets.indexOf(this);
  67051. if (index >= 0) {
  67052. scene.customRenderTargets.splice(index, 1);
  67053. }
  67054. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67055. var camera = _a[_i];
  67056. index = camera.customRenderTargets.indexOf(this);
  67057. if (index >= 0) {
  67058. camera.customRenderTargets.splice(index, 1);
  67059. }
  67060. }
  67061. _super.prototype.dispose.call(this);
  67062. };
  67063. /** @hidden */
  67064. RenderTargetTexture.prototype._rebuild = function () {
  67065. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67066. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67067. }
  67068. if (this._postProcessManager) {
  67069. this._postProcessManager._rebuild();
  67070. }
  67071. };
  67072. /**
  67073. * Clear the info related to rendering groups preventing retention point in material dispose.
  67074. */
  67075. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67076. if (this._renderingManager) {
  67077. this._renderingManager.freeRenderingGroups();
  67078. }
  67079. };
  67080. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67081. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67082. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67083. return RenderTargetTexture;
  67084. }(BABYLON.Texture));
  67085. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67086. })(BABYLON || (BABYLON = {}));
  67087. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67088. var BABYLON;
  67089. (function (BABYLON) {
  67090. ;
  67091. var MultiRenderTarget = /** @class */ (function (_super) {
  67092. __extends(MultiRenderTarget, _super);
  67093. function MultiRenderTarget(name, size, count, scene, options) {
  67094. var _this = this;
  67095. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67096. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67097. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67098. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67099. _this._engine = scene.getEngine();
  67100. if (!_this.isSupported) {
  67101. _this.dispose();
  67102. return;
  67103. }
  67104. var types = [];
  67105. var samplingModes = [];
  67106. for (var i = 0; i < count; i++) {
  67107. if (options && options.types && options.types[i] !== undefined) {
  67108. types.push(options.types[i]);
  67109. }
  67110. else {
  67111. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67112. }
  67113. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67114. samplingModes.push(options.samplingModes[i]);
  67115. }
  67116. else {
  67117. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67118. }
  67119. }
  67120. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  67121. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  67122. _this._size = size;
  67123. _this._multiRenderTargetOptions = {
  67124. samplingModes: samplingModes,
  67125. generateMipMaps: generateMipMaps,
  67126. generateDepthBuffer: generateDepthBuffer,
  67127. generateStencilBuffer: generateStencilBuffer,
  67128. generateDepthTexture: generateDepthTexture,
  67129. types: types,
  67130. textureCount: count
  67131. };
  67132. _this._createInternalTextures();
  67133. _this._createTextures();
  67134. return _this;
  67135. }
  67136. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  67137. get: function () {
  67138. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  67139. },
  67140. enumerable: true,
  67141. configurable: true
  67142. });
  67143. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  67144. get: function () {
  67145. return this._textures;
  67146. },
  67147. enumerable: true,
  67148. configurable: true
  67149. });
  67150. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  67151. get: function () {
  67152. return this._textures[this._textures.length - 1];
  67153. },
  67154. enumerable: true,
  67155. configurable: true
  67156. });
  67157. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  67158. set: function (wrap) {
  67159. if (this._textures) {
  67160. for (var i = 0; i < this._textures.length; i++) {
  67161. this._textures[i].wrapU = wrap;
  67162. }
  67163. }
  67164. },
  67165. enumerable: true,
  67166. configurable: true
  67167. });
  67168. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  67169. set: function (wrap) {
  67170. if (this._textures) {
  67171. for (var i = 0; i < this._textures.length; i++) {
  67172. this._textures[i].wrapV = wrap;
  67173. }
  67174. }
  67175. },
  67176. enumerable: true,
  67177. configurable: true
  67178. });
  67179. /** @hidden */
  67180. MultiRenderTarget.prototype._rebuild = function () {
  67181. this.releaseInternalTextures();
  67182. this._createInternalTextures();
  67183. for (var i = 0; i < this._internalTextures.length; i++) {
  67184. var texture = this._textures[i];
  67185. texture._texture = this._internalTextures[i];
  67186. }
  67187. // Keeps references to frame buffer and stencil/depth buffer
  67188. this._texture = this._internalTextures[0];
  67189. };
  67190. MultiRenderTarget.prototype._createInternalTextures = function () {
  67191. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  67192. };
  67193. MultiRenderTarget.prototype._createTextures = function () {
  67194. this._textures = [];
  67195. for (var i = 0; i < this._internalTextures.length; i++) {
  67196. var texture = new BABYLON.Texture(null, this.getScene());
  67197. texture._texture = this._internalTextures[i];
  67198. this._textures.push(texture);
  67199. }
  67200. // Keeps references to frame buffer and stencil/depth buffer
  67201. this._texture = this._internalTextures[0];
  67202. };
  67203. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  67204. get: function () {
  67205. return this._samples;
  67206. },
  67207. set: function (value) {
  67208. if (this._samples === value) {
  67209. return;
  67210. }
  67211. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  67212. },
  67213. enumerable: true,
  67214. configurable: true
  67215. });
  67216. MultiRenderTarget.prototype.resize = function (size) {
  67217. this.releaseInternalTextures();
  67218. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  67219. this._createInternalTextures();
  67220. };
  67221. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67222. var _this = this;
  67223. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67224. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67225. });
  67226. };
  67227. MultiRenderTarget.prototype.dispose = function () {
  67228. this.releaseInternalTextures();
  67229. _super.prototype.dispose.call(this);
  67230. };
  67231. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67232. if (!this._internalTextures) {
  67233. return;
  67234. }
  67235. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67236. if (this._internalTextures[i] !== undefined) {
  67237. this._internalTextures[i].dispose();
  67238. this._internalTextures.splice(i, 1);
  67239. }
  67240. }
  67241. };
  67242. return MultiRenderTarget;
  67243. }(BABYLON.RenderTargetTexture));
  67244. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67245. })(BABYLON || (BABYLON = {}));
  67246. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67247. var BABYLON;
  67248. (function (BABYLON) {
  67249. var MirrorTexture = /** @class */ (function (_super) {
  67250. __extends(MirrorTexture, _super);
  67251. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67252. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67254. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67255. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67256. _this.scene = scene;
  67257. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67258. _this._transformMatrix = BABYLON.Matrix.Zero();
  67259. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67260. _this._adaptiveBlurKernel = 0;
  67261. _this._blurKernelX = 0;
  67262. _this._blurKernelY = 0;
  67263. _this._blurRatio = 1.0;
  67264. _this.ignoreCameraViewport = true;
  67265. _this._updateGammaSpace();
  67266. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67267. _this._updateGammaSpace;
  67268. });
  67269. _this.onBeforeRenderObservable.add(function () {
  67270. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67271. _this._savedViewMatrix = scene.getViewMatrix();
  67272. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67273. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67274. scene.clipPlane = _this.mirrorPlane;
  67275. scene.getEngine().cullBackFaces = false;
  67276. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67277. });
  67278. _this.onAfterRenderObservable.add(function () {
  67279. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67280. scene.getEngine().cullBackFaces = true;
  67281. scene._mirroredCameraPosition = null;
  67282. delete scene.clipPlane;
  67283. });
  67284. return _this;
  67285. }
  67286. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67287. get: function () {
  67288. return this._blurRatio;
  67289. },
  67290. set: function (value) {
  67291. if (this._blurRatio === value) {
  67292. return;
  67293. }
  67294. this._blurRatio = value;
  67295. this._preparePostProcesses();
  67296. },
  67297. enumerable: true,
  67298. configurable: true
  67299. });
  67300. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67301. set: function (value) {
  67302. this._adaptiveBlurKernel = value;
  67303. this._autoComputeBlurKernel();
  67304. },
  67305. enumerable: true,
  67306. configurable: true
  67307. });
  67308. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67309. set: function (value) {
  67310. this.blurKernelX = value;
  67311. this.blurKernelY = value;
  67312. },
  67313. enumerable: true,
  67314. configurable: true
  67315. });
  67316. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67317. get: function () {
  67318. return this._blurKernelX;
  67319. },
  67320. set: function (value) {
  67321. if (this._blurKernelX === value) {
  67322. return;
  67323. }
  67324. this._blurKernelX = value;
  67325. this._preparePostProcesses();
  67326. },
  67327. enumerable: true,
  67328. configurable: true
  67329. });
  67330. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67331. get: function () {
  67332. return this._blurKernelY;
  67333. },
  67334. set: function (value) {
  67335. if (this._blurKernelY === value) {
  67336. return;
  67337. }
  67338. this._blurKernelY = value;
  67339. this._preparePostProcesses();
  67340. },
  67341. enumerable: true,
  67342. configurable: true
  67343. });
  67344. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67345. var engine = this.getScene().getEngine();
  67346. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67347. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67348. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67349. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67350. };
  67351. MirrorTexture.prototype._onRatioRescale = function () {
  67352. if (this._sizeRatio) {
  67353. this.resize(this._initialSizeParameter);
  67354. if (!this._adaptiveBlurKernel) {
  67355. this._preparePostProcesses();
  67356. }
  67357. }
  67358. if (this._adaptiveBlurKernel) {
  67359. this._autoComputeBlurKernel();
  67360. }
  67361. };
  67362. MirrorTexture.prototype._updateGammaSpace = function () {
  67363. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67364. };
  67365. MirrorTexture.prototype._preparePostProcesses = function () {
  67366. this.clearPostProcesses(true);
  67367. if (this._blurKernelX && this._blurKernelY) {
  67368. var engine = this.getScene().getEngine();
  67369. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67370. 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);
  67371. this._blurX.autoClear = false;
  67372. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67373. this._blurX.inputTexture = this._texture;
  67374. }
  67375. else {
  67376. this._blurX.alwaysForcePOT = true;
  67377. }
  67378. 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);
  67379. this._blurY.autoClear = false;
  67380. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67381. this.addPostProcess(this._blurX);
  67382. this.addPostProcess(this._blurY);
  67383. }
  67384. else {
  67385. if (this._blurY) {
  67386. this.removePostProcess(this._blurY);
  67387. this._blurY.dispose();
  67388. this._blurY = null;
  67389. }
  67390. if (this._blurX) {
  67391. this.removePostProcess(this._blurX);
  67392. this._blurX.dispose();
  67393. this._blurX = null;
  67394. }
  67395. }
  67396. };
  67397. MirrorTexture.prototype.clone = function () {
  67398. var scene = this.getScene();
  67399. if (!scene) {
  67400. return this;
  67401. }
  67402. var textureSize = this.getSize();
  67403. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67404. // Base texture
  67405. newTexture.hasAlpha = this.hasAlpha;
  67406. newTexture.level = this.level;
  67407. // Mirror Texture
  67408. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67409. if (this.renderList) {
  67410. newTexture.renderList = this.renderList.slice(0);
  67411. }
  67412. return newTexture;
  67413. };
  67414. MirrorTexture.prototype.serialize = function () {
  67415. if (!this.name) {
  67416. return null;
  67417. }
  67418. var serializationObject = _super.prototype.serialize.call(this);
  67419. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67420. return serializationObject;
  67421. };
  67422. MirrorTexture.prototype.dispose = function () {
  67423. _super.prototype.dispose.call(this);
  67424. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67425. };
  67426. return MirrorTexture;
  67427. }(BABYLON.RenderTargetTexture));
  67428. BABYLON.MirrorTexture = MirrorTexture;
  67429. })(BABYLON || (BABYLON = {}));
  67430. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67431. var BABYLON;
  67432. (function (BABYLON) {
  67433. /**
  67434. * Creates a refraction texture used by refraction channel of the standard material.
  67435. * @param name the texture name
  67436. * @param size size of the underlying texture
  67437. * @param scene root scene
  67438. */
  67439. var RefractionTexture = /** @class */ (function (_super) {
  67440. __extends(RefractionTexture, _super);
  67441. function RefractionTexture(name, size, scene, generateMipMaps) {
  67442. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67443. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67444. _this.depth = 2.0;
  67445. _this.onBeforeRenderObservable.add(function () {
  67446. scene.clipPlane = _this.refractionPlane;
  67447. });
  67448. _this.onAfterRenderObservable.add(function () {
  67449. delete scene.clipPlane;
  67450. });
  67451. return _this;
  67452. }
  67453. RefractionTexture.prototype.clone = function () {
  67454. var scene = this.getScene();
  67455. if (!scene) {
  67456. return this;
  67457. }
  67458. var textureSize = this.getSize();
  67459. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67460. // Base texture
  67461. newTexture.hasAlpha = this.hasAlpha;
  67462. newTexture.level = this.level;
  67463. // Refraction Texture
  67464. newTexture.refractionPlane = this.refractionPlane.clone();
  67465. if (this.renderList) {
  67466. newTexture.renderList = this.renderList.slice(0);
  67467. }
  67468. newTexture.depth = this.depth;
  67469. return newTexture;
  67470. };
  67471. RefractionTexture.prototype.serialize = function () {
  67472. if (!this.name) {
  67473. return null;
  67474. }
  67475. var serializationObject = _super.prototype.serialize.call(this);
  67476. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67477. serializationObject.depth = this.depth;
  67478. return serializationObject;
  67479. };
  67480. return RefractionTexture;
  67481. }(BABYLON.RenderTargetTexture));
  67482. BABYLON.RefractionTexture = RefractionTexture;
  67483. })(BABYLON || (BABYLON = {}));
  67484. //# sourceMappingURL=babylon.refractionTexture.js.map
  67485. var BABYLON;
  67486. (function (BABYLON) {
  67487. /**
  67488. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67489. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67490. */
  67491. var DynamicTexture = /** @class */ (function (_super) {
  67492. __extends(DynamicTexture, _super);
  67493. /**
  67494. * Creates a {BABYLON.DynamicTexture}
  67495. * @param name defines the name of the texture
  67496. * @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
  67497. * @param scene defines the scene where you want the texture
  67498. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67499. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67500. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67501. */
  67502. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67503. if (scene === void 0) { scene = null; }
  67504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67505. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67506. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67507. _this.name = name;
  67508. _this._engine = _this.getScene().getEngine();
  67509. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67510. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67511. _this._generateMipMaps = generateMipMaps;
  67512. if (options.getContext) {
  67513. _this._canvas = options;
  67514. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67515. }
  67516. else {
  67517. _this._canvas = document.createElement("canvas");
  67518. if (options.width || options.width === 0) {
  67519. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67520. }
  67521. else {
  67522. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67523. }
  67524. }
  67525. var textureSize = _this.getSize();
  67526. _this._canvas.width = textureSize.width;
  67527. _this._canvas.height = textureSize.height;
  67528. _this._context = _this._canvas.getContext("2d");
  67529. return _this;
  67530. }
  67531. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67532. /**
  67533. * Gets the current state of canRescale
  67534. */
  67535. get: function () {
  67536. return true;
  67537. },
  67538. enumerable: true,
  67539. configurable: true
  67540. });
  67541. DynamicTexture.prototype._recreate = function (textureSize) {
  67542. this._canvas.width = textureSize.width;
  67543. this._canvas.height = textureSize.height;
  67544. this.releaseInternalTexture();
  67545. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67546. };
  67547. /**
  67548. * Scales the texture
  67549. * @param ratio the scale factor to apply to both width and height
  67550. */
  67551. DynamicTexture.prototype.scale = function (ratio) {
  67552. var textureSize = this.getSize();
  67553. textureSize.width *= ratio;
  67554. textureSize.height *= ratio;
  67555. this._recreate(textureSize);
  67556. };
  67557. /**
  67558. * Resizes the texture
  67559. * @param width the new width
  67560. * @param height the new height
  67561. */
  67562. DynamicTexture.prototype.scaleTo = function (width, height) {
  67563. var textureSize = this.getSize();
  67564. textureSize.width = width;
  67565. textureSize.height = height;
  67566. this._recreate(textureSize);
  67567. };
  67568. /**
  67569. * Gets the context of the canvas used by the texture
  67570. * @returns the canvas context of the dynamic texture
  67571. */
  67572. DynamicTexture.prototype.getContext = function () {
  67573. return this._context;
  67574. };
  67575. /**
  67576. * Clears the texture
  67577. */
  67578. DynamicTexture.prototype.clear = function () {
  67579. var size = this.getSize();
  67580. this._context.fillRect(0, 0, size.width, size.height);
  67581. };
  67582. /**
  67583. * Updates the texture
  67584. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67585. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67586. */
  67587. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67588. if (premulAlpha === void 0) { premulAlpha = false; }
  67589. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67590. };
  67591. /**
  67592. * Draws text onto the texture
  67593. * @param text defines the text to be drawn
  67594. * @param x defines the placement of the text from the left
  67595. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67596. * @param font defines the font to be used with font-style, font-size, font-name
  67597. * @param color defines the color used for the text
  67598. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67599. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67600. * @param update defines whether texture is immediately update (default is true)
  67601. */
  67602. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67603. if (update === void 0) { update = true; }
  67604. var size = this.getSize();
  67605. if (clearColor) {
  67606. this._context.fillStyle = clearColor;
  67607. this._context.fillRect(0, 0, size.width, size.height);
  67608. }
  67609. this._context.font = font;
  67610. if (x === null || x === undefined) {
  67611. var textSize = this._context.measureText(text);
  67612. x = (size.width - textSize.width) / 2;
  67613. }
  67614. if (y === null || y === undefined) {
  67615. var fontSize = parseInt((font.replace(/\D/g, '')));
  67616. y = (size.height / 2) + (fontSize / 3.65);
  67617. }
  67618. this._context.fillStyle = color;
  67619. this._context.fillText(text, x, y);
  67620. if (update) {
  67621. this.update(invertY);
  67622. }
  67623. };
  67624. /**
  67625. * Clones the texture
  67626. * @returns the clone of the texture.
  67627. */
  67628. DynamicTexture.prototype.clone = function () {
  67629. var scene = this.getScene();
  67630. if (!scene) {
  67631. return this;
  67632. }
  67633. var textureSize = this.getSize();
  67634. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67635. // Base texture
  67636. newTexture.hasAlpha = this.hasAlpha;
  67637. newTexture.level = this.level;
  67638. // Dynamic Texture
  67639. newTexture.wrapU = this.wrapU;
  67640. newTexture.wrapV = this.wrapV;
  67641. return newTexture;
  67642. };
  67643. /**
  67644. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67645. * @returns a serialized dynamic texture object
  67646. */
  67647. DynamicTexture.prototype.serialize = function () {
  67648. var scene = this.getScene();
  67649. if (scene && !scene.isReady()) {
  67650. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67651. }
  67652. var serializationObject = _super.prototype.serialize.call(this);
  67653. serializationObject.base64String = this._canvas.toDataURL();
  67654. serializationObject.invertY = this._invertY;
  67655. serializationObject.samplingMode = this.samplingMode;
  67656. return serializationObject;
  67657. };
  67658. /** @hidden */
  67659. DynamicTexture.prototype._rebuild = function () {
  67660. this.update();
  67661. };
  67662. return DynamicTexture;
  67663. }(BABYLON.Texture));
  67664. BABYLON.DynamicTexture = DynamicTexture;
  67665. })(BABYLON || (BABYLON = {}));
  67666. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67667. var BABYLON;
  67668. (function (BABYLON) {
  67669. var VideoTexture = /** @class */ (function (_super) {
  67670. __extends(VideoTexture, _super);
  67671. /**
  67672. * Creates a video texture.
  67673. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67674. * @param {string | null} name optional name, will detect from video source, if not defined
  67675. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67676. * @param {BABYLON.Scene} scene is obviously the current scene.
  67677. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67678. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67679. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67680. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67681. */
  67682. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67683. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67684. if (invertY === void 0) { invertY = false; }
  67685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67686. if (settings === void 0) { settings = {
  67687. autoPlay: true,
  67688. loop: true,
  67689. autoUpdateTexture: true,
  67690. }; }
  67691. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67692. _this._onUserActionRequestedObservable = null;
  67693. _this._stillImageCaptured = false;
  67694. _this._poster = false;
  67695. _this._createInternalTexture = function () {
  67696. if (_this._texture != null) {
  67697. if (_this._poster) {
  67698. _this._texture.dispose();
  67699. _this._poster = false;
  67700. }
  67701. else {
  67702. return;
  67703. }
  67704. }
  67705. if (!_this._engine.needPOTTextures ||
  67706. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67707. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67708. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67709. }
  67710. else {
  67711. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67712. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67713. _this._generateMipMaps = false;
  67714. }
  67715. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67716. if (!_this.video.autoplay) {
  67717. var oldHandler_1 = _this.video.onplaying;
  67718. var error_1 = false;
  67719. _this.video.onplaying = function () {
  67720. _this.video.onplaying = oldHandler_1;
  67721. _this._texture.isReady = true;
  67722. _this._updateInternalTexture();
  67723. if (!error_1) {
  67724. _this.video.pause();
  67725. }
  67726. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67727. _this.onLoadObservable.notifyObservers(_this);
  67728. }
  67729. };
  67730. var playing = _this.video.play();
  67731. if (playing) {
  67732. playing.then(function () {
  67733. // Everything is good.
  67734. })
  67735. .catch(function () {
  67736. error_1 = true;
  67737. // On Chrome for instance, new policies might prevent playing without user interaction.
  67738. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67739. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67740. }
  67741. });
  67742. }
  67743. else {
  67744. _this.video.onplaying = oldHandler_1;
  67745. _this._texture.isReady = true;
  67746. _this._updateInternalTexture();
  67747. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67748. _this.onLoadObservable.notifyObservers(_this);
  67749. }
  67750. }
  67751. }
  67752. else {
  67753. _this._texture.isReady = true;
  67754. _this._updateInternalTexture();
  67755. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67756. _this.onLoadObservable.notifyObservers(_this);
  67757. }
  67758. }
  67759. };
  67760. _this.reset = function () {
  67761. if (_this._texture == null) {
  67762. return;
  67763. }
  67764. if (!_this._poster) {
  67765. _this._texture.dispose();
  67766. _this._texture = null;
  67767. }
  67768. };
  67769. _this._updateInternalTexture = function (e) {
  67770. if (_this._texture == null || !_this._texture.isReady) {
  67771. return;
  67772. }
  67773. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67774. return;
  67775. }
  67776. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67777. };
  67778. _this._engine = _this.getScene().getEngine();
  67779. _this._generateMipMaps = generateMipMaps;
  67780. _this._samplingMode = samplingMode;
  67781. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67782. _this.name = name || _this._getName(src);
  67783. _this.video = _this._getVideo(src);
  67784. if (settings.poster) {
  67785. _this.video.poster = settings.poster;
  67786. }
  67787. if (settings.autoPlay !== undefined) {
  67788. _this.video.autoplay = settings.autoPlay;
  67789. }
  67790. if (settings.loop !== undefined) {
  67791. _this.video.loop = settings.loop;
  67792. }
  67793. _this.video.setAttribute("playsinline", "");
  67794. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67795. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67796. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67797. _this.video.addEventListener("emptied", _this.reset);
  67798. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67799. _this._createInternalTexture();
  67800. }
  67801. if (settings.poster) {
  67802. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67803. _this._poster = true;
  67804. }
  67805. return _this;
  67806. }
  67807. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67808. get: function () {
  67809. if (!this._onUserActionRequestedObservable) {
  67810. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67811. }
  67812. return this._onUserActionRequestedObservable;
  67813. },
  67814. enumerable: true,
  67815. configurable: true
  67816. });
  67817. VideoTexture.prototype._getName = function (src) {
  67818. if (src instanceof HTMLVideoElement) {
  67819. return src.currentSrc;
  67820. }
  67821. if (typeof src === "object") {
  67822. return src.toString();
  67823. }
  67824. return src;
  67825. };
  67826. ;
  67827. VideoTexture.prototype._getVideo = function (src) {
  67828. if (src instanceof HTMLVideoElement) {
  67829. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67830. return src;
  67831. }
  67832. var video = document.createElement("video");
  67833. if (typeof src === "string") {
  67834. BABYLON.Tools.SetCorsBehavior(src, video);
  67835. video.src = src;
  67836. }
  67837. else {
  67838. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67839. src.forEach(function (url) {
  67840. var source = document.createElement("source");
  67841. source.src = url;
  67842. video.appendChild(source);
  67843. });
  67844. }
  67845. return video;
  67846. };
  67847. ;
  67848. /**
  67849. * @hidden Internal method to initiate `update`.
  67850. */
  67851. VideoTexture.prototype._rebuild = function () {
  67852. this.update();
  67853. };
  67854. /**
  67855. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  67856. */
  67857. VideoTexture.prototype.update = function () {
  67858. if (!this.autoUpdateTexture) {
  67859. // Expecting user to call `updateTexture` manually
  67860. return;
  67861. }
  67862. this.updateTexture(true);
  67863. };
  67864. /**
  67865. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  67866. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  67867. */
  67868. VideoTexture.prototype.updateTexture = function (isVisible) {
  67869. if (!isVisible) {
  67870. return;
  67871. }
  67872. if (this.video.paused && this._stillImageCaptured) {
  67873. return;
  67874. }
  67875. this._stillImageCaptured = true;
  67876. this._updateInternalTexture();
  67877. };
  67878. /**
  67879. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  67880. * @param url New url.
  67881. */
  67882. VideoTexture.prototype.updateURL = function (url) {
  67883. this.video.src = url;
  67884. };
  67885. VideoTexture.prototype.dispose = function () {
  67886. _super.prototype.dispose.call(this);
  67887. if (this._onUserActionRequestedObservable) {
  67888. this._onUserActionRequestedObservable.clear();
  67889. this._onUserActionRequestedObservable = null;
  67890. }
  67891. this.video.removeEventListener("canplay", this._createInternalTexture);
  67892. this.video.removeEventListener("paused", this._updateInternalTexture);
  67893. this.video.removeEventListener("seeked", this._updateInternalTexture);
  67894. this.video.removeEventListener("emptied", this.reset);
  67895. this.video.pause();
  67896. };
  67897. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  67898. var video = document.createElement("video");
  67899. video.setAttribute('autoplay', '');
  67900. video.setAttribute('muted', '');
  67901. video.setAttribute('playsinline', '');
  67902. var constraintsDeviceId;
  67903. if (constraints && constraints.deviceId) {
  67904. constraintsDeviceId = {
  67905. exact: constraints.deviceId,
  67906. };
  67907. }
  67908. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67909. if (navigator.mediaDevices) {
  67910. navigator.mediaDevices.getUserMedia({ video: constraints })
  67911. .then(function (stream) {
  67912. if (video.mozSrcObject !== undefined) {
  67913. // hack for Firefox < 19
  67914. video.mozSrcObject = stream;
  67915. }
  67916. else {
  67917. video.srcObject = stream;
  67918. }
  67919. var onPlaying = function () {
  67920. if (onReady) {
  67921. onReady(new VideoTexture("video", video, scene, true, true));
  67922. }
  67923. video.removeEventListener("playing", onPlaying);
  67924. };
  67925. video.addEventListener("playing", onPlaying);
  67926. video.play();
  67927. })
  67928. .catch(function (err) {
  67929. BABYLON.Tools.Error(err.name);
  67930. });
  67931. }
  67932. else {
  67933. navigator.getUserMedia =
  67934. navigator.getUserMedia ||
  67935. navigator.webkitGetUserMedia ||
  67936. navigator.mozGetUserMedia ||
  67937. navigator.msGetUserMedia;
  67938. if (navigator.getUserMedia) {
  67939. navigator.getUserMedia({
  67940. video: {
  67941. deviceId: constraintsDeviceId,
  67942. width: {
  67943. min: (constraints && constraints.minWidth) || 256,
  67944. max: (constraints && constraints.maxWidth) || 640,
  67945. },
  67946. height: {
  67947. min: (constraints && constraints.minHeight) || 256,
  67948. max: (constraints && constraints.maxHeight) || 480,
  67949. },
  67950. },
  67951. }, function (stream) {
  67952. if (video.mozSrcObject !== undefined) {
  67953. // hack for Firefox < 19
  67954. video.mozSrcObject = stream;
  67955. }
  67956. else {
  67957. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67958. }
  67959. video.play();
  67960. if (onReady) {
  67961. onReady(new VideoTexture("video", video, scene, true, true));
  67962. }
  67963. }, function (e) {
  67964. BABYLON.Tools.Error(e.name);
  67965. });
  67966. }
  67967. }
  67968. };
  67969. return VideoTexture;
  67970. }(BABYLON.Texture));
  67971. BABYLON.VideoTexture = VideoTexture;
  67972. })(BABYLON || (BABYLON = {}));
  67973. //# sourceMappingURL=babylon.videoTexture.js.map
  67974. var BABYLON;
  67975. (function (BABYLON) {
  67976. var RawTexture = /** @class */ (function (_super) {
  67977. __extends(RawTexture, _super);
  67978. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  67979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67980. if (invertY === void 0) { invertY = false; }
  67981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67982. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67983. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67984. _this.format = format;
  67985. _this._engine = scene.getEngine();
  67986. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  67987. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67988. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67989. return _this;
  67990. }
  67991. RawTexture.prototype.update = function (data) {
  67992. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67993. };
  67994. // Statics
  67995. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67996. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67997. if (invertY === void 0) { invertY = false; }
  67998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67999. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68000. };
  68001. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68002. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68003. if (invertY === void 0) { invertY = false; }
  68004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68005. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68006. };
  68007. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68008. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68009. if (invertY === void 0) { invertY = false; }
  68010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68011. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68012. };
  68013. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68014. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68015. if (invertY === void 0) { invertY = false; }
  68016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68017. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68018. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68019. };
  68020. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68021. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68022. if (invertY === void 0) { invertY = false; }
  68023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68024. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68025. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68026. };
  68027. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68028. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68029. if (invertY === void 0) { invertY = false; }
  68030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68031. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68032. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68033. };
  68034. return RawTexture;
  68035. }(BABYLON.Texture));
  68036. BABYLON.RawTexture = RawTexture;
  68037. })(BABYLON || (BABYLON = {}));
  68038. //# sourceMappingURL=babylon.rawTexture.js.map
  68039. var BABYLON;
  68040. (function (BABYLON) {
  68041. /**
  68042. * Class used to store 3D textures containing user data
  68043. */
  68044. var RawTexture3D = /** @class */ (function (_super) {
  68045. __extends(RawTexture3D, _super);
  68046. /**
  68047. * Create a new RawTexture3D
  68048. * @param data defines the data of the texture
  68049. * @param width defines the width of the texture
  68050. * @param height defines the height of the texture
  68051. * @param depth defines the depth of the texture
  68052. * @param format defines the texture format to use
  68053. * @param scene defines the hosting scene
  68054. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68055. * @param invertY defines if texture must be stored with Y axis inverted
  68056. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68057. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68058. */
  68059. function RawTexture3D(data, width, height, depth,
  68060. /** Gets or sets the texture format to use */
  68061. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68062. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68063. if (invertY === void 0) { invertY = false; }
  68064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68065. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68066. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68067. _this.format = format;
  68068. _this._engine = scene.getEngine();
  68069. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68070. _this.is3D = true;
  68071. return _this;
  68072. }
  68073. /**
  68074. * Update the texture with new data
  68075. * @param data defines the data to store in the texture
  68076. */
  68077. RawTexture3D.prototype.update = function (data) {
  68078. if (!this._texture) {
  68079. return;
  68080. }
  68081. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68082. };
  68083. return RawTexture3D;
  68084. }(BABYLON.Texture));
  68085. BABYLON.RawTexture3D = RawTexture3D;
  68086. })(BABYLON || (BABYLON = {}));
  68087. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68088. var BABYLON;
  68089. (function (BABYLON) {
  68090. /**
  68091. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68092. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68093. */
  68094. var PostProcessManager = /** @class */ (function () {
  68095. /**
  68096. * Creates a new instance PostProcess
  68097. * @param scene The scene that the post process is associated with.
  68098. */
  68099. function PostProcessManager(scene) {
  68100. this._vertexBuffers = {};
  68101. this._scene = scene;
  68102. }
  68103. PostProcessManager.prototype._prepareBuffers = function () {
  68104. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68105. return;
  68106. }
  68107. // VBO
  68108. var vertices = [];
  68109. vertices.push(1, 1);
  68110. vertices.push(-1, 1);
  68111. vertices.push(-1, -1);
  68112. vertices.push(1, -1);
  68113. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68114. this._buildIndexBuffer();
  68115. };
  68116. PostProcessManager.prototype._buildIndexBuffer = function () {
  68117. // Indices
  68118. var indices = [];
  68119. indices.push(0);
  68120. indices.push(1);
  68121. indices.push(2);
  68122. indices.push(0);
  68123. indices.push(2);
  68124. indices.push(3);
  68125. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  68126. };
  68127. /**
  68128. * Rebuilds the vertex buffers of the manager.
  68129. * @hidden
  68130. */
  68131. PostProcessManager.prototype._rebuild = function () {
  68132. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68133. if (!vb) {
  68134. return;
  68135. }
  68136. vb._rebuild();
  68137. this._buildIndexBuffer();
  68138. };
  68139. // Methods
  68140. /**
  68141. * Prepares a frame to be run through a post process.
  68142. * @param sourceTexture The input texture to the post procesess. (default: null)
  68143. * @param postProcesses An array of post processes to be run. (default: null)
  68144. * @returns True if the post processes were able to be run.
  68145. * @hidden
  68146. */
  68147. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  68148. if (sourceTexture === void 0) { sourceTexture = null; }
  68149. if (postProcesses === void 0) { postProcesses = null; }
  68150. var camera = this._scene.activeCamera;
  68151. if (!camera) {
  68152. return false;
  68153. }
  68154. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68155. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68156. return false;
  68157. }
  68158. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  68159. return true;
  68160. };
  68161. /**
  68162. * Manually render a set of post processes to a texture.
  68163. * @param postProcesses An array of post processes to be run.
  68164. * @param targetTexture The target texture to render to.
  68165. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  68166. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  68167. * @param lodLevel defines which lod of the texture to render to
  68168. */
  68169. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  68170. if (targetTexture === void 0) { targetTexture = null; }
  68171. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68172. if (faceIndex === void 0) { faceIndex = 0; }
  68173. if (lodLevel === void 0) { lodLevel = 0; }
  68174. var engine = this._scene.getEngine();
  68175. for (var index = 0; index < postProcesses.length; index++) {
  68176. if (index < postProcesses.length - 1) {
  68177. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  68178. }
  68179. else {
  68180. if (targetTexture) {
  68181. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  68182. }
  68183. else {
  68184. engine.restoreDefaultFramebuffer();
  68185. }
  68186. }
  68187. var pp = postProcesses[index];
  68188. var effect = pp.apply();
  68189. if (effect) {
  68190. pp.onBeforeRenderObservable.notifyObservers(effect);
  68191. // VBOs
  68192. this._prepareBuffers();
  68193. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68194. // Draw order
  68195. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68196. pp.onAfterRenderObservable.notifyObservers(effect);
  68197. }
  68198. }
  68199. // Restore depth buffer
  68200. engine.setDepthBuffer(true);
  68201. engine.setDepthWrite(true);
  68202. };
  68203. /**
  68204. * Finalize the result of the output of the postprocesses.
  68205. * @param doNotPresent If true the result will not be displayed to the screen.
  68206. * @param targetTexture The target texture to render to.
  68207. * @param faceIndex The index of the face to bind the target texture to.
  68208. * @param postProcesses The array of post processes to render.
  68209. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  68210. * @hidden
  68211. */
  68212. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  68213. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68214. var camera = this._scene.activeCamera;
  68215. if (!camera) {
  68216. return;
  68217. }
  68218. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68219. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68220. return;
  68221. }
  68222. var engine = this._scene.getEngine();
  68223. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68224. var pp = postProcesses[index];
  68225. if (index < len - 1) {
  68226. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68227. }
  68228. else {
  68229. if (targetTexture) {
  68230. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68231. pp._outputTexture = targetTexture;
  68232. }
  68233. else {
  68234. engine.restoreDefaultFramebuffer();
  68235. pp._outputTexture = null;
  68236. }
  68237. }
  68238. if (doNotPresent) {
  68239. break;
  68240. }
  68241. var effect = pp.apply();
  68242. if (effect) {
  68243. pp.onBeforeRenderObservable.notifyObservers(effect);
  68244. // VBOs
  68245. this._prepareBuffers();
  68246. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68247. // Draw order
  68248. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68249. pp.onAfterRenderObservable.notifyObservers(effect);
  68250. }
  68251. }
  68252. // Restore states
  68253. engine.setDepthBuffer(true);
  68254. engine.setDepthWrite(true);
  68255. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68256. };
  68257. /**
  68258. * Disposes of the post process manager.
  68259. */
  68260. PostProcessManager.prototype.dispose = function () {
  68261. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68262. if (buffer) {
  68263. buffer.dispose();
  68264. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68265. }
  68266. if (this._indexBuffer) {
  68267. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68268. this._indexBuffer = null;
  68269. }
  68270. };
  68271. return PostProcessManager;
  68272. }());
  68273. BABYLON.PostProcessManager = PostProcessManager;
  68274. })(BABYLON || (BABYLON = {}));
  68275. //# sourceMappingURL=babylon.postProcessManager.js.map
  68276. var BABYLON;
  68277. (function (BABYLON) {
  68278. /**
  68279. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68280. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68281. */
  68282. var PostProcess = /** @class */ (function () {
  68283. /**
  68284. * Creates a new instance PostProcess
  68285. * @param name The name of the PostProcess.
  68286. * @param fragmentUrl The url of the fragment shader to be used.
  68287. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68288. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68289. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68290. * @param camera The camera to apply the render pass to.
  68291. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68292. * @param engine The engine which the post process will be applied. (default: current engine)
  68293. * @param reusable If the post process can be reused on the same frame. (default: false)
  68294. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68295. * @param textureType Type of textures used when performing the post process. (default: 0)
  68296. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68297. * @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
  68298. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68299. */
  68300. function PostProcess(
  68301. /** Name of the PostProcess. */
  68302. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68303. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68304. if (defines === void 0) { defines = null; }
  68305. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68306. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68307. if (blockCompilation === void 0) { blockCompilation = false; }
  68308. this.name = name;
  68309. /**
  68310. * Width of the texture to apply the post process on
  68311. */
  68312. this.width = -1;
  68313. /**
  68314. * Height of the texture to apply the post process on
  68315. */
  68316. this.height = -1;
  68317. /**
  68318. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68319. * @hidden
  68320. */
  68321. this._outputTexture = null;
  68322. /**
  68323. * If the buffer needs to be cleared before applying the post process. (default: true)
  68324. * Should be set to false if shader will overwrite all previous pixels.
  68325. */
  68326. this.autoClear = true;
  68327. /**
  68328. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68329. */
  68330. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68331. /**
  68332. * Animations to be used for the post processing
  68333. */
  68334. this.animations = new Array();
  68335. /**
  68336. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68337. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68338. */
  68339. this.enablePixelPerfectMode = false;
  68340. /**
  68341. * Force the postprocess to be applied without taking in account viewport
  68342. */
  68343. this.forceFullscreenViewport = true;
  68344. /**
  68345. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68346. *
  68347. * | Value | Type | Description |
  68348. * | ----- | ----------------------------------- | ----------- |
  68349. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68350. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68351. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68352. *
  68353. */
  68354. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68355. /**
  68356. * Force textures to be a power of two (default: false)
  68357. */
  68358. this.alwaysForcePOT = false;
  68359. this._samples = 1;
  68360. /**
  68361. * Modify the scale of the post process to be the same as the viewport (default: false)
  68362. */
  68363. this.adaptScaleToCurrentViewport = false;
  68364. this._reusable = false;
  68365. /**
  68366. * Smart array of input and output textures for the post process.
  68367. * @hidden
  68368. */
  68369. this._textures = new BABYLON.SmartArray(2);
  68370. /**
  68371. * The index in _textures that corresponds to the output texture.
  68372. * @hidden
  68373. */
  68374. this._currentRenderTextureInd = 0;
  68375. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68376. this._texelSize = BABYLON.Vector2.Zero();
  68377. // Events
  68378. /**
  68379. * An event triggered when the postprocess is activated.
  68380. */
  68381. this.onActivateObservable = new BABYLON.Observable();
  68382. /**
  68383. * An event triggered when the postprocess changes its size.
  68384. */
  68385. this.onSizeChangedObservable = new BABYLON.Observable();
  68386. /**
  68387. * An event triggered when the postprocess applies its effect.
  68388. */
  68389. this.onApplyObservable = new BABYLON.Observable();
  68390. /**
  68391. * An event triggered before rendering the postprocess
  68392. */
  68393. this.onBeforeRenderObservable = new BABYLON.Observable();
  68394. /**
  68395. * An event triggered after rendering the postprocess
  68396. */
  68397. this.onAfterRenderObservable = new BABYLON.Observable();
  68398. if (camera != null) {
  68399. this._camera = camera;
  68400. this._scene = camera.getScene();
  68401. camera.attachPostProcess(this);
  68402. this._engine = this._scene.getEngine();
  68403. this._scene.postProcesses.push(this);
  68404. }
  68405. else if (engine) {
  68406. this._engine = engine;
  68407. this._engine.postProcesses.push(this);
  68408. }
  68409. this._options = options;
  68410. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68411. this._reusable = reusable || false;
  68412. this._textureType = textureType;
  68413. this._samplers = samplers || [];
  68414. this._samplers.push("textureSampler");
  68415. this._fragmentUrl = fragmentUrl;
  68416. this._vertexUrl = vertexUrl;
  68417. this._parameters = parameters || [];
  68418. this._parameters.push("scale");
  68419. this._indexParameters = indexParameters;
  68420. if (!blockCompilation) {
  68421. this.updateEffect(defines);
  68422. }
  68423. }
  68424. Object.defineProperty(PostProcess.prototype, "samples", {
  68425. /**
  68426. * Number of sample textures (default: 1)
  68427. */
  68428. get: function () {
  68429. return this._samples;
  68430. },
  68431. set: function (n) {
  68432. var _this = this;
  68433. this._samples = n;
  68434. this._textures.forEach(function (texture) {
  68435. if (texture.samples !== _this._samples) {
  68436. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68437. }
  68438. });
  68439. },
  68440. enumerable: true,
  68441. configurable: true
  68442. });
  68443. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68444. /**
  68445. * A function that is added to the onActivateObservable
  68446. */
  68447. set: function (callback) {
  68448. if (this._onActivateObserver) {
  68449. this.onActivateObservable.remove(this._onActivateObserver);
  68450. }
  68451. if (callback) {
  68452. this._onActivateObserver = this.onActivateObservable.add(callback);
  68453. }
  68454. },
  68455. enumerable: true,
  68456. configurable: true
  68457. });
  68458. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68459. /**
  68460. * A function that is added to the onSizeChangedObservable
  68461. */
  68462. set: function (callback) {
  68463. if (this._onSizeChangedObserver) {
  68464. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68465. }
  68466. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68467. },
  68468. enumerable: true,
  68469. configurable: true
  68470. });
  68471. Object.defineProperty(PostProcess.prototype, "onApply", {
  68472. /**
  68473. * A function that is added to the onApplyObservable
  68474. */
  68475. set: function (callback) {
  68476. if (this._onApplyObserver) {
  68477. this.onApplyObservable.remove(this._onApplyObserver);
  68478. }
  68479. this._onApplyObserver = this.onApplyObservable.add(callback);
  68480. },
  68481. enumerable: true,
  68482. configurable: true
  68483. });
  68484. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68485. /**
  68486. * A function that is added to the onBeforeRenderObservable
  68487. */
  68488. set: function (callback) {
  68489. if (this._onBeforeRenderObserver) {
  68490. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68491. }
  68492. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68493. },
  68494. enumerable: true,
  68495. configurable: true
  68496. });
  68497. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68498. /**
  68499. * A function that is added to the onAfterRenderObservable
  68500. */
  68501. set: function (callback) {
  68502. if (this._onAfterRenderObserver) {
  68503. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68504. }
  68505. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68506. },
  68507. enumerable: true,
  68508. configurable: true
  68509. });
  68510. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68511. /**
  68512. * 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
  68513. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68514. */
  68515. get: function () {
  68516. return this._textures.data[this._currentRenderTextureInd];
  68517. },
  68518. set: function (value) {
  68519. this._forcedOutputTexture = value;
  68520. },
  68521. enumerable: true,
  68522. configurable: true
  68523. });
  68524. /**
  68525. * Gets the camera which post process is applied to.
  68526. * @returns The camera the post process is applied to.
  68527. */
  68528. PostProcess.prototype.getCamera = function () {
  68529. return this._camera;
  68530. };
  68531. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68532. /**
  68533. * Gets the texel size of the postprocess.
  68534. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68535. */
  68536. get: function () {
  68537. if (this._shareOutputWithPostProcess) {
  68538. return this._shareOutputWithPostProcess.texelSize;
  68539. }
  68540. if (this._forcedOutputTexture) {
  68541. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68542. }
  68543. return this._texelSize;
  68544. },
  68545. enumerable: true,
  68546. configurable: true
  68547. });
  68548. /**
  68549. * Gets the engine which this post process belongs to.
  68550. * @returns The engine the post process was enabled with.
  68551. */
  68552. PostProcess.prototype.getEngine = function () {
  68553. return this._engine;
  68554. };
  68555. /**
  68556. * The effect that is created when initializing the post process.
  68557. * @returns The created effect corrisponding the the postprocess.
  68558. */
  68559. PostProcess.prototype.getEffect = function () {
  68560. return this._effect;
  68561. };
  68562. /**
  68563. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68564. * @param postProcess The post process to share the output with.
  68565. * @returns This post process.
  68566. */
  68567. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68568. this._disposeTextures();
  68569. this._shareOutputWithPostProcess = postProcess;
  68570. return this;
  68571. };
  68572. /**
  68573. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68574. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68575. */
  68576. PostProcess.prototype.useOwnOutput = function () {
  68577. if (this._textures.length == 0) {
  68578. this._textures = new BABYLON.SmartArray(2);
  68579. }
  68580. this._shareOutputWithPostProcess = null;
  68581. };
  68582. /**
  68583. * Updates the effect with the current post process compile time values and recompiles the shader.
  68584. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68585. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68586. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68587. * @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
  68588. * @param onCompiled Called when the shader has been compiled.
  68589. * @param onError Called if there is an error when compiling a shader.
  68590. */
  68591. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68592. if (defines === void 0) { defines = null; }
  68593. if (uniforms === void 0) { uniforms = null; }
  68594. if (samplers === void 0) { samplers = null; }
  68595. 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);
  68596. };
  68597. /**
  68598. * The post process is reusable if it can be used multiple times within one frame.
  68599. * @returns If the post process is reusable
  68600. */
  68601. PostProcess.prototype.isReusable = function () {
  68602. return this._reusable;
  68603. };
  68604. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68605. PostProcess.prototype.markTextureDirty = function () {
  68606. this.width = -1;
  68607. };
  68608. /**
  68609. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68610. * 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.
  68611. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68612. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68613. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68614. * @returns The target texture that was bound to be written to.
  68615. */
  68616. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68617. var _this = this;
  68618. if (sourceTexture === void 0) { sourceTexture = null; }
  68619. camera = camera || this._camera;
  68620. var scene = camera.getScene();
  68621. var engine = scene.getEngine();
  68622. var maxSize = engine.getCaps().maxTextureSize;
  68623. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68624. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68625. // 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
  68626. var webVRCamera = camera.parent;
  68627. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68628. requiredWidth /= 2;
  68629. }
  68630. var desiredWidth = (this._options.width || requiredWidth);
  68631. var desiredHeight = this._options.height || requiredHeight;
  68632. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68633. if (this.adaptScaleToCurrentViewport) {
  68634. var currentViewport = engine.currentViewport;
  68635. if (currentViewport) {
  68636. desiredWidth *= currentViewport.width;
  68637. desiredHeight *= currentViewport.height;
  68638. }
  68639. }
  68640. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68641. if (!this._options.width) {
  68642. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68643. }
  68644. if (!this._options.height) {
  68645. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68646. }
  68647. }
  68648. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68649. if (this._textures.length > 0) {
  68650. for (var i = 0; i < this._textures.length; i++) {
  68651. this._engine._releaseTexture(this._textures.data[i]);
  68652. }
  68653. this._textures.reset();
  68654. }
  68655. this.width = desiredWidth;
  68656. this.height = desiredHeight;
  68657. var textureSize = { width: this.width, height: this.height };
  68658. var textureOptions = {
  68659. generateMipMaps: false,
  68660. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68661. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68662. samplingMode: this.renderTargetSamplingMode,
  68663. type: this._textureType
  68664. };
  68665. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68666. if (this._reusable) {
  68667. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68668. }
  68669. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68670. this.onSizeChangedObservable.notifyObservers(this);
  68671. }
  68672. this._textures.forEach(function (texture) {
  68673. if (texture.samples !== _this.samples) {
  68674. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68675. }
  68676. });
  68677. }
  68678. var target;
  68679. if (this._shareOutputWithPostProcess) {
  68680. target = this._shareOutputWithPostProcess.inputTexture;
  68681. }
  68682. else if (this._forcedOutputTexture) {
  68683. target = this._forcedOutputTexture;
  68684. this.width = this._forcedOutputTexture.width;
  68685. this.height = this._forcedOutputTexture.height;
  68686. }
  68687. else {
  68688. target = this.inputTexture;
  68689. }
  68690. // Bind the input of this post process to be used as the output of the previous post process.
  68691. if (this.enablePixelPerfectMode) {
  68692. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68693. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68694. }
  68695. else {
  68696. this._scaleRatio.copyFromFloats(1, 1);
  68697. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68698. }
  68699. this.onActivateObservable.notifyObservers(camera);
  68700. // Clear
  68701. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68702. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68703. }
  68704. if (this._reusable) {
  68705. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68706. }
  68707. return target;
  68708. };
  68709. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68710. /**
  68711. * If the post process is supported.
  68712. */
  68713. get: function () {
  68714. return this._effect.isSupported;
  68715. },
  68716. enumerable: true,
  68717. configurable: true
  68718. });
  68719. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68720. /**
  68721. * The aspect ratio of the output texture.
  68722. */
  68723. get: function () {
  68724. if (this._shareOutputWithPostProcess) {
  68725. return this._shareOutputWithPostProcess.aspectRatio;
  68726. }
  68727. if (this._forcedOutputTexture) {
  68728. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68729. }
  68730. return this.width / this.height;
  68731. },
  68732. enumerable: true,
  68733. configurable: true
  68734. });
  68735. /**
  68736. * Get a value indicating if the post-process is ready to be used
  68737. * @returns true if the post-process is ready (shader is compiled)
  68738. */
  68739. PostProcess.prototype.isReady = function () {
  68740. return this._effect && this._effect.isReady();
  68741. };
  68742. /**
  68743. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68744. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68745. */
  68746. PostProcess.prototype.apply = function () {
  68747. // Check
  68748. if (!this._effect || !this._effect.isReady())
  68749. return null;
  68750. // States
  68751. this._engine.enableEffect(this._effect);
  68752. this._engine.setState(false);
  68753. this._engine.setDepthBuffer(false);
  68754. this._engine.setDepthWrite(false);
  68755. // Alpha
  68756. this._engine.setAlphaMode(this.alphaMode);
  68757. if (this.alphaConstants) {
  68758. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68759. }
  68760. // Bind the output texture of the preivous post process as the input to this post process.
  68761. var source;
  68762. if (this._shareOutputWithPostProcess) {
  68763. source = this._shareOutputWithPostProcess.inputTexture;
  68764. }
  68765. else if (this._forcedOutputTexture) {
  68766. source = this._forcedOutputTexture;
  68767. }
  68768. else {
  68769. source = this.inputTexture;
  68770. }
  68771. this._effect._bindTexture("textureSampler", source);
  68772. // Parameters
  68773. this._effect.setVector2("scale", this._scaleRatio);
  68774. this.onApplyObservable.notifyObservers(this._effect);
  68775. return this._effect;
  68776. };
  68777. PostProcess.prototype._disposeTextures = function () {
  68778. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68779. return;
  68780. }
  68781. if (this._textures.length > 0) {
  68782. for (var i = 0; i < this._textures.length; i++) {
  68783. this._engine._releaseTexture(this._textures.data[i]);
  68784. }
  68785. }
  68786. this._textures.dispose();
  68787. };
  68788. /**
  68789. * Disposes the post process.
  68790. * @param camera The camera to dispose the post process on.
  68791. */
  68792. PostProcess.prototype.dispose = function (camera) {
  68793. camera = camera || this._camera;
  68794. this._disposeTextures();
  68795. if (this._scene) {
  68796. var index_1 = this._scene.postProcesses.indexOf(this);
  68797. if (index_1 !== -1) {
  68798. this._scene.postProcesses.splice(index_1, 1);
  68799. }
  68800. }
  68801. else {
  68802. var index_2 = this._engine.postProcesses.indexOf(this);
  68803. if (index_2 !== -1) {
  68804. this._engine.postProcesses.splice(index_2, 1);
  68805. }
  68806. }
  68807. if (!camera) {
  68808. return;
  68809. }
  68810. camera.detachPostProcess(this);
  68811. var index = camera._postProcesses.indexOf(this);
  68812. if (index === 0 && camera._postProcesses.length > 0) {
  68813. var firstPostProcess = this._camera._getFirstPostProcess();
  68814. if (firstPostProcess) {
  68815. firstPostProcess.markTextureDirty();
  68816. }
  68817. }
  68818. this.onActivateObservable.clear();
  68819. this.onAfterRenderObservable.clear();
  68820. this.onApplyObservable.clear();
  68821. this.onBeforeRenderObservable.clear();
  68822. this.onSizeChangedObservable.clear();
  68823. };
  68824. return PostProcess;
  68825. }());
  68826. BABYLON.PostProcess = PostProcess;
  68827. })(BABYLON || (BABYLON = {}));
  68828. //# sourceMappingURL=babylon.postProcess.js.map
  68829. var BABYLON;
  68830. (function (BABYLON) {
  68831. var PassPostProcess = /** @class */ (function (_super) {
  68832. __extends(PassPostProcess, _super);
  68833. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68834. if (camera === void 0) { camera = null; }
  68835. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68836. if (blockCompilation === void 0) { blockCompilation = false; }
  68837. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68838. }
  68839. return PassPostProcess;
  68840. }(BABYLON.PostProcess));
  68841. BABYLON.PassPostProcess = PassPostProcess;
  68842. })(BABYLON || (BABYLON = {}));
  68843. //# sourceMappingURL=babylon.passPostProcess.js.map
  68844. var __assign = (this && this.__assign) || function () {
  68845. __assign = Object.assign || function(t) {
  68846. for (var s, i = 1, n = arguments.length; i < n; i++) {
  68847. s = arguments[i];
  68848. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  68849. t[p] = s[p];
  68850. }
  68851. return t;
  68852. };
  68853. return __assign.apply(this, arguments);
  68854. };
  68855. var BABYLON;
  68856. (function (BABYLON) {
  68857. /**
  68858. * Default implementation IShadowGenerator.
  68859. * This is the main object responsible of generating shadows in the framework.
  68860. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  68861. */
  68862. var ShadowGenerator = /** @class */ (function () {
  68863. /**
  68864. * Creates a ShadowGenerator object.
  68865. * A ShadowGenerator is the required tool to use the shadows.
  68866. * Each light casting shadows needs to use its own ShadowGenerator.
  68867. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  68868. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  68869. * @param light The light object generating the shadows.
  68870. * @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.
  68871. */
  68872. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  68873. this._bias = 0.00005;
  68874. this._normalBias = 0;
  68875. this._blurBoxOffset = 1;
  68876. this._blurScale = 2;
  68877. this._blurKernel = 1;
  68878. this._useKernelBlur = false;
  68879. this._filter = ShadowGenerator.FILTER_NONE;
  68880. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  68881. this._contactHardeningLightSizeUVRatio = 0.1;
  68882. this._darkness = 0;
  68883. this._transparencyShadow = false;
  68884. /**
  68885. * Controls the extent to which the shadows fade out at the edge of the frustum
  68886. * Used only by directionals and spots
  68887. */
  68888. this.frustumEdgeFalloff = 0;
  68889. /**
  68890. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  68891. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  68892. * It might on the other hand introduce peter panning.
  68893. */
  68894. this.forceBackFacesOnly = false;
  68895. this._lightDirection = BABYLON.Vector3.Zero();
  68896. this._viewMatrix = BABYLON.Matrix.Zero();
  68897. this._projectionMatrix = BABYLON.Matrix.Zero();
  68898. this._transformMatrix = BABYLON.Matrix.Zero();
  68899. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68900. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68901. this._currentFaceIndex = 0;
  68902. this._currentFaceIndexCache = 0;
  68903. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  68904. this._mapSize = mapSize;
  68905. this._light = light;
  68906. this._scene = light.getScene();
  68907. light._shadowGenerator = this;
  68908. // Texture type fallback from float to int if not supported.
  68909. var caps = this._scene.getEngine().getCaps();
  68910. if (!useFullFloatFirst) {
  68911. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68912. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68913. }
  68914. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68915. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68916. }
  68917. else {
  68918. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68919. }
  68920. }
  68921. else {
  68922. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68923. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68924. }
  68925. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68926. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68927. }
  68928. else {
  68929. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68930. }
  68931. }
  68932. this._initializeGenerator();
  68933. this._applyFilterValues();
  68934. }
  68935. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68936. /**
  68937. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68938. */
  68939. get: function () {
  68940. return this._bias;
  68941. },
  68942. /**
  68943. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68944. */
  68945. set: function (bias) {
  68946. this._bias = bias;
  68947. },
  68948. enumerable: true,
  68949. configurable: true
  68950. });
  68951. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68952. /**
  68953. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68954. */
  68955. get: function () {
  68956. return this._normalBias;
  68957. },
  68958. /**
  68959. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68960. */
  68961. set: function (normalBias) {
  68962. this._normalBias = normalBias;
  68963. },
  68964. enumerable: true,
  68965. configurable: true
  68966. });
  68967. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68968. /**
  68969. * Gets the blur box offset: offset applied during the blur pass.
  68970. * Only usefull if useKernelBlur = false
  68971. */
  68972. get: function () {
  68973. return this._blurBoxOffset;
  68974. },
  68975. /**
  68976. * Sets the blur box offset: offset applied during the blur pass.
  68977. * Only usefull if useKernelBlur = false
  68978. */
  68979. set: function (value) {
  68980. if (this._blurBoxOffset === value) {
  68981. return;
  68982. }
  68983. this._blurBoxOffset = value;
  68984. this._disposeBlurPostProcesses();
  68985. },
  68986. enumerable: true,
  68987. configurable: true
  68988. });
  68989. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  68990. /**
  68991. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  68992. * 2 means half of the size.
  68993. */
  68994. get: function () {
  68995. return this._blurScale;
  68996. },
  68997. /**
  68998. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  68999. * 2 means half of the size.
  69000. */
  69001. set: function (value) {
  69002. if (this._blurScale === value) {
  69003. return;
  69004. }
  69005. this._blurScale = value;
  69006. this._disposeBlurPostProcesses();
  69007. },
  69008. enumerable: true,
  69009. configurable: true
  69010. });
  69011. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69012. /**
  69013. * Gets the blur kernel: kernel size of the blur pass.
  69014. * Only usefull if useKernelBlur = true
  69015. */
  69016. get: function () {
  69017. return this._blurKernel;
  69018. },
  69019. /**
  69020. * Sets the blur kernel: kernel size of the blur pass.
  69021. * Only usefull if useKernelBlur = true
  69022. */
  69023. set: function (value) {
  69024. if (this._blurKernel === value) {
  69025. return;
  69026. }
  69027. this._blurKernel = value;
  69028. this._disposeBlurPostProcesses();
  69029. },
  69030. enumerable: true,
  69031. configurable: true
  69032. });
  69033. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69034. /**
  69035. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69036. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69037. */
  69038. get: function () {
  69039. return this._useKernelBlur;
  69040. },
  69041. /**
  69042. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69043. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69044. */
  69045. set: function (value) {
  69046. if (this._useKernelBlur === value) {
  69047. return;
  69048. }
  69049. this._useKernelBlur = value;
  69050. this._disposeBlurPostProcesses();
  69051. },
  69052. enumerable: true,
  69053. configurable: true
  69054. });
  69055. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69056. /**
  69057. * Gets the depth scale used in ESM mode.
  69058. */
  69059. get: function () {
  69060. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69061. },
  69062. /**
  69063. * Sets the depth scale used in ESM mode.
  69064. * This can override the scale stored on the light.
  69065. */
  69066. set: function (value) {
  69067. this._depthScale = value;
  69068. },
  69069. enumerable: true,
  69070. configurable: true
  69071. });
  69072. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69073. /**
  69074. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69075. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69076. */
  69077. get: function () {
  69078. return this._filter;
  69079. },
  69080. /**
  69081. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69082. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69083. */
  69084. set: function (value) {
  69085. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69086. if (this._light.needCube()) {
  69087. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69088. this.useExponentialShadowMap = true;
  69089. return;
  69090. }
  69091. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69092. this.useCloseExponentialShadowMap = true;
  69093. return;
  69094. }
  69095. // PCF on cubemap would also be expensive
  69096. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69097. this.usePoissonSampling = true;
  69098. return;
  69099. }
  69100. }
  69101. // Weblg1 fallback for PCF.
  69102. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69103. if (this._scene.getEngine().webGLVersion === 1) {
  69104. this.usePoissonSampling = true;
  69105. return;
  69106. }
  69107. }
  69108. if (this._filter === value) {
  69109. return;
  69110. }
  69111. this._filter = value;
  69112. this._disposeBlurPostProcesses();
  69113. this._applyFilterValues();
  69114. this._light._markMeshesAsLightDirty();
  69115. },
  69116. enumerable: true,
  69117. configurable: true
  69118. });
  69119. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  69120. /**
  69121. * Gets if the current filter is set to Poisson Sampling.
  69122. */
  69123. get: function () {
  69124. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  69125. },
  69126. /**
  69127. * Sets the current filter to Poisson Sampling.
  69128. */
  69129. set: function (value) {
  69130. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  69131. return;
  69132. }
  69133. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  69134. },
  69135. enumerable: true,
  69136. configurable: true
  69137. });
  69138. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  69139. /**
  69140. * Gets if the current filter is set to VSM.
  69141. * DEPRECATED. Should use useExponentialShadowMap instead.
  69142. */
  69143. get: function () {
  69144. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69145. return this.useExponentialShadowMap;
  69146. },
  69147. /**
  69148. * Sets the current filter is to VSM.
  69149. * DEPRECATED. Should use useExponentialShadowMap instead.
  69150. */
  69151. set: function (value) {
  69152. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69153. this.useExponentialShadowMap = value;
  69154. },
  69155. enumerable: true,
  69156. configurable: true
  69157. });
  69158. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  69159. /**
  69160. * Gets if the current filter is set to blurred VSM.
  69161. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69162. */
  69163. get: function () {
  69164. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69165. return this.useBlurExponentialShadowMap;
  69166. },
  69167. /**
  69168. * Sets the current filter is to blurred VSM.
  69169. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69170. */
  69171. set: function (value) {
  69172. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69173. this.useBlurExponentialShadowMap = value;
  69174. },
  69175. enumerable: true,
  69176. configurable: true
  69177. });
  69178. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  69179. /**
  69180. * Gets if the current filter is set to ESM.
  69181. */
  69182. get: function () {
  69183. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  69184. },
  69185. /**
  69186. * Sets the current filter is to ESM.
  69187. */
  69188. set: function (value) {
  69189. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  69190. return;
  69191. }
  69192. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69193. },
  69194. enumerable: true,
  69195. configurable: true
  69196. });
  69197. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  69198. /**
  69199. * Gets if the current filter is set to filtered ESM.
  69200. */
  69201. get: function () {
  69202. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  69203. },
  69204. /**
  69205. * Gets if the current filter is set to filtered ESM.
  69206. */
  69207. set: function (value) {
  69208. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69209. return;
  69210. }
  69211. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69212. },
  69213. enumerable: true,
  69214. configurable: true
  69215. });
  69216. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  69217. /**
  69218. * Gets if the current filter is set to "close ESM" (using the inverse of the
  69219. * exponential to prevent steep falloff artifacts).
  69220. */
  69221. get: function () {
  69222. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  69223. },
  69224. /**
  69225. * Sets the current filter to "close ESM" (using the inverse of the
  69226. * exponential to prevent steep falloff artifacts).
  69227. */
  69228. set: function (value) {
  69229. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  69230. return;
  69231. }
  69232. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69233. },
  69234. enumerable: true,
  69235. configurable: true
  69236. });
  69237. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  69238. /**
  69239. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69240. * exponential to prevent steep falloff artifacts).
  69241. */
  69242. get: function () {
  69243. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69244. },
  69245. /**
  69246. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69247. * exponential to prevent steep falloff artifacts).
  69248. */
  69249. set: function (value) {
  69250. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69251. return;
  69252. }
  69253. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69254. },
  69255. enumerable: true,
  69256. configurable: true
  69257. });
  69258. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69259. /**
  69260. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69261. */
  69262. get: function () {
  69263. return this.filter === ShadowGenerator.FILTER_PCF;
  69264. },
  69265. /**
  69266. * Sets the current filter to "PCF" (percentage closer filtering).
  69267. */
  69268. set: function (value) {
  69269. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69270. return;
  69271. }
  69272. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69273. },
  69274. enumerable: true,
  69275. configurable: true
  69276. });
  69277. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69278. /**
  69279. * Gets the PCF or PCSS Quality.
  69280. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69281. */
  69282. get: function () {
  69283. return this._filteringQuality;
  69284. },
  69285. /**
  69286. * Sets the PCF or PCSS Quality.
  69287. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69288. */
  69289. set: function (filteringQuality) {
  69290. this._filteringQuality = filteringQuality;
  69291. },
  69292. enumerable: true,
  69293. configurable: true
  69294. });
  69295. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69296. /**
  69297. * Gets if the current filter is set to "PCSS" (contact hardening).
  69298. */
  69299. get: function () {
  69300. return this.filter === ShadowGenerator.FILTER_PCSS;
  69301. },
  69302. /**
  69303. * Sets the current filter to "PCSS" (contact hardening).
  69304. */
  69305. set: function (value) {
  69306. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69307. return;
  69308. }
  69309. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69310. },
  69311. enumerable: true,
  69312. configurable: true
  69313. });
  69314. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69315. /**
  69316. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69317. * Using a ratio helps keeping shape stability independently of the map size.
  69318. *
  69319. * It does not account for the light projection as it was having too much
  69320. * instability during the light setup or during light position changes.
  69321. *
  69322. * Only valid if useContactHardeningShadow is true.
  69323. */
  69324. get: function () {
  69325. return this._contactHardeningLightSizeUVRatio;
  69326. },
  69327. /**
  69328. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69329. * Using a ratio helps keeping shape stability independently of the map size.
  69330. *
  69331. * It does not account for the light projection as it was having too much
  69332. * instability during the light setup or during light position changes.
  69333. *
  69334. * Only valid if useContactHardeningShadow is true.
  69335. */
  69336. set: function (contactHardeningLightSizeUVRatio) {
  69337. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69338. },
  69339. enumerable: true,
  69340. configurable: true
  69341. });
  69342. /**
  69343. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69344. * 0 means strongest and 1 would means no shadow.
  69345. * @returns the darkness.
  69346. */
  69347. ShadowGenerator.prototype.getDarkness = function () {
  69348. return this._darkness;
  69349. };
  69350. /**
  69351. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69352. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69353. * @returns the shadow generator allowing fluent coding.
  69354. */
  69355. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69356. if (darkness >= 1.0)
  69357. this._darkness = 1.0;
  69358. else if (darkness <= 0.0)
  69359. this._darkness = 0.0;
  69360. else
  69361. this._darkness = darkness;
  69362. return this;
  69363. };
  69364. /**
  69365. * Sets the ability to have transparent shadow (boolean).
  69366. * @param transparent True if transparent else False
  69367. * @returns the shadow generator allowing fluent coding
  69368. */
  69369. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69370. this._transparencyShadow = transparent;
  69371. return this;
  69372. };
  69373. /**
  69374. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69375. * @returns The render target texture if present otherwise, null
  69376. */
  69377. ShadowGenerator.prototype.getShadowMap = function () {
  69378. return this._shadowMap;
  69379. };
  69380. /**
  69381. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69382. * @returns The render target texture if the shadow map is present otherwise, null
  69383. */
  69384. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69385. if (this._shadowMap2) {
  69386. return this._shadowMap2;
  69387. }
  69388. return this._shadowMap;
  69389. };
  69390. /**
  69391. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69392. * @param mesh Mesh to add
  69393. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69394. * @returns the Shadow Generator itself
  69395. */
  69396. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69397. if (includeDescendants === void 0) { includeDescendants = true; }
  69398. var _a;
  69399. if (!this._shadowMap) {
  69400. return this;
  69401. }
  69402. if (!this._shadowMap.renderList) {
  69403. this._shadowMap.renderList = [];
  69404. }
  69405. this._shadowMap.renderList.push(mesh);
  69406. if (includeDescendants) {
  69407. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69408. }
  69409. return this;
  69410. };
  69411. /**
  69412. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69413. * @param mesh Mesh to remove
  69414. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69415. * @returns the Shadow Generator itself
  69416. */
  69417. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69418. if (includeDescendants === void 0) { includeDescendants = true; }
  69419. if (!this._shadowMap || !this._shadowMap.renderList) {
  69420. return this;
  69421. }
  69422. var index = this._shadowMap.renderList.indexOf(mesh);
  69423. if (index !== -1) {
  69424. this._shadowMap.renderList.splice(index, 1);
  69425. }
  69426. if (includeDescendants) {
  69427. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69428. var child = _a[_i];
  69429. this.removeShadowCaster(child);
  69430. }
  69431. }
  69432. return this;
  69433. };
  69434. /**
  69435. * Returns the associated light object.
  69436. * @returns the light generating the shadow
  69437. */
  69438. ShadowGenerator.prototype.getLight = function () {
  69439. return this._light;
  69440. };
  69441. ShadowGenerator.prototype._initializeGenerator = function () {
  69442. this._light._markMeshesAsLightDirty();
  69443. this._initializeShadowMap();
  69444. };
  69445. ShadowGenerator.prototype._initializeShadowMap = function () {
  69446. var _this = this;
  69447. // Render target
  69448. var engine = this._scene.getEngine();
  69449. if (engine.webGLVersion > 1) {
  69450. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69451. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69452. }
  69453. else {
  69454. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69455. }
  69456. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69457. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69458. this._shadowMap.anisotropicFilteringLevel = 1;
  69459. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69460. this._shadowMap.renderParticles = false;
  69461. this._shadowMap.ignoreCameraViewport = true;
  69462. // Record Face Index before render.
  69463. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69464. _this._currentFaceIndex = faceIndex;
  69465. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69466. engine.setColorWrite(false);
  69467. }
  69468. });
  69469. // Custom render function.
  69470. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69471. // Blur if required afer render.
  69472. this._shadowMap.onAfterUnbindObservable.add(function () {
  69473. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69474. engine.setColorWrite(true);
  69475. }
  69476. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69477. return;
  69478. }
  69479. var shadowMap = _this.getShadowMapForRendering();
  69480. if (shadowMap) {
  69481. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69482. }
  69483. });
  69484. // Clear according to the chosen filter.
  69485. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69486. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69487. this._shadowMap.onClearObservable.add(function (engine) {
  69488. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69489. engine.clear(clearOne, false, true, false);
  69490. }
  69491. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69492. engine.clear(clearZero, true, true, false);
  69493. }
  69494. else {
  69495. engine.clear(clearOne, true, true, false);
  69496. }
  69497. });
  69498. };
  69499. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69500. var _this = this;
  69501. var engine = this._scene.getEngine();
  69502. var targetSize = this._mapSize / this.blurScale;
  69503. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69504. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69505. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69506. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69507. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69508. }
  69509. if (this.useKernelBlur) {
  69510. 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);
  69511. this._kernelBlurXPostprocess.width = targetSize;
  69512. this._kernelBlurXPostprocess.height = targetSize;
  69513. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69514. effect.setTexture("textureSampler", _this._shadowMap);
  69515. });
  69516. 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);
  69517. this._kernelBlurXPostprocess.autoClear = false;
  69518. this._kernelBlurYPostprocess.autoClear = false;
  69519. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69520. this._kernelBlurXPostprocess.packedFloat = true;
  69521. this._kernelBlurYPostprocess.packedFloat = true;
  69522. }
  69523. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69524. }
  69525. else {
  69526. 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);
  69527. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69528. effect.setFloat2("screenSize", targetSize, targetSize);
  69529. effect.setTexture("textureSampler", _this._shadowMap);
  69530. });
  69531. this._boxBlurPostprocess.autoClear = false;
  69532. this._blurPostProcesses = [this._boxBlurPostprocess];
  69533. }
  69534. };
  69535. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69536. var index;
  69537. var engine = this._scene.getEngine();
  69538. if (depthOnlySubMeshes.length) {
  69539. engine.setColorWrite(false);
  69540. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69541. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  69542. }
  69543. engine.setColorWrite(true);
  69544. }
  69545. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69546. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  69547. }
  69548. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69549. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69550. }
  69551. if (this._transparencyShadow) {
  69552. for (index = 0; index < transparentSubMeshes.length; index++) {
  69553. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69554. }
  69555. }
  69556. };
  69557. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69558. var _this = this;
  69559. var mesh = subMesh.getRenderingMesh();
  69560. var scene = this._scene;
  69561. var engine = scene.getEngine();
  69562. var material = subMesh.getMaterial();
  69563. if (!material) {
  69564. return;
  69565. }
  69566. // Culling
  69567. engine.setState(material.backFaceCulling);
  69568. // Managing instances
  69569. var batch = mesh._getInstancesRenderList(subMesh._id);
  69570. if (batch.mustReturn) {
  69571. return;
  69572. }
  69573. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69574. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69575. engine.enableEffect(this._effect);
  69576. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69577. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69578. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69579. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69580. this._effect.setVector3("lightData", this._cachedDirection);
  69581. }
  69582. else {
  69583. this._effect.setVector3("lightData", this._cachedPosition);
  69584. }
  69585. if (scene.activeCamera) {
  69586. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69587. }
  69588. // Alpha test
  69589. if (material && material.needAlphaTesting()) {
  69590. var alphaTexture = material.getAlphaTestTexture();
  69591. if (alphaTexture) {
  69592. this._effect.setTexture("diffuseSampler", alphaTexture);
  69593. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69594. }
  69595. }
  69596. // Bones
  69597. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69598. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69599. }
  69600. // Morph targets
  69601. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69602. if (this.forceBackFacesOnly) {
  69603. engine.setState(true, 0, false, true);
  69604. }
  69605. // Draw
  69606. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69607. if (this.forceBackFacesOnly) {
  69608. engine.setState(true, 0, false, false);
  69609. }
  69610. }
  69611. else {
  69612. // Need to reset refresh rate of the shadowMap
  69613. if (this._shadowMap) {
  69614. this._shadowMap.resetRefreshCounter();
  69615. }
  69616. }
  69617. };
  69618. ShadowGenerator.prototype._applyFilterValues = function () {
  69619. if (!this._shadowMap) {
  69620. return;
  69621. }
  69622. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69623. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69624. }
  69625. else {
  69626. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69627. }
  69628. };
  69629. /**
  69630. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69631. * @param onCompiled Callback triggered at the and of the effects compilation
  69632. * @param options Sets of optional options forcing the compilation with different modes
  69633. */
  69634. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69635. var _this = this;
  69636. var localOptions = __assign({ useInstances: false }, options);
  69637. var shadowMap = this.getShadowMap();
  69638. if (!shadowMap) {
  69639. if (onCompiled) {
  69640. onCompiled(this);
  69641. }
  69642. return;
  69643. }
  69644. var renderList = shadowMap.renderList;
  69645. if (!renderList) {
  69646. if (onCompiled) {
  69647. onCompiled(this);
  69648. }
  69649. return;
  69650. }
  69651. var subMeshes = new Array();
  69652. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69653. var mesh = renderList_1[_i];
  69654. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69655. }
  69656. if (subMeshes.length === 0) {
  69657. if (onCompiled) {
  69658. onCompiled(this);
  69659. }
  69660. return;
  69661. }
  69662. var currentIndex = 0;
  69663. var checkReady = function () {
  69664. if (!_this._scene || !_this._scene.getEngine()) {
  69665. return;
  69666. }
  69667. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69668. currentIndex++;
  69669. if (currentIndex >= subMeshes.length) {
  69670. if (onCompiled) {
  69671. onCompiled(_this);
  69672. }
  69673. return;
  69674. }
  69675. }
  69676. setTimeout(checkReady, 16);
  69677. };
  69678. checkReady();
  69679. };
  69680. /**
  69681. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69682. * @param options Sets of optional options forcing the compilation with different modes
  69683. * @returns A promise that resolves when the compilation completes
  69684. */
  69685. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69686. var _this = this;
  69687. return new Promise(function (resolve) {
  69688. _this.forceCompilation(function () {
  69689. resolve();
  69690. }, options);
  69691. });
  69692. };
  69693. /**
  69694. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69695. * @param subMesh The submesh we want to render in the shadow map
  69696. * @param useInstances Defines wether will draw in the map using instances
  69697. * @returns true if ready otherwise, false
  69698. */
  69699. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69700. var defines = [];
  69701. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69702. defines.push("#define FLOAT");
  69703. }
  69704. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69705. defines.push("#define ESM");
  69706. }
  69707. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69708. defines.push("#define DEPTHTEXTURE");
  69709. }
  69710. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69711. var mesh = subMesh.getMesh();
  69712. var material = subMesh.getMaterial();
  69713. // Normal bias.
  69714. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69715. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69716. defines.push("#define NORMAL");
  69717. if (mesh.nonUniformScaling) {
  69718. defines.push("#define NONUNIFORMSCALING");
  69719. }
  69720. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69721. defines.push("#define DIRECTIONINLIGHTDATA");
  69722. }
  69723. }
  69724. // Alpha test
  69725. if (material && material.needAlphaTesting()) {
  69726. var alphaTexture = material.getAlphaTestTexture();
  69727. if (alphaTexture) {
  69728. defines.push("#define ALPHATEST");
  69729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69730. attribs.push(BABYLON.VertexBuffer.UVKind);
  69731. defines.push("#define UV1");
  69732. }
  69733. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69734. if (alphaTexture.coordinatesIndex === 1) {
  69735. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69736. defines.push("#define UV2");
  69737. }
  69738. }
  69739. }
  69740. }
  69741. // Bones
  69742. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69745. if (mesh.numBoneInfluencers > 4) {
  69746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69748. }
  69749. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69750. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69751. }
  69752. else {
  69753. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69754. }
  69755. // Morph targets
  69756. var manager = mesh.morphTargetManager;
  69757. var morphInfluencers = 0;
  69758. if (manager) {
  69759. if (manager.numInfluencers > 0) {
  69760. defines.push("#define MORPHTARGETS");
  69761. morphInfluencers = manager.numInfluencers;
  69762. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69763. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69764. }
  69765. }
  69766. // Instances
  69767. if (useInstances) {
  69768. defines.push("#define INSTANCES");
  69769. attribs.push("world0");
  69770. attribs.push("world1");
  69771. attribs.push("world2");
  69772. attribs.push("world3");
  69773. }
  69774. // Get correct effect
  69775. var join = defines.join("\n");
  69776. if (this._cachedDefines !== join) {
  69777. this._cachedDefines = join;
  69778. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69779. }
  69780. if (!this._effect.isReady()) {
  69781. return false;
  69782. }
  69783. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69784. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69785. this._initializeBlurRTTAndPostProcesses();
  69786. }
  69787. }
  69788. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69789. return false;
  69790. }
  69791. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69792. return false;
  69793. }
  69794. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69795. return false;
  69796. }
  69797. return true;
  69798. };
  69799. /**
  69800. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69801. * @param defines Defines of the material we want to update
  69802. * @param lightIndex Index of the light in the enabled light list of the material
  69803. */
  69804. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69805. var scene = this._scene;
  69806. var light = this._light;
  69807. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69808. return;
  69809. }
  69810. defines["SHADOW" + lightIndex] = true;
  69811. if (this.useContactHardeningShadow) {
  69812. defines["SHADOWPCSS" + lightIndex] = true;
  69813. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69814. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69815. }
  69816. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69817. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69818. }
  69819. // else default to high.
  69820. }
  69821. if (this.usePercentageCloserFiltering) {
  69822. defines["SHADOWPCF" + lightIndex] = true;
  69823. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69824. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69825. }
  69826. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69827. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69828. }
  69829. // else default to high.
  69830. }
  69831. else if (this.usePoissonSampling) {
  69832. defines["SHADOWPOISSON" + lightIndex] = true;
  69833. }
  69834. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69835. defines["SHADOWESM" + lightIndex] = true;
  69836. }
  69837. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69838. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69839. }
  69840. if (light.needCube()) {
  69841. defines["SHADOWCUBE" + lightIndex] = true;
  69842. }
  69843. };
  69844. /**
  69845. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  69846. * defined in the generator but impacting the effect).
  69847. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  69848. * @param effect The effect we are binfing the information for
  69849. */
  69850. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  69851. var light = this._light;
  69852. var scene = this._scene;
  69853. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69854. return;
  69855. }
  69856. var camera = scene.activeCamera;
  69857. if (!camera) {
  69858. return;
  69859. }
  69860. var shadowMap = this.getShadowMap();
  69861. if (!shadowMap) {
  69862. return;
  69863. }
  69864. if (!light.needCube()) {
  69865. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  69866. }
  69867. // Only PCF uses depth stencil texture.
  69868. if (this._filter === ShadowGenerator.FILTER_PCF) {
  69869. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69870. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69871. }
  69872. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  69873. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69874. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  69875. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69876. }
  69877. else {
  69878. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69879. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  69880. }
  69881. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  69882. };
  69883. /**
  69884. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  69885. * (eq to shadow prjection matrix * light transform matrix)
  69886. * @returns The transform matrix used to create the shadow map
  69887. */
  69888. ShadowGenerator.prototype.getTransformMatrix = function () {
  69889. var scene = this._scene;
  69890. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  69891. return this._transformMatrix;
  69892. }
  69893. this._currentRenderID = scene.getRenderId();
  69894. this._currentFaceIndexCache = this._currentFaceIndex;
  69895. var lightPosition = this._light.position;
  69896. if (this._light.computeTransformedInformation()) {
  69897. lightPosition = this._light.transformedPosition;
  69898. }
  69899. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  69900. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  69901. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  69902. }
  69903. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  69904. this._cachedPosition.copyFrom(lightPosition);
  69905. this._cachedDirection.copyFrom(this._lightDirection);
  69906. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  69907. var shadowMap = this.getShadowMap();
  69908. if (shadowMap) {
  69909. var renderList = shadowMap.renderList;
  69910. if (renderList) {
  69911. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  69912. }
  69913. }
  69914. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  69915. }
  69916. return this._transformMatrix;
  69917. };
  69918. /**
  69919. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  69920. * Cube and 2D textures for instance.
  69921. */
  69922. ShadowGenerator.prototype.recreateShadowMap = function () {
  69923. var shadowMap = this._shadowMap;
  69924. if (!shadowMap) {
  69925. return;
  69926. }
  69927. // Track render list.
  69928. var renderList = shadowMap.renderList;
  69929. // Clean up existing data.
  69930. this._disposeRTTandPostProcesses();
  69931. // Reinitializes.
  69932. this._initializeGenerator();
  69933. // Reaffect the filter to ensure a correct fallback if necessary.
  69934. this.filter = this.filter;
  69935. // Reaffect the filter.
  69936. this._applyFilterValues();
  69937. // Reaffect Render List.
  69938. this._shadowMap.renderList = renderList;
  69939. };
  69940. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69941. if (this._shadowMap2) {
  69942. this._shadowMap2.dispose();
  69943. this._shadowMap2 = null;
  69944. }
  69945. if (this._boxBlurPostprocess) {
  69946. this._boxBlurPostprocess.dispose();
  69947. this._boxBlurPostprocess = null;
  69948. }
  69949. if (this._kernelBlurXPostprocess) {
  69950. this._kernelBlurXPostprocess.dispose();
  69951. this._kernelBlurXPostprocess = null;
  69952. }
  69953. if (this._kernelBlurYPostprocess) {
  69954. this._kernelBlurYPostprocess.dispose();
  69955. this._kernelBlurYPostprocess = null;
  69956. }
  69957. this._blurPostProcesses = [];
  69958. };
  69959. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69960. if (this._shadowMap) {
  69961. this._shadowMap.dispose();
  69962. this._shadowMap = null;
  69963. }
  69964. this._disposeBlurPostProcesses();
  69965. };
  69966. /**
  69967. * Disposes the ShadowGenerator.
  69968. * Returns nothing.
  69969. */
  69970. ShadowGenerator.prototype.dispose = function () {
  69971. this._disposeRTTandPostProcesses();
  69972. if (this._light) {
  69973. this._light._shadowGenerator = null;
  69974. this._light._markMeshesAsLightDirty();
  69975. }
  69976. };
  69977. /**
  69978. * Serializes the shadow generator setup to a json object.
  69979. * @returns The serialized JSON object
  69980. */
  69981. ShadowGenerator.prototype.serialize = function () {
  69982. var serializationObject = {};
  69983. var shadowMap = this.getShadowMap();
  69984. if (!shadowMap) {
  69985. return serializationObject;
  69986. }
  69987. serializationObject.lightId = this._light.id;
  69988. serializationObject.mapSize = shadowMap.getRenderSize();
  69989. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  69990. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  69991. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69992. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69993. serializationObject.usePoissonSampling = this.usePoissonSampling;
  69994. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  69995. serializationObject.depthScale = this.depthScale;
  69996. serializationObject.darkness = this.getDarkness();
  69997. serializationObject.blurBoxOffset = this.blurBoxOffset;
  69998. serializationObject.blurKernel = this.blurKernel;
  69999. serializationObject.blurScale = this.blurScale;
  70000. serializationObject.useKernelBlur = this.useKernelBlur;
  70001. serializationObject.transparencyShadow = this._transparencyShadow;
  70002. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70003. serializationObject.bias = this.bias;
  70004. serializationObject.normalBias = this.normalBias;
  70005. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70006. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70007. serializationObject.filteringQuality = this.filteringQuality;
  70008. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70009. serializationObject.renderList = [];
  70010. if (shadowMap.renderList) {
  70011. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70012. var mesh = shadowMap.renderList[meshIndex];
  70013. serializationObject.renderList.push(mesh.id);
  70014. }
  70015. }
  70016. return serializationObject;
  70017. };
  70018. /**
  70019. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70020. * @param parsedShadowGenerator The JSON object to parse
  70021. * @param scene The scene to create the shadow map for
  70022. * @returns The parsed shadow generator
  70023. */
  70024. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70025. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70026. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70027. var shadowMap = shadowGenerator.getShadowMap();
  70028. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70029. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70030. meshes.forEach(function (mesh) {
  70031. if (!shadowMap) {
  70032. return;
  70033. }
  70034. if (!shadowMap.renderList) {
  70035. shadowMap.renderList = [];
  70036. }
  70037. shadowMap.renderList.push(mesh);
  70038. });
  70039. }
  70040. if (parsedShadowGenerator.usePoissonSampling) {
  70041. shadowGenerator.usePoissonSampling = true;
  70042. }
  70043. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70044. shadowGenerator.useExponentialShadowMap = true;
  70045. }
  70046. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70047. shadowGenerator.useBlurExponentialShadowMap = true;
  70048. }
  70049. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70050. shadowGenerator.useCloseExponentialShadowMap = true;
  70051. }
  70052. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70053. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70054. }
  70055. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70056. shadowGenerator.usePercentageCloserFiltering = true;
  70057. }
  70058. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70059. shadowGenerator.useContactHardeningShadow = true;
  70060. }
  70061. if (parsedShadowGenerator.filteringQuality) {
  70062. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70063. }
  70064. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70065. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70066. }
  70067. // Backward compat
  70068. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70069. shadowGenerator.useExponentialShadowMap = true;
  70070. }
  70071. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70072. shadowGenerator.useBlurExponentialShadowMap = true;
  70073. }
  70074. if (parsedShadowGenerator.depthScale) {
  70075. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70076. }
  70077. if (parsedShadowGenerator.blurScale) {
  70078. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70079. }
  70080. if (parsedShadowGenerator.blurBoxOffset) {
  70081. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70082. }
  70083. if (parsedShadowGenerator.useKernelBlur) {
  70084. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70085. }
  70086. if (parsedShadowGenerator.blurKernel) {
  70087. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70088. }
  70089. if (parsedShadowGenerator.bias !== undefined) {
  70090. shadowGenerator.bias = parsedShadowGenerator.bias;
  70091. }
  70092. if (parsedShadowGenerator.normalBias !== undefined) {
  70093. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70094. }
  70095. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70096. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70097. }
  70098. if (parsedShadowGenerator.darkness) {
  70099. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70100. }
  70101. if (parsedShadowGenerator.transparencyShadow) {
  70102. shadowGenerator.setTransparencyShadow(true);
  70103. }
  70104. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70105. return shadowGenerator;
  70106. };
  70107. /**
  70108. * Shadow generator mode None: no filtering applied.
  70109. */
  70110. ShadowGenerator.FILTER_NONE = 0;
  70111. /**
  70112. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70113. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70114. */
  70115. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  70116. /**
  70117. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  70118. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  70119. */
  70120. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  70121. /**
  70122. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  70123. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70124. */
  70125. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  70126. /**
  70127. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  70128. * edge artifacts on steep falloff.
  70129. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70130. */
  70131. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  70132. /**
  70133. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  70134. * edge artifacts on steep falloff.
  70135. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70136. */
  70137. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  70138. /**
  70139. * Shadow generator mode PCF: Percentage Closer Filtering
  70140. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70141. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  70142. */
  70143. ShadowGenerator.FILTER_PCF = 6;
  70144. /**
  70145. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  70146. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70147. * Contact Hardening
  70148. */
  70149. ShadowGenerator.FILTER_PCSS = 7;
  70150. /**
  70151. * Reserved for PCF and PCSS
  70152. * Highest Quality.
  70153. *
  70154. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  70155. *
  70156. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  70157. */
  70158. ShadowGenerator.QUALITY_HIGH = 0;
  70159. /**
  70160. * Reserved for PCF and PCSS
  70161. * Good tradeoff for quality/perf cross devices
  70162. *
  70163. * Execute PCF on a 3*3 kernel.
  70164. *
  70165. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  70166. */
  70167. ShadowGenerator.QUALITY_MEDIUM = 1;
  70168. /**
  70169. * Reserved for PCF and PCSS
  70170. * The lowest quality but the fastest.
  70171. *
  70172. * Execute PCF on a 1*1 kernel.
  70173. *
  70174. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  70175. */
  70176. ShadowGenerator.QUALITY_LOW = 2;
  70177. return ShadowGenerator;
  70178. }());
  70179. BABYLON.ShadowGenerator = ShadowGenerator;
  70180. })(BABYLON || (BABYLON = {}));
  70181. //# sourceMappingURL=babylon.shadowGenerator.js.map
  70182. var BABYLON;
  70183. (function (BABYLON) {
  70184. var DefaultLoadingScreen = /** @class */ (function () {
  70185. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  70186. if (_loadingText === void 0) { _loadingText = ""; }
  70187. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  70188. var _this = this;
  70189. this._renderingCanvas = _renderingCanvas;
  70190. this._loadingText = _loadingText;
  70191. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  70192. // Resize
  70193. this._resizeLoadingUI = function () {
  70194. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  70195. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  70196. if (!_this._loadingDiv) {
  70197. return;
  70198. }
  70199. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  70200. _this._loadingDiv.style.left = canvasRect.left + "px";
  70201. _this._loadingDiv.style.top = canvasRect.top + "px";
  70202. _this._loadingDiv.style.width = canvasRect.width + "px";
  70203. _this._loadingDiv.style.height = canvasRect.height + "px";
  70204. };
  70205. }
  70206. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  70207. if (this._loadingDiv) {
  70208. // Do not add a loading screen if there is already one
  70209. return;
  70210. }
  70211. this._loadingDiv = document.createElement("div");
  70212. this._loadingDiv.id = "babylonjsLoadingDiv";
  70213. this._loadingDiv.style.opacity = "0";
  70214. this._loadingDiv.style.transition = "opacity 1.5s ease";
  70215. this._loadingDiv.style.pointerEvents = "none";
  70216. // Loading text
  70217. this._loadingTextDiv = document.createElement("div");
  70218. this._loadingTextDiv.style.position = "absolute";
  70219. this._loadingTextDiv.style.left = "0";
  70220. this._loadingTextDiv.style.top = "50%";
  70221. this._loadingTextDiv.style.marginTop = "80px";
  70222. this._loadingTextDiv.style.width = "100%";
  70223. this._loadingTextDiv.style.height = "20px";
  70224. this._loadingTextDiv.style.fontFamily = "Arial";
  70225. this._loadingTextDiv.style.fontSize = "14px";
  70226. this._loadingTextDiv.style.color = "white";
  70227. this._loadingTextDiv.style.textAlign = "center";
  70228. this._loadingTextDiv.innerHTML = "Loading";
  70229. this._loadingDiv.appendChild(this._loadingTextDiv);
  70230. //set the predefined text
  70231. this._loadingTextDiv.innerHTML = this._loadingText;
  70232. // Generating keyframes
  70233. var style = document.createElement('style');
  70234. style.type = 'text/css';
  70235. 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 }";
  70236. style.innerHTML = keyFrames;
  70237. document.getElementsByTagName('head')[0].appendChild(style);
  70238. // Loading img
  70239. var imgBack = new Image();
  70240. 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";
  70241. imgBack.style.position = "absolute";
  70242. imgBack.style.left = "50%";
  70243. imgBack.style.top = "50%";
  70244. imgBack.style.marginLeft = "-60px";
  70245. imgBack.style.marginTop = "-60px";
  70246. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70247. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70248. imgBack.style.transformOrigin = "50% 50%";
  70249. imgBack.style.webkitTransformOrigin = "50% 50%";
  70250. this._loadingDiv.appendChild(imgBack);
  70251. this._resizeLoadingUI();
  70252. window.addEventListener("resize", this._resizeLoadingUI);
  70253. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70254. document.body.appendChild(this._loadingDiv);
  70255. this._loadingDiv.style.opacity = "1";
  70256. };
  70257. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70258. var _this = this;
  70259. if (!this._loadingDiv) {
  70260. return;
  70261. }
  70262. var onTransitionEnd = function () {
  70263. if (!_this._loadingDiv) {
  70264. return;
  70265. }
  70266. document.body.removeChild(_this._loadingDiv);
  70267. window.removeEventListener("resize", _this._resizeLoadingUI);
  70268. _this._loadingDiv = null;
  70269. };
  70270. this._loadingDiv.style.opacity = "0";
  70271. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70272. };
  70273. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70274. set: function (text) {
  70275. this._loadingText = text;
  70276. if (this._loadingTextDiv) {
  70277. this._loadingTextDiv.innerHTML = this._loadingText;
  70278. }
  70279. },
  70280. enumerable: true,
  70281. configurable: true
  70282. });
  70283. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70284. get: function () {
  70285. return this._loadingDivBackgroundColor;
  70286. },
  70287. set: function (color) {
  70288. this._loadingDivBackgroundColor = color;
  70289. if (!this._loadingDiv) {
  70290. return;
  70291. }
  70292. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70293. },
  70294. enumerable: true,
  70295. configurable: true
  70296. });
  70297. return DefaultLoadingScreen;
  70298. }());
  70299. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70300. })(BABYLON || (BABYLON = {}));
  70301. //# sourceMappingURL=babylon.loadingScreen.js.map
  70302. var BABYLON;
  70303. (function (BABYLON) {
  70304. var SceneLoaderProgressEvent = /** @class */ (function () {
  70305. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70306. this.lengthComputable = lengthComputable;
  70307. this.loaded = loaded;
  70308. this.total = total;
  70309. }
  70310. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70311. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70312. };
  70313. return SceneLoaderProgressEvent;
  70314. }());
  70315. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70316. var SceneLoader = /** @class */ (function () {
  70317. function SceneLoader() {
  70318. }
  70319. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70320. get: function () {
  70321. return 0;
  70322. },
  70323. enumerable: true,
  70324. configurable: true
  70325. });
  70326. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70327. get: function () {
  70328. return 1;
  70329. },
  70330. enumerable: true,
  70331. configurable: true
  70332. });
  70333. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70334. get: function () {
  70335. return 2;
  70336. },
  70337. enumerable: true,
  70338. configurable: true
  70339. });
  70340. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70341. get: function () {
  70342. return 3;
  70343. },
  70344. enumerable: true,
  70345. configurable: true
  70346. });
  70347. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70348. get: function () {
  70349. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70350. },
  70351. set: function (value) {
  70352. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70353. },
  70354. enumerable: true,
  70355. configurable: true
  70356. });
  70357. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70358. get: function () {
  70359. return SceneLoader._ShowLoadingScreen;
  70360. },
  70361. set: function (value) {
  70362. SceneLoader._ShowLoadingScreen = value;
  70363. },
  70364. enumerable: true,
  70365. configurable: true
  70366. });
  70367. Object.defineProperty(SceneLoader, "loggingLevel", {
  70368. get: function () {
  70369. return SceneLoader._loggingLevel;
  70370. },
  70371. set: function (value) {
  70372. SceneLoader._loggingLevel = value;
  70373. },
  70374. enumerable: true,
  70375. configurable: true
  70376. });
  70377. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70378. get: function () {
  70379. return SceneLoader._CleanBoneMatrixWeights;
  70380. },
  70381. set: function (value) {
  70382. SceneLoader._CleanBoneMatrixWeights = value;
  70383. },
  70384. enumerable: true,
  70385. configurable: true
  70386. });
  70387. SceneLoader._getDefaultPlugin = function () {
  70388. return SceneLoader._registeredPlugins[".babylon"];
  70389. };
  70390. SceneLoader._getPluginForExtension = function (extension) {
  70391. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70392. if (registeredPlugin) {
  70393. return registeredPlugin;
  70394. }
  70395. 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");
  70396. return SceneLoader._getDefaultPlugin();
  70397. };
  70398. SceneLoader._getPluginForDirectLoad = function (data) {
  70399. for (var extension in SceneLoader._registeredPlugins) {
  70400. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70401. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70402. return SceneLoader._registeredPlugins[extension];
  70403. }
  70404. }
  70405. return SceneLoader._getDefaultPlugin();
  70406. };
  70407. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70408. if (sceneFilename.name) {
  70409. sceneFilename = sceneFilename.name;
  70410. }
  70411. var queryStringPosition = sceneFilename.indexOf("?");
  70412. if (queryStringPosition !== -1) {
  70413. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70414. }
  70415. var dotPosition = sceneFilename.lastIndexOf(".");
  70416. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70417. return SceneLoader._getPluginForExtension(extension);
  70418. };
  70419. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70420. SceneLoader._getDirectLoad = function (sceneFilename) {
  70421. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70422. return sceneFilename.substr(5);
  70423. }
  70424. return null;
  70425. };
  70426. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70427. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70428. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70429. var plugin;
  70430. if (registeredPlugin.plugin.createPlugin) {
  70431. plugin = registeredPlugin.plugin.createPlugin();
  70432. }
  70433. else {
  70434. plugin = registeredPlugin.plugin;
  70435. }
  70436. var useArrayBuffer = registeredPlugin.isBinary;
  70437. var database;
  70438. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  70439. var dataCallback = function (data, responseURL) {
  70440. if (scene.isDisposed) {
  70441. onError("Scene has been disposed");
  70442. return;
  70443. }
  70444. scene.database = database;
  70445. onSuccess(plugin, data, responseURL);
  70446. };
  70447. var request = null;
  70448. var pluginDisposed = false;
  70449. var onDisposeObservable = plugin.onDisposeObservable;
  70450. if (onDisposeObservable) {
  70451. onDisposeObservable.add(function () {
  70452. pluginDisposed = true;
  70453. if (request) {
  70454. request.abort();
  70455. request = null;
  70456. }
  70457. onDispose();
  70458. });
  70459. }
  70460. var manifestChecked = function () {
  70461. if (pluginDisposed) {
  70462. return;
  70463. }
  70464. var url = rootUrl + sceneFilename;
  70465. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  70466. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  70467. } : undefined, database, useArrayBuffer, function (request, exception) {
  70468. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  70469. });
  70470. };
  70471. if (directLoad) {
  70472. dataCallback(directLoad);
  70473. return plugin;
  70474. }
  70475. if (rootUrl.indexOf("file:") === -1) {
  70476. var engine = scene.getEngine();
  70477. var canUseOfflineSupport = engine.enableOfflineSupport;
  70478. if (canUseOfflineSupport) {
  70479. // Also check for exceptions
  70480. var exceptionFound = false;
  70481. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  70482. var regex = _a[_i];
  70483. if (regex.test(rootUrl + sceneFilename)) {
  70484. exceptionFound = true;
  70485. break;
  70486. }
  70487. }
  70488. canUseOfflineSupport = !exceptionFound;
  70489. }
  70490. if (canUseOfflineSupport) {
  70491. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  70492. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  70493. }
  70494. else {
  70495. manifestChecked();
  70496. }
  70497. }
  70498. // Loading file from disk via input file or drag'n'drop
  70499. else {
  70500. var fileOrString = sceneFilename;
  70501. if (fileOrString.name) { // File
  70502. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  70503. }
  70504. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  70505. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  70506. }
  70507. else {
  70508. onError("Unable to find file named " + sceneFilename);
  70509. }
  70510. }
  70511. return plugin;
  70512. };
  70513. // Public functions
  70514. SceneLoader.GetPluginForExtension = function (extension) {
  70515. return SceneLoader._getPluginForExtension(extension).plugin;
  70516. };
  70517. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  70518. return !!SceneLoader._registeredPlugins[extension];
  70519. };
  70520. SceneLoader.RegisterPlugin = function (plugin) {
  70521. if (typeof plugin.extensions === "string") {
  70522. var extension = plugin.extensions;
  70523. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70524. plugin: plugin,
  70525. isBinary: false
  70526. };
  70527. }
  70528. else {
  70529. var extensions = plugin.extensions;
  70530. Object.keys(extensions).forEach(function (extension) {
  70531. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70532. plugin: plugin,
  70533. isBinary: extensions[extension].isBinary
  70534. };
  70535. });
  70536. }
  70537. };
  70538. /**
  70539. * Import meshes into a scene
  70540. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70541. * @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)
  70542. * @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)
  70543. * @param scene the instance of BABYLON.Scene to append to
  70544. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  70545. * @param onProgress a callback with a progress event for each file being loaded
  70546. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70547. * @param pluginExtension the extension used to determine the plugin
  70548. * @returns The loaded plugin
  70549. */
  70550. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70551. if (sceneFilename === void 0) { sceneFilename = ""; }
  70552. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70553. if (onSuccess === void 0) { onSuccess = null; }
  70554. if (onProgress === void 0) { onProgress = null; }
  70555. if (onError === void 0) { onError = null; }
  70556. if (pluginExtension === void 0) { pluginExtension = null; }
  70557. if (!scene) {
  70558. BABYLON.Tools.Error("No scene available to import mesh to");
  70559. return null;
  70560. }
  70561. if (!sceneFilename) {
  70562. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70563. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70564. }
  70565. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70566. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70567. return null;
  70568. }
  70569. var loadingToken = {};
  70570. scene._addPendingData(loadingToken);
  70571. var disposeHandler = function () {
  70572. scene._removePendingData(loadingToken);
  70573. };
  70574. var errorHandler = function (message, exception) {
  70575. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70576. if (onError) {
  70577. onError(scene, errorMessage, exception);
  70578. }
  70579. else {
  70580. BABYLON.Tools.Error(errorMessage);
  70581. // should the exception be thrown?
  70582. }
  70583. disposeHandler();
  70584. };
  70585. var progressHandler = onProgress ? function (event) {
  70586. try {
  70587. onProgress(event);
  70588. }
  70589. catch (e) {
  70590. errorHandler("Error in onProgress callback", e);
  70591. }
  70592. } : undefined;
  70593. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70594. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70595. if (onSuccess) {
  70596. try {
  70597. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70598. }
  70599. catch (e) {
  70600. errorHandler("Error in onSuccess callback", e);
  70601. }
  70602. }
  70603. scene._removePendingData(loadingToken);
  70604. };
  70605. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70606. if (plugin.rewriteRootURL) {
  70607. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70608. }
  70609. if (sceneFilename === "") {
  70610. if (sceneFilename === "") {
  70611. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70612. }
  70613. }
  70614. if (plugin.importMesh) {
  70615. var syncedPlugin = plugin;
  70616. var meshes = new Array();
  70617. var particleSystems = new Array();
  70618. var skeletons = new Array();
  70619. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70620. return;
  70621. }
  70622. scene.loadingPluginName = plugin.name;
  70623. successHandler(meshes, particleSystems, skeletons, []);
  70624. }
  70625. else {
  70626. var asyncedPlugin = plugin;
  70627. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70628. scene.loadingPluginName = plugin.name;
  70629. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70630. }).catch(function (error) {
  70631. errorHandler(error.message, error);
  70632. });
  70633. }
  70634. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70635. };
  70636. /**
  70637. * Import meshes into a scene
  70638. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70639. * @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)
  70640. * @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)
  70641. * @param scene the instance of BABYLON.Scene to append to
  70642. * @param onProgress a callback with a progress event for each file being loaded
  70643. * @param pluginExtension the extension used to determine the plugin
  70644. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70645. */
  70646. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70647. if (sceneFilename === void 0) { sceneFilename = ""; }
  70648. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70649. if (onProgress === void 0) { onProgress = null; }
  70650. if (pluginExtension === void 0) { pluginExtension = null; }
  70651. return new Promise(function (resolve, reject) {
  70652. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70653. resolve({
  70654. meshes: meshes,
  70655. particleSystems: particleSystems,
  70656. skeletons: skeletons,
  70657. animationGroups: animationGroups
  70658. });
  70659. }, onProgress, function (scene, message, exception) {
  70660. reject(exception || new Error(message));
  70661. }, pluginExtension);
  70662. });
  70663. };
  70664. /**
  70665. * Load a scene
  70666. * @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)
  70667. * @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)
  70668. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70669. * @param onSuccess a callback with the scene when import succeeds
  70670. * @param onProgress a callback with a progress event for each file being loaded
  70671. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70672. * @param pluginExtension the extension used to determine the plugin
  70673. * @returns The loaded plugin
  70674. */
  70675. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70676. if (onSuccess === void 0) { onSuccess = null; }
  70677. if (onProgress === void 0) { onProgress = null; }
  70678. if (onError === void 0) { onError = null; }
  70679. if (pluginExtension === void 0) { pluginExtension = null; }
  70680. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70681. };
  70682. /**
  70683. * Load a scene
  70684. * @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)
  70685. * @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)
  70686. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70687. * @param onProgress a callback with a progress event for each file being loaded
  70688. * @param pluginExtension the extension used to determine the plugin
  70689. * @returns The loaded scene
  70690. */
  70691. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70692. if (onProgress === void 0) { onProgress = null; }
  70693. if (pluginExtension === void 0) { pluginExtension = null; }
  70694. return new Promise(function (resolve, reject) {
  70695. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70696. resolve(scene);
  70697. }, onProgress, function (scene, message, exception) {
  70698. reject(exception || new Error(message));
  70699. }, pluginExtension);
  70700. });
  70701. };
  70702. /**
  70703. * Append a scene
  70704. * @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)
  70705. * @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)
  70706. * @param scene is the instance of BABYLON.Scene to append to
  70707. * @param onSuccess a callback with the scene when import succeeds
  70708. * @param onProgress a callback with a progress event for each file being loaded
  70709. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70710. * @param pluginExtension the extension used to determine the plugin
  70711. * @returns The loaded plugin
  70712. */
  70713. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70714. if (sceneFilename === void 0) { sceneFilename = ""; }
  70715. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70716. if (onSuccess === void 0) { onSuccess = null; }
  70717. if (onProgress === void 0) { onProgress = null; }
  70718. if (onError === void 0) { onError = null; }
  70719. if (pluginExtension === void 0) { pluginExtension = null; }
  70720. if (!scene) {
  70721. BABYLON.Tools.Error("No scene available to append to");
  70722. return null;
  70723. }
  70724. if (!sceneFilename) {
  70725. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70726. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70727. }
  70728. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70729. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70730. return null;
  70731. }
  70732. if (SceneLoader.ShowLoadingScreen) {
  70733. scene.getEngine().displayLoadingUI();
  70734. }
  70735. var loadingToken = {};
  70736. scene._addPendingData(loadingToken);
  70737. var disposeHandler = function () {
  70738. scene._removePendingData(loadingToken);
  70739. scene.getEngine().hideLoadingUI();
  70740. };
  70741. var errorHandler = function (message, exception) {
  70742. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70743. if (onError) {
  70744. onError(scene, errorMessage, exception);
  70745. }
  70746. else {
  70747. BABYLON.Tools.Error(errorMessage);
  70748. // should the exception be thrown?
  70749. }
  70750. disposeHandler();
  70751. };
  70752. var progressHandler = onProgress ? function (event) {
  70753. try {
  70754. onProgress(event);
  70755. }
  70756. catch (e) {
  70757. errorHandler("Error in onProgress callback", e);
  70758. }
  70759. } : undefined;
  70760. var successHandler = function () {
  70761. if (onSuccess) {
  70762. try {
  70763. onSuccess(scene);
  70764. }
  70765. catch (e) {
  70766. errorHandler("Error in onSuccess callback", e);
  70767. }
  70768. }
  70769. scene._removePendingData(loadingToken);
  70770. };
  70771. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70772. if (sceneFilename === "") {
  70773. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70774. }
  70775. if (plugin.load) {
  70776. var syncedPlugin = plugin;
  70777. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70778. return;
  70779. }
  70780. scene.loadingPluginName = plugin.name;
  70781. successHandler();
  70782. }
  70783. else {
  70784. var asyncedPlugin = plugin;
  70785. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70786. scene.loadingPluginName = plugin.name;
  70787. successHandler();
  70788. }).catch(function (error) {
  70789. errorHandler(error.message, error);
  70790. });
  70791. }
  70792. if (SceneLoader.ShowLoadingScreen) {
  70793. scene.executeWhenReady(function () {
  70794. scene.getEngine().hideLoadingUI();
  70795. });
  70796. }
  70797. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70798. };
  70799. /**
  70800. * Append a scene
  70801. * @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)
  70802. * @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)
  70803. * @param scene is the instance of BABYLON.Scene to append to
  70804. * @param onProgress a callback with a progress event for each file being loaded
  70805. * @param pluginExtension the extension used to determine the plugin
  70806. * @returns The given scene
  70807. */
  70808. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70809. if (sceneFilename === void 0) { sceneFilename = ""; }
  70810. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70811. if (onProgress === void 0) { onProgress = null; }
  70812. if (pluginExtension === void 0) { pluginExtension = null; }
  70813. return new Promise(function (resolve, reject) {
  70814. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70815. resolve(scene);
  70816. }, onProgress, function (scene, message, exception) {
  70817. reject(exception || new Error(message));
  70818. }, pluginExtension);
  70819. });
  70820. };
  70821. /**
  70822. * Load a scene into an asset container
  70823. * @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)
  70824. * @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)
  70825. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70826. * @param onSuccess a callback with the scene when import succeeds
  70827. * @param onProgress a callback with a progress event for each file being loaded
  70828. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70829. * @param pluginExtension the extension used to determine the plugin
  70830. * @returns The loaded plugin
  70831. */
  70832. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70833. if (sceneFilename === void 0) { sceneFilename = ""; }
  70834. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70835. if (onSuccess === void 0) { onSuccess = null; }
  70836. if (onProgress === void 0) { onProgress = null; }
  70837. if (onError === void 0) { onError = null; }
  70838. if (pluginExtension === void 0) { pluginExtension = null; }
  70839. if (!scene) {
  70840. BABYLON.Tools.Error("No scene available to load asset container to");
  70841. return null;
  70842. }
  70843. if (!sceneFilename) {
  70844. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70845. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70846. }
  70847. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70848. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70849. return null;
  70850. }
  70851. var loadingToken = {};
  70852. scene._addPendingData(loadingToken);
  70853. var disposeHandler = function () {
  70854. scene._removePendingData(loadingToken);
  70855. };
  70856. var errorHandler = function (message, exception) {
  70857. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70858. if (onError) {
  70859. onError(scene, errorMessage, exception);
  70860. }
  70861. else {
  70862. BABYLON.Tools.Error(errorMessage);
  70863. // should the exception be thrown?
  70864. }
  70865. disposeHandler();
  70866. };
  70867. var progressHandler = onProgress ? function (event) {
  70868. try {
  70869. onProgress(event);
  70870. }
  70871. catch (e) {
  70872. errorHandler("Error in onProgress callback", e);
  70873. }
  70874. } : undefined;
  70875. var successHandler = function (assets) {
  70876. if (onSuccess) {
  70877. try {
  70878. onSuccess(assets);
  70879. }
  70880. catch (e) {
  70881. errorHandler("Error in onSuccess callback", e);
  70882. }
  70883. }
  70884. scene._removePendingData(loadingToken);
  70885. };
  70886. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70887. if (plugin.loadAssetContainer) {
  70888. var syncedPlugin = plugin;
  70889. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  70890. if (!assetContainer) {
  70891. return;
  70892. }
  70893. scene.loadingPluginName = plugin.name;
  70894. successHandler(assetContainer);
  70895. }
  70896. else if (plugin.loadAssetContainerAsync) {
  70897. var asyncedPlugin = plugin;
  70898. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  70899. scene.loadingPluginName = plugin.name;
  70900. successHandler(assetContainer);
  70901. }).catch(function (error) {
  70902. errorHandler(error.message, error);
  70903. });
  70904. }
  70905. else {
  70906. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  70907. }
  70908. if (SceneLoader.ShowLoadingScreen) {
  70909. scene.executeWhenReady(function () {
  70910. scene.getEngine().hideLoadingUI();
  70911. });
  70912. }
  70913. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70914. };
  70915. /**
  70916. * Load a scene into an asset container
  70917. * @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)
  70918. * @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)
  70919. * @param scene is the instance of BABYLON.Scene to append to
  70920. * @param onProgress a callback with a progress event for each file being loaded
  70921. * @param pluginExtension the extension used to determine the plugin
  70922. * @returns The loaded asset container
  70923. */
  70924. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70925. if (sceneFilename === void 0) { sceneFilename = ""; }
  70926. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70927. if (onProgress === void 0) { onProgress = null; }
  70928. if (pluginExtension === void 0) { pluginExtension = null; }
  70929. return new Promise(function (resolve, reject) {
  70930. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70931. resolve(assetContainer);
  70932. }, onProgress, function (scene, message, exception) {
  70933. reject(exception || new Error(message));
  70934. }, pluginExtension);
  70935. });
  70936. };
  70937. // Flags
  70938. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70939. SceneLoader._ShowLoadingScreen = true;
  70940. SceneLoader._CleanBoneMatrixWeights = false;
  70941. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70942. // Members
  70943. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70944. SceneLoader._registeredPlugins = {};
  70945. return SceneLoader;
  70946. }());
  70947. BABYLON.SceneLoader = SceneLoader;
  70948. ;
  70949. })(BABYLON || (BABYLON = {}));
  70950. //# sourceMappingURL=babylon.sceneLoader.js.map
  70951. var BABYLON;
  70952. (function (BABYLON) {
  70953. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70954. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70955. var parsedMaterial = parsedData.materials[index];
  70956. if (parsedMaterial.id === id) {
  70957. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70958. }
  70959. }
  70960. return null;
  70961. };
  70962. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70963. for (var i in names) {
  70964. if (mesh.name === names[i]) {
  70965. hierarchyIds.push(mesh.id);
  70966. return true;
  70967. }
  70968. }
  70969. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70970. hierarchyIds.push(mesh.id);
  70971. return true;
  70972. }
  70973. return false;
  70974. };
  70975. var logOperation = function (operation, producer) {
  70976. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70977. };
  70978. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  70979. if (addToScene === void 0) { addToScene = false; }
  70980. var container = new BABYLON.AssetContainer(scene);
  70981. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70982. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70983. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70984. // and avoid problems with multiple concurrent .babylon loads.
  70985. var log = "importScene has failed JSON parse";
  70986. try {
  70987. var parsedData = JSON.parse(data);
  70988. log = "";
  70989. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70990. var index;
  70991. var cache;
  70992. // Lights
  70993. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  70994. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  70995. var parsedLight = parsedData.lights[index];
  70996. var light = BABYLON.Light.Parse(parsedLight, scene);
  70997. if (light) {
  70998. container.lights.push(light);
  70999. log += (index === 0 ? "\n\tLights:" : "");
  71000. log += "\n\t\t" + light.toString(fullDetails);
  71001. }
  71002. }
  71003. }
  71004. // Animations
  71005. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  71006. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  71007. var parsedAnimation = parsedData.animations[index];
  71008. var animation = BABYLON.Animation.Parse(parsedAnimation);
  71009. scene.animations.push(animation);
  71010. container.animations.push(animation);
  71011. log += (index === 0 ? "\n\tAnimations:" : "");
  71012. log += "\n\t\t" + animation.toString(fullDetails);
  71013. }
  71014. }
  71015. // Materials
  71016. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  71017. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71018. var parsedMaterial = parsedData.materials[index];
  71019. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71020. container.materials.push(mat);
  71021. log += (index === 0 ? "\n\tMaterials:" : "");
  71022. log += "\n\t\t" + mat.toString(fullDetails);
  71023. }
  71024. }
  71025. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71026. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  71027. var parsedMultiMaterial = parsedData.multiMaterials[index];
  71028. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71029. container.multiMaterials.push(mmat);
  71030. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  71031. log += "\n\t\t" + mmat.toString(fullDetails);
  71032. }
  71033. }
  71034. // Morph targets
  71035. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71036. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71037. var managerData = _a[_i];
  71038. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  71039. }
  71040. }
  71041. // Skeletons
  71042. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71043. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  71044. var parsedSkeleton = parsedData.skeletons[index];
  71045. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71046. container.skeletons.push(skeleton);
  71047. log += (index === 0 ? "\n\tSkeletons:" : "");
  71048. log += "\n\t\t" + skeleton.toString(fullDetails);
  71049. }
  71050. }
  71051. // Geometries
  71052. var geometries = parsedData.geometries;
  71053. if (geometries !== undefined && geometries !== null) {
  71054. var addedGeometry = new Array();
  71055. // Boxes
  71056. var boxes = geometries.boxes;
  71057. if (boxes !== undefined && boxes !== null) {
  71058. for (index = 0, cache = boxes.length; index < cache; index++) {
  71059. var parsedBox = boxes[index];
  71060. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  71061. }
  71062. }
  71063. // Spheres
  71064. var spheres = geometries.spheres;
  71065. if (spheres !== undefined && spheres !== null) {
  71066. for (index = 0, cache = spheres.length; index < cache; index++) {
  71067. var parsedSphere = spheres[index];
  71068. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  71069. }
  71070. }
  71071. // Cylinders
  71072. var cylinders = geometries.cylinders;
  71073. if (cylinders !== undefined && cylinders !== null) {
  71074. for (index = 0, cache = cylinders.length; index < cache; index++) {
  71075. var parsedCylinder = cylinders[index];
  71076. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  71077. }
  71078. }
  71079. // Toruses
  71080. var toruses = geometries.toruses;
  71081. if (toruses !== undefined && toruses !== null) {
  71082. for (index = 0, cache = toruses.length; index < cache; index++) {
  71083. var parsedTorus = toruses[index];
  71084. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  71085. }
  71086. }
  71087. // Grounds
  71088. var grounds = geometries.grounds;
  71089. if (grounds !== undefined && grounds !== null) {
  71090. for (index = 0, cache = grounds.length; index < cache; index++) {
  71091. var parsedGround = grounds[index];
  71092. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  71093. }
  71094. }
  71095. // Planes
  71096. var planes = geometries.planes;
  71097. if (planes !== undefined && planes !== null) {
  71098. for (index = 0, cache = planes.length; index < cache; index++) {
  71099. var parsedPlane = planes[index];
  71100. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  71101. }
  71102. }
  71103. // TorusKnots
  71104. var torusKnots = geometries.torusKnots;
  71105. if (torusKnots !== undefined && torusKnots !== null) {
  71106. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  71107. var parsedTorusKnot = torusKnots[index];
  71108. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  71109. }
  71110. }
  71111. // VertexData
  71112. var vertexData = geometries.vertexData;
  71113. if (vertexData !== undefined && vertexData !== null) {
  71114. for (index = 0, cache = vertexData.length; index < cache; index++) {
  71115. var parsedVertexData = vertexData[index];
  71116. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  71117. }
  71118. }
  71119. addedGeometry.forEach(function (g) {
  71120. if (g) {
  71121. container.geometries.push(g);
  71122. }
  71123. });
  71124. }
  71125. // Transform nodes
  71126. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  71127. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  71128. var parsedTransformNode = parsedData.transformNodes[index];
  71129. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  71130. container.transformNodes.push(node);
  71131. }
  71132. }
  71133. // Meshes
  71134. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71135. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71136. var parsedMesh = parsedData.meshes[index];
  71137. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71138. container.meshes.push(mesh);
  71139. log += (index === 0 ? "\n\tMeshes:" : "");
  71140. log += "\n\t\t" + mesh.toString(fullDetails);
  71141. }
  71142. }
  71143. // Cameras
  71144. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  71145. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  71146. var parsedCamera = parsedData.cameras[index];
  71147. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  71148. container.cameras.push(camera);
  71149. log += (index === 0 ? "\n\tCameras:" : "");
  71150. log += "\n\t\t" + camera.toString(fullDetails);
  71151. }
  71152. }
  71153. // Browsing all the graph to connect the dots
  71154. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  71155. var camera = scene.cameras[index];
  71156. if (camera._waitingParentId) {
  71157. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  71158. camera._waitingParentId = null;
  71159. }
  71160. }
  71161. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71162. var light_1 = scene.lights[index];
  71163. if (light_1 && light_1._waitingParentId) {
  71164. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  71165. light_1._waitingParentId = null;
  71166. }
  71167. }
  71168. // Sounds
  71169. // TODO: add sound
  71170. var loadedSounds = [];
  71171. var loadedSound;
  71172. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71173. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71174. var parsedSound = parsedData.sounds[index];
  71175. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71176. if (!parsedSound.url)
  71177. parsedSound.url = parsedSound.name;
  71178. if (!loadedSounds[parsedSound.url]) {
  71179. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71180. loadedSounds[parsedSound.url] = loadedSound;
  71181. container.sounds.push(loadedSound);
  71182. }
  71183. else {
  71184. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71185. }
  71186. }
  71187. else {
  71188. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71189. }
  71190. }
  71191. }
  71192. loadedSounds = [];
  71193. // Connect parents & children and parse actions
  71194. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  71195. var transformNode = scene.transformNodes[index];
  71196. if (transformNode._waitingParentId) {
  71197. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  71198. transformNode._waitingParentId = null;
  71199. }
  71200. }
  71201. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71202. var mesh = scene.meshes[index];
  71203. if (mesh._waitingParentId) {
  71204. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  71205. mesh._waitingParentId = null;
  71206. }
  71207. if (mesh._waitingActions) {
  71208. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  71209. mesh._waitingActions = null;
  71210. }
  71211. }
  71212. // freeze world matrix application
  71213. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71214. var currentMesh = scene.meshes[index];
  71215. if (currentMesh._waitingFreezeWorldMatrix) {
  71216. currentMesh.freezeWorldMatrix();
  71217. currentMesh._waitingFreezeWorldMatrix = null;
  71218. }
  71219. else {
  71220. currentMesh.computeWorldMatrix(true);
  71221. }
  71222. }
  71223. // Shadows
  71224. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71225. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71226. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71227. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71228. // SG would be available on their associated lights
  71229. }
  71230. }
  71231. // Lights exclusions / inclusions
  71232. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71233. var light_2 = scene.lights[index];
  71234. // Excluded check
  71235. if (light_2._excludedMeshesIds.length > 0) {
  71236. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  71237. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  71238. if (excludedMesh) {
  71239. light_2.excludedMeshes.push(excludedMesh);
  71240. }
  71241. }
  71242. light_2._excludedMeshesIds = [];
  71243. }
  71244. // Included check
  71245. if (light_2._includedOnlyMeshesIds.length > 0) {
  71246. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71247. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71248. if (includedOnlyMesh) {
  71249. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71250. }
  71251. }
  71252. light_2._includedOnlyMeshesIds = [];
  71253. }
  71254. }
  71255. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71256. // Actions (scene)
  71257. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71258. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71259. }
  71260. if (!addToScene) {
  71261. container.removeAllFromScene();
  71262. }
  71263. }
  71264. catch (err) {
  71265. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  71266. if (onError) {
  71267. onError(msg, err);
  71268. }
  71269. else {
  71270. BABYLON.Tools.Log(msg);
  71271. throw err;
  71272. }
  71273. }
  71274. finally {
  71275. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71276. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71277. }
  71278. }
  71279. return container;
  71280. };
  71281. BABYLON.SceneLoader.RegisterPlugin({
  71282. name: "babylon.js",
  71283. extensions: ".babylon",
  71284. canDirectLoad: function (data) {
  71285. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71286. return true;
  71287. }
  71288. return false;
  71289. },
  71290. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71291. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71292. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71293. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71294. // and avoid problems with multiple concurrent .babylon loads.
  71295. var log = "importMesh has failed JSON parse";
  71296. try {
  71297. var parsedData = JSON.parse(data);
  71298. log = "";
  71299. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71300. if (!meshesNames) {
  71301. meshesNames = null;
  71302. }
  71303. else if (!Array.isArray(meshesNames)) {
  71304. meshesNames = [meshesNames];
  71305. }
  71306. var hierarchyIds = new Array();
  71307. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71308. var loadedSkeletonsIds = [];
  71309. var loadedMaterialsIds = [];
  71310. var index;
  71311. var cache;
  71312. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71313. var parsedMesh = parsedData.meshes[index];
  71314. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71315. if (meshesNames !== null) {
  71316. // Remove found mesh name from list.
  71317. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71318. }
  71319. //Geometry?
  71320. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71321. //does the file contain geometries?
  71322. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71323. //find the correct geometry and add it to the scene
  71324. var found = false;
  71325. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71326. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71327. return;
  71328. }
  71329. else {
  71330. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71331. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71332. switch (geometryType) {
  71333. case "boxes":
  71334. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71335. break;
  71336. case "spheres":
  71337. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71338. break;
  71339. case "cylinders":
  71340. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71341. break;
  71342. case "toruses":
  71343. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71344. break;
  71345. case "grounds":
  71346. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71347. break;
  71348. case "planes":
  71349. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71350. break;
  71351. case "torusKnots":
  71352. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71353. break;
  71354. case "vertexData":
  71355. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71356. break;
  71357. }
  71358. found = true;
  71359. }
  71360. });
  71361. }
  71362. });
  71363. if (found === false) {
  71364. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71365. }
  71366. }
  71367. }
  71368. // Material ?
  71369. if (parsedMesh.materialId) {
  71370. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71371. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71372. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71373. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71374. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71375. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71376. var subMatId = parsedMultiMaterial.materials[matIndex];
  71377. loadedMaterialsIds.push(subMatId);
  71378. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71379. if (mat) {
  71380. log += "\n\tMaterial " + mat.toString(fullDetails);
  71381. }
  71382. }
  71383. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71384. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71385. if (mmat) {
  71386. materialFound = true;
  71387. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71388. }
  71389. break;
  71390. }
  71391. }
  71392. }
  71393. if (materialFound === false) {
  71394. loadedMaterialsIds.push(parsedMesh.materialId);
  71395. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71396. if (!mat) {
  71397. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71398. }
  71399. else {
  71400. log += "\n\tMaterial " + mat.toString(fullDetails);
  71401. }
  71402. }
  71403. }
  71404. // Skeleton ?
  71405. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71406. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71407. if (skeletonAlreadyLoaded === false) {
  71408. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71409. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71410. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71411. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71412. skeletons.push(skeleton);
  71413. loadedSkeletonsIds.push(parsedSkeleton.id);
  71414. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71415. }
  71416. }
  71417. }
  71418. }
  71419. // Morph targets ?
  71420. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71421. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71422. var managerData = _a[_i];
  71423. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71424. }
  71425. }
  71426. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71427. meshes.push(mesh);
  71428. log += "\n\tMesh " + mesh.toString(fullDetails);
  71429. }
  71430. }
  71431. // Connecting parents
  71432. var currentMesh;
  71433. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71434. currentMesh = scene.meshes[index];
  71435. if (currentMesh._waitingParentId) {
  71436. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71437. currentMesh._waitingParentId = null;
  71438. }
  71439. }
  71440. // freeze and compute world matrix application
  71441. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71442. currentMesh = scene.meshes[index];
  71443. if (currentMesh._waitingFreezeWorldMatrix) {
  71444. currentMesh.freezeWorldMatrix();
  71445. currentMesh._waitingFreezeWorldMatrix = null;
  71446. }
  71447. else {
  71448. currentMesh.computeWorldMatrix(true);
  71449. }
  71450. }
  71451. }
  71452. // Particles
  71453. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  71454. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  71455. if (parser) {
  71456. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  71457. var parsedParticleSystem = parsedData.particleSystems[index];
  71458. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  71459. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  71460. }
  71461. }
  71462. }
  71463. }
  71464. return true;
  71465. }
  71466. catch (err) {
  71467. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  71468. if (onError) {
  71469. onError(msg, err);
  71470. }
  71471. else {
  71472. BABYLON.Tools.Log(msg);
  71473. throw err;
  71474. }
  71475. }
  71476. finally {
  71477. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71478. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71479. }
  71480. }
  71481. return false;
  71482. },
  71483. load: function (scene, data, rootUrl, onError) {
  71484. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71485. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71486. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71487. // and avoid problems with multiple concurrent .babylon loads.
  71488. var log = "importScene has failed JSON parse";
  71489. try {
  71490. var parsedData = JSON.parse(data);
  71491. log = "";
  71492. // Scene
  71493. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  71494. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  71495. }
  71496. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  71497. scene.autoClear = parsedData.autoClear;
  71498. }
  71499. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  71500. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  71501. }
  71502. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  71503. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  71504. }
  71505. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  71506. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  71507. }
  71508. // Fog
  71509. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  71510. scene.fogMode = parsedData.fogMode;
  71511. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  71512. scene.fogStart = parsedData.fogStart;
  71513. scene.fogEnd = parsedData.fogEnd;
  71514. scene.fogDensity = parsedData.fogDensity;
  71515. log += "\tFog mode for scene: ";
  71516. switch (scene.fogMode) {
  71517. // getters not compiling, so using hardcoded
  71518. case 1:
  71519. log += "exp\n";
  71520. break;
  71521. case 2:
  71522. log += "exp2\n";
  71523. break;
  71524. case 3:
  71525. log += "linear\n";
  71526. break;
  71527. }
  71528. }
  71529. //Physics
  71530. if (parsedData.physicsEnabled) {
  71531. var physicsPlugin;
  71532. if (parsedData.physicsEngine === "cannon") {
  71533. physicsPlugin = new BABYLON.CannonJSPlugin();
  71534. }
  71535. else if (parsedData.physicsEngine === "oimo") {
  71536. physicsPlugin = new BABYLON.OimoJSPlugin();
  71537. }
  71538. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  71539. //else - default engine, which is currently oimo
  71540. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  71541. scene.enablePhysics(physicsGravity, physicsPlugin);
  71542. }
  71543. // Metadata
  71544. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  71545. scene.metadata = parsedData.metadata;
  71546. }
  71547. //collisions, if defined. otherwise, default is true
  71548. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  71549. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71550. }
  71551. scene.workerCollisions = !!parsedData.workerCollisions;
  71552. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71553. if (!container) {
  71554. return false;
  71555. }
  71556. if (parsedData.autoAnimate) {
  71557. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71558. }
  71559. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71560. scene.setActiveCameraByID(parsedData.activeCameraID);
  71561. }
  71562. // Environment texture
  71563. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71564. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71565. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71566. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71567. if (parsedData.environmentTextureRotationY) {
  71568. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71569. }
  71570. scene.environmentTexture = hdrTexture;
  71571. }
  71572. else {
  71573. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71574. if (parsedData.environmentTextureRotationY) {
  71575. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71576. }
  71577. scene.environmentTexture = cubeTexture;
  71578. }
  71579. if (parsedData.createDefaultSkybox === true) {
  71580. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71581. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71582. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71583. }
  71584. }
  71585. // Finish
  71586. return true;
  71587. }
  71588. catch (err) {
  71589. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71590. if (onError) {
  71591. onError(msg, err);
  71592. }
  71593. else {
  71594. BABYLON.Tools.Log(msg);
  71595. throw err;
  71596. }
  71597. }
  71598. finally {
  71599. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71600. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71601. }
  71602. }
  71603. return false;
  71604. },
  71605. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71606. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71607. return container;
  71608. }
  71609. });
  71610. })(BABYLON || (BABYLON = {}));
  71611. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71612. var BABYLON;
  71613. (function (BABYLON) {
  71614. var FilesInput = /** @class */ (function () {
  71615. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71616. this.onProcessFileCallback = function () { return true; };
  71617. this._engine = engine;
  71618. this._currentScene = scene;
  71619. this._sceneLoadedCallback = sceneLoadedCallback;
  71620. this._progressCallback = progressCallback;
  71621. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71622. this._textureLoadingCallback = textureLoadingCallback;
  71623. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71624. this._onReloadCallback = onReloadCallback;
  71625. this._errorCallback = errorCallback;
  71626. }
  71627. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71628. var _this = this;
  71629. if (elementToMonitor) {
  71630. this._elementToMonitor = elementToMonitor;
  71631. this._dragEnterHandler = function (e) { _this.drag(e); };
  71632. this._dragOverHandler = function (e) { _this.drag(e); };
  71633. this._dropHandler = function (e) { _this.drop(e); };
  71634. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71635. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71636. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71637. }
  71638. };
  71639. FilesInput.prototype.dispose = function () {
  71640. if (!this._elementToMonitor) {
  71641. return;
  71642. }
  71643. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71644. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71645. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71646. };
  71647. FilesInput.prototype.renderFunction = function () {
  71648. if (this._additionalRenderLoopLogicCallback) {
  71649. this._additionalRenderLoopLogicCallback();
  71650. }
  71651. if (this._currentScene) {
  71652. if (this._textureLoadingCallback) {
  71653. var remaining = this._currentScene.getWaitingItemsCount();
  71654. if (remaining > 0) {
  71655. this._textureLoadingCallback(remaining);
  71656. }
  71657. }
  71658. this._currentScene.render();
  71659. }
  71660. };
  71661. FilesInput.prototype.drag = function (e) {
  71662. e.stopPropagation();
  71663. e.preventDefault();
  71664. };
  71665. FilesInput.prototype.drop = function (eventDrop) {
  71666. eventDrop.stopPropagation();
  71667. eventDrop.preventDefault();
  71668. this.loadFiles(eventDrop);
  71669. };
  71670. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71671. var _this = this;
  71672. var reader = folder.createReader();
  71673. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71674. reader.readEntries(function (entries) {
  71675. remaining.count += entries.length;
  71676. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71677. var entry = entries_1[_i];
  71678. if (entry.isFile) {
  71679. entry.file(function (file) {
  71680. file.correctName = relativePath + file.name;
  71681. files.push(file);
  71682. if (--remaining.count === 0) {
  71683. callback();
  71684. }
  71685. });
  71686. }
  71687. else if (entry.isDirectory) {
  71688. _this._traverseFolder(entry, files, remaining, callback);
  71689. }
  71690. }
  71691. if (--remaining.count) {
  71692. callback();
  71693. }
  71694. });
  71695. };
  71696. FilesInput.prototype._processFiles = function (files) {
  71697. for (var i = 0; i < files.length; i++) {
  71698. var name = files[i].correctName.toLowerCase();
  71699. var extension = name.split('.').pop();
  71700. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71701. continue;
  71702. }
  71703. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71704. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71705. this._sceneFileToLoad = files[i];
  71706. }
  71707. else {
  71708. FilesInput.FilesToLoad[name] = files[i];
  71709. }
  71710. }
  71711. };
  71712. FilesInput.prototype.loadFiles = function (event) {
  71713. var _this = this;
  71714. // Handling data transfer via drag'n'drop
  71715. if (event && event.dataTransfer && event.dataTransfer.files) {
  71716. this._filesToLoad = event.dataTransfer.files;
  71717. }
  71718. // Handling files from input files
  71719. if (event && event.target && event.target.files) {
  71720. this._filesToLoad = event.target.files;
  71721. }
  71722. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  71723. return;
  71724. }
  71725. if (this._startingProcessingFilesCallback) {
  71726. this._startingProcessingFilesCallback(this._filesToLoad);
  71727. }
  71728. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71729. var files_1 = new Array();
  71730. var folders = [];
  71731. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71732. for (var i = 0; i < this._filesToLoad.length; i++) {
  71733. var fileToLoad = this._filesToLoad[i];
  71734. var name_1 = fileToLoad.name.toLowerCase();
  71735. var entry = void 0;
  71736. fileToLoad.correctName = name_1;
  71737. if (items) {
  71738. var item = items[i];
  71739. if (item.getAsEntry) {
  71740. entry = item.getAsEntry();
  71741. }
  71742. else if (item.webkitGetAsEntry) {
  71743. entry = item.webkitGetAsEntry();
  71744. }
  71745. }
  71746. if (!entry) {
  71747. files_1.push(fileToLoad);
  71748. }
  71749. else {
  71750. if (entry.isDirectory) {
  71751. folders.push(entry);
  71752. }
  71753. else {
  71754. files_1.push(fileToLoad);
  71755. }
  71756. }
  71757. }
  71758. if (folders.length === 0) {
  71759. this._processFiles(files_1);
  71760. this._processReload();
  71761. }
  71762. else {
  71763. var remaining = { count: folders.length };
  71764. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71765. var folder = folders_1[_i];
  71766. this._traverseFolder(folder, files_1, remaining, function () {
  71767. _this._processFiles(files_1);
  71768. if (remaining.count === 0) {
  71769. _this._processReload();
  71770. }
  71771. });
  71772. }
  71773. }
  71774. }
  71775. };
  71776. FilesInput.prototype._processReload = function () {
  71777. if (this._onReloadCallback) {
  71778. this._onReloadCallback(this._sceneFileToLoad);
  71779. }
  71780. else {
  71781. this.reload();
  71782. }
  71783. };
  71784. FilesInput.prototype.reload = function () {
  71785. var _this = this;
  71786. // If a scene file has been provided
  71787. if (this._sceneFileToLoad) {
  71788. if (this._currentScene) {
  71789. if (BABYLON.Tools.errorsCount > 0) {
  71790. BABYLON.Tools.ClearLogCache();
  71791. }
  71792. this._engine.stopRenderLoop();
  71793. }
  71794. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71795. if (_this._progressCallback) {
  71796. _this._progressCallback(progress);
  71797. }
  71798. }).then(function (scene) {
  71799. if (_this._currentScene) {
  71800. _this._currentScene.dispose();
  71801. }
  71802. _this._currentScene = scene;
  71803. if (_this._sceneLoadedCallback) {
  71804. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71805. }
  71806. // Wait for textures and shaders to be ready
  71807. _this._currentScene.executeWhenReady(function () {
  71808. _this._engine.runRenderLoop(function () {
  71809. _this.renderFunction();
  71810. });
  71811. });
  71812. }).catch(function (error) {
  71813. if (_this._errorCallback) {
  71814. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71815. }
  71816. });
  71817. }
  71818. else {
  71819. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71820. }
  71821. };
  71822. FilesInput.FilesToLoad = {};
  71823. return FilesInput;
  71824. }());
  71825. BABYLON.FilesInput = FilesInput;
  71826. })(BABYLON || (BABYLON = {}));
  71827. //# sourceMappingURL=babylon.filesInput.js.map
  71828. var BABYLON;
  71829. (function (BABYLON) {
  71830. var Tags = /** @class */ (function () {
  71831. function Tags() {
  71832. }
  71833. Tags.EnableFor = function (obj) {
  71834. obj._tags = obj._tags || {};
  71835. obj.hasTags = function () {
  71836. return Tags.HasTags(obj);
  71837. };
  71838. obj.addTags = function (tagsString) {
  71839. return Tags.AddTagsTo(obj, tagsString);
  71840. };
  71841. obj.removeTags = function (tagsString) {
  71842. return Tags.RemoveTagsFrom(obj, tagsString);
  71843. };
  71844. obj.matchesTagsQuery = function (tagsQuery) {
  71845. return Tags.MatchesQuery(obj, tagsQuery);
  71846. };
  71847. };
  71848. Tags.DisableFor = function (obj) {
  71849. delete obj._tags;
  71850. delete obj.hasTags;
  71851. delete obj.addTags;
  71852. delete obj.removeTags;
  71853. delete obj.matchesTagsQuery;
  71854. };
  71855. Tags.HasTags = function (obj) {
  71856. if (!obj._tags) {
  71857. return false;
  71858. }
  71859. return !BABYLON.Tools.IsEmpty(obj._tags);
  71860. };
  71861. Tags.GetTags = function (obj, asString) {
  71862. if (asString === void 0) { asString = true; }
  71863. if (!obj._tags) {
  71864. return null;
  71865. }
  71866. if (asString) {
  71867. var tagsArray = [];
  71868. for (var tag in obj._tags) {
  71869. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  71870. tagsArray.push(tag);
  71871. }
  71872. }
  71873. return tagsArray.join(" ");
  71874. }
  71875. else {
  71876. return obj._tags;
  71877. }
  71878. };
  71879. // the tags 'true' and 'false' are reserved and cannot be used as tags
  71880. // a tag cannot start with '||', '&&', and '!'
  71881. // it cannot contain whitespaces
  71882. Tags.AddTagsTo = function (obj, tagsString) {
  71883. if (!tagsString) {
  71884. return;
  71885. }
  71886. if (typeof tagsString !== "string") {
  71887. return;
  71888. }
  71889. var tags = tagsString.split(" ");
  71890. tags.forEach(function (tag, index, array) {
  71891. Tags._AddTagTo(obj, tag);
  71892. });
  71893. };
  71894. Tags._AddTagTo = function (obj, tag) {
  71895. tag = tag.trim();
  71896. if (tag === "" || tag === "true" || tag === "false") {
  71897. return;
  71898. }
  71899. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  71900. return;
  71901. }
  71902. Tags.EnableFor(obj);
  71903. obj._tags[tag] = true;
  71904. };
  71905. Tags.RemoveTagsFrom = function (obj, tagsString) {
  71906. if (!Tags.HasTags(obj)) {
  71907. return;
  71908. }
  71909. var tags = tagsString.split(" ");
  71910. for (var t in tags) {
  71911. Tags._RemoveTagFrom(obj, tags[t]);
  71912. }
  71913. };
  71914. Tags._RemoveTagFrom = function (obj, tag) {
  71915. delete obj._tags[tag];
  71916. };
  71917. Tags.MatchesQuery = function (obj, tagsQuery) {
  71918. if (tagsQuery === undefined) {
  71919. return true;
  71920. }
  71921. if (tagsQuery === "") {
  71922. return Tags.HasTags(obj);
  71923. }
  71924. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  71925. };
  71926. return Tags;
  71927. }());
  71928. BABYLON.Tags = Tags;
  71929. })(BABYLON || (BABYLON = {}));
  71930. //# sourceMappingURL=babylon.tags.js.map
  71931. var BABYLON;
  71932. (function (BABYLON) {
  71933. /**
  71934. * Class used to evalaute queries containing `and` and `or` operators
  71935. */
  71936. var AndOrNotEvaluator = /** @class */ (function () {
  71937. function AndOrNotEvaluator() {
  71938. }
  71939. /**
  71940. * Evaluate a query
  71941. * @param query defines the query to evaluate
  71942. * @param evaluateCallback defines the callback used to filter result
  71943. * @returns true if the query matches
  71944. */
  71945. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71946. if (!query.match(/\([^\(\)]*\)/g)) {
  71947. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71948. }
  71949. else {
  71950. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71951. // remove parenthesis
  71952. r = r.slice(1, r.length - 1);
  71953. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71954. });
  71955. }
  71956. if (query === "true") {
  71957. return true;
  71958. }
  71959. if (query === "false") {
  71960. return false;
  71961. }
  71962. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71963. };
  71964. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71965. evaluateCallback = evaluateCallback || (function (r) {
  71966. return r === "true" ? true : false;
  71967. });
  71968. var result;
  71969. var or = parenthesisContent.split("||");
  71970. for (var i in or) {
  71971. if (or.hasOwnProperty(i)) {
  71972. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71973. var and = ori.split("&&");
  71974. if (and.length > 1) {
  71975. for (var j = 0; j < and.length; ++j) {
  71976. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71977. if (andj !== "true" && andj !== "false") {
  71978. if (andj[0] === "!") {
  71979. result = !evaluateCallback(andj.substring(1));
  71980. }
  71981. else {
  71982. result = evaluateCallback(andj);
  71983. }
  71984. }
  71985. else {
  71986. result = andj === "true" ? true : false;
  71987. }
  71988. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  71989. ori = "false";
  71990. break;
  71991. }
  71992. }
  71993. }
  71994. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  71995. result = true;
  71996. break;
  71997. }
  71998. // result equals false (or undefined)
  71999. if (ori !== "true" && ori !== "false") {
  72000. if (ori[0] === "!") {
  72001. result = !evaluateCallback(ori.substring(1));
  72002. }
  72003. else {
  72004. result = evaluateCallback(ori);
  72005. }
  72006. }
  72007. else {
  72008. result = ori === "true" ? true : false;
  72009. }
  72010. }
  72011. }
  72012. // the whole parenthesis scope is replaced by 'true' or 'false'
  72013. return result ? "true" : "false";
  72014. };
  72015. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  72016. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  72017. // remove whitespaces
  72018. r = r.replace(/[\s]/g, function () { return ""; });
  72019. return r.length % 2 ? "!" : "";
  72020. });
  72021. booleanString = booleanString.trim();
  72022. if (booleanString === "!true") {
  72023. booleanString = "false";
  72024. }
  72025. else if (booleanString === "!false") {
  72026. booleanString = "true";
  72027. }
  72028. return booleanString;
  72029. };
  72030. return AndOrNotEvaluator;
  72031. }());
  72032. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  72033. })(BABYLON || (BABYLON = {}));
  72034. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  72035. var BABYLON;
  72036. (function (BABYLON) {
  72037. /**
  72038. * Class used to enable access to IndexedDB
  72039. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  72040. */
  72041. var Database = /** @class */ (function () {
  72042. /**
  72043. * Creates a new Database
  72044. * @param urlToScene defines the url to load the scene
  72045. * @param callbackManifestChecked defines the callback to use when manifest is checked
  72046. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  72047. */
  72048. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  72049. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  72050. var _this = this;
  72051. // Handling various flavors of prefixed version of IndexedDB
  72052. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  72053. this.callbackManifestChecked = callbackManifestChecked;
  72054. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  72055. this.db = null;
  72056. this._enableSceneOffline = false;
  72057. this._enableTexturesOffline = false;
  72058. this.manifestVersionFound = 0;
  72059. this.mustUpdateRessources = false;
  72060. this.hasReachedQuota = false;
  72061. if (!Database.IDBStorageEnabled) {
  72062. this.callbackManifestChecked(true);
  72063. }
  72064. else {
  72065. if (disableManifestCheck) {
  72066. this._enableSceneOffline = true;
  72067. this._enableTexturesOffline = true;
  72068. this.manifestVersionFound = 1;
  72069. BABYLON.Tools.SetImmediate(function () {
  72070. _this.callbackManifestChecked(true);
  72071. });
  72072. }
  72073. else {
  72074. this._checkManifestFile();
  72075. }
  72076. }
  72077. }
  72078. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  72079. /**
  72080. * Gets a boolean indicating if scene must be saved in the database
  72081. */
  72082. get: function () {
  72083. return this._enableSceneOffline;
  72084. },
  72085. enumerable: true,
  72086. configurable: true
  72087. });
  72088. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  72089. /**
  72090. * Gets a boolean indicating if textures must be saved in the database
  72091. */
  72092. get: function () {
  72093. return this._enableTexturesOffline;
  72094. },
  72095. enumerable: true,
  72096. configurable: true
  72097. });
  72098. Database.prototype._checkManifestFile = function () {
  72099. var _this = this;
  72100. var noManifestFile = function () {
  72101. _this._enableSceneOffline = false;
  72102. _this._enableTexturesOffline = false;
  72103. _this.callbackManifestChecked(false);
  72104. };
  72105. var timeStampUsed = false;
  72106. var manifestURL = this.currentSceneUrl + ".manifest";
  72107. var xhr = new XMLHttpRequest();
  72108. if (navigator.onLine) {
  72109. // Adding a timestamp to by-pass browsers' cache
  72110. timeStampUsed = true;
  72111. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  72112. }
  72113. xhr.open("GET", manifestURL, true);
  72114. xhr.addEventListener("load", function () {
  72115. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72116. try {
  72117. var manifestFile = JSON.parse(xhr.response);
  72118. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  72119. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  72120. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  72121. _this.manifestVersionFound = manifestFile.version;
  72122. }
  72123. if (_this.callbackManifestChecked) {
  72124. _this.callbackManifestChecked(true);
  72125. }
  72126. }
  72127. catch (ex) {
  72128. noManifestFile();
  72129. }
  72130. }
  72131. else {
  72132. noManifestFile();
  72133. }
  72134. }, false);
  72135. xhr.addEventListener("error", function (event) {
  72136. if (timeStampUsed) {
  72137. timeStampUsed = false;
  72138. // Let's retry without the timeStamp
  72139. // It could fail when coupled with HTML5 Offline API
  72140. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  72141. xhr.open("GET", retryManifestURL, true);
  72142. xhr.send();
  72143. }
  72144. else {
  72145. noManifestFile();
  72146. }
  72147. }, false);
  72148. try {
  72149. xhr.send();
  72150. }
  72151. catch (ex) {
  72152. BABYLON.Tools.Error("Error on XHR send request.");
  72153. this.callbackManifestChecked(false);
  72154. }
  72155. };
  72156. /**
  72157. * Open the database and make it available
  72158. * @param successCallback defines the callback to call on success
  72159. * @param errorCallback defines the callback to call on error
  72160. */
  72161. Database.prototype.openAsync = function (successCallback, errorCallback) {
  72162. var _this = this;
  72163. var handleError = function () {
  72164. _this.isSupported = false;
  72165. if (errorCallback)
  72166. errorCallback();
  72167. };
  72168. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  72169. // Your browser doesn't support IndexedDB
  72170. this.isSupported = false;
  72171. if (errorCallback)
  72172. errorCallback();
  72173. }
  72174. else {
  72175. // If the DB hasn't been opened or created yet
  72176. if (!this.db) {
  72177. this.hasReachedQuota = false;
  72178. this.isSupported = true;
  72179. var request = this.idbFactory.open("babylonjs", 1);
  72180. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  72181. request.onerror = function (event) {
  72182. handleError();
  72183. };
  72184. // executes when a version change transaction cannot complete due to other active transactions
  72185. request.onblocked = function (event) {
  72186. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  72187. handleError();
  72188. };
  72189. // DB has been opened successfully
  72190. request.onsuccess = function (event) {
  72191. _this.db = request.result;
  72192. successCallback();
  72193. };
  72194. // Initialization of the DB. Creating Scenes & Textures stores
  72195. request.onupgradeneeded = function (event) {
  72196. _this.db = (event.target).result;
  72197. if (_this.db) {
  72198. try {
  72199. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  72200. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  72201. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  72202. }
  72203. catch (ex) {
  72204. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  72205. handleError();
  72206. }
  72207. }
  72208. };
  72209. }
  72210. // DB has already been created and opened
  72211. else {
  72212. if (successCallback)
  72213. successCallback();
  72214. }
  72215. }
  72216. };
  72217. /**
  72218. * Loads an image from the database
  72219. * @param url defines the url to load from
  72220. * @param image defines the target DOM image
  72221. */
  72222. Database.prototype.loadImageFromDB = function (url, image) {
  72223. var _this = this;
  72224. var completeURL = Database._ReturnFullUrlLocation(url);
  72225. var saveAndLoadImage = function () {
  72226. if (!_this.hasReachedQuota && _this.db !== null) {
  72227. // the texture is not yet in the DB, let's try to save it
  72228. _this._saveImageIntoDBAsync(completeURL, image);
  72229. }
  72230. // If the texture is not in the DB and we've reached the DB quota limit
  72231. // let's load it directly from the web
  72232. else {
  72233. image.src = url;
  72234. }
  72235. };
  72236. if (!this.mustUpdateRessources) {
  72237. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  72238. }
  72239. // First time we're download the images or update requested in the manifest file by a version change
  72240. else {
  72241. saveAndLoadImage();
  72242. }
  72243. };
  72244. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72245. if (this.isSupported && this.db !== null) {
  72246. var texture;
  72247. var transaction = this.db.transaction(["textures"]);
  72248. transaction.onabort = function (event) {
  72249. image.src = url;
  72250. };
  72251. transaction.oncomplete = function (event) {
  72252. var blobTextureURL;
  72253. if (texture) {
  72254. var URL = window.URL || window.webkitURL;
  72255. blobTextureURL = URL.createObjectURL(texture.data);
  72256. image.onerror = function () {
  72257. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72258. image.src = url;
  72259. };
  72260. image.src = blobTextureURL;
  72261. }
  72262. else {
  72263. notInDBCallback();
  72264. }
  72265. };
  72266. var getRequest = transaction.objectStore("textures").get(url);
  72267. getRequest.onsuccess = function (event) {
  72268. texture = (event.target).result;
  72269. };
  72270. getRequest.onerror = function (event) {
  72271. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72272. image.src = url;
  72273. };
  72274. }
  72275. else {
  72276. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72277. image.src = url;
  72278. }
  72279. };
  72280. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72281. var _this = this;
  72282. if (this.isSupported) {
  72283. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72284. var generateBlobUrl = function () {
  72285. var blobTextureURL;
  72286. if (blob) {
  72287. var URL = window.URL || window.webkitURL;
  72288. try {
  72289. blobTextureURL = URL.createObjectURL(blob);
  72290. }
  72291. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72292. catch (ex) {
  72293. blobTextureURL = URL.createObjectURL(blob);
  72294. }
  72295. }
  72296. if (blobTextureURL) {
  72297. image.src = blobTextureURL;
  72298. }
  72299. };
  72300. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72301. var xhr = new XMLHttpRequest(), blob;
  72302. xhr.open("GET", url, true);
  72303. xhr.responseType = "blob";
  72304. xhr.addEventListener("load", function () {
  72305. if (xhr.status === 200 && _this.db) {
  72306. // Blob as response (XHR2)
  72307. blob = xhr.response;
  72308. var transaction = _this.db.transaction(["textures"], "readwrite");
  72309. // the transaction could abort because of a QuotaExceededError error
  72310. transaction.onabort = function (event) {
  72311. try {
  72312. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72313. var srcElement = (event.srcElement || event.target);
  72314. var error = srcElement.error;
  72315. if (error && error.name === "QuotaExceededError") {
  72316. _this.hasReachedQuota = true;
  72317. }
  72318. }
  72319. catch (ex) { }
  72320. generateBlobUrl();
  72321. };
  72322. transaction.oncomplete = function (event) {
  72323. generateBlobUrl();
  72324. };
  72325. var newTexture = { textureUrl: url, data: blob };
  72326. try {
  72327. // Put the blob into the dabase
  72328. var addRequest = transaction.objectStore("textures").put(newTexture);
  72329. addRequest.onsuccess = function (event) {
  72330. };
  72331. addRequest.onerror = function (event) {
  72332. generateBlobUrl();
  72333. };
  72334. }
  72335. catch (ex) {
  72336. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72337. if (ex.code === 25) {
  72338. Database.IsUASupportingBlobStorage = false;
  72339. }
  72340. image.src = url;
  72341. }
  72342. }
  72343. else {
  72344. image.src = url;
  72345. }
  72346. }, false);
  72347. xhr.addEventListener("error", function (event) {
  72348. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72349. image.src = url;
  72350. }, false);
  72351. xhr.send();
  72352. }
  72353. else {
  72354. image.src = url;
  72355. }
  72356. }
  72357. else {
  72358. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72359. image.src = url;
  72360. }
  72361. };
  72362. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72363. var _this = this;
  72364. var updateVersion = function () {
  72365. // the version is not yet in the DB or we need to update it
  72366. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72367. };
  72368. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72369. };
  72370. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72371. var _this = this;
  72372. if (this.isSupported && this.db) {
  72373. var version;
  72374. try {
  72375. var transaction = this.db.transaction(["versions"]);
  72376. transaction.oncomplete = function (event) {
  72377. if (version) {
  72378. // If the version in the JSON file is different from the version in DB
  72379. if (_this.manifestVersionFound !== version.data) {
  72380. _this.mustUpdateRessources = true;
  72381. updateInDBCallback();
  72382. }
  72383. else {
  72384. callback(version.data);
  72385. }
  72386. }
  72387. // version was not found in DB
  72388. else {
  72389. _this.mustUpdateRessources = true;
  72390. updateInDBCallback();
  72391. }
  72392. };
  72393. transaction.onabort = function (event) {
  72394. callback(-1);
  72395. };
  72396. var getRequest = transaction.objectStore("versions").get(url);
  72397. getRequest.onsuccess = function (event) {
  72398. version = (event.target).result;
  72399. };
  72400. getRequest.onerror = function (event) {
  72401. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72402. callback(-1);
  72403. };
  72404. }
  72405. catch (ex) {
  72406. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72407. callback(-1);
  72408. }
  72409. }
  72410. else {
  72411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72412. callback(-1);
  72413. }
  72414. };
  72415. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72416. var _this = this;
  72417. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72418. try {
  72419. // Open a transaction to the database
  72420. var transaction = this.db.transaction(["versions"], "readwrite");
  72421. // the transaction could abort because of a QuotaExceededError error
  72422. transaction.onabort = function (event) {
  72423. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72424. var error = event.srcElement['error'];
  72425. if (error && error.name === "QuotaExceededError") {
  72426. _this.hasReachedQuota = true;
  72427. }
  72428. }
  72429. catch (ex) { }
  72430. callback(-1);
  72431. };
  72432. transaction.oncomplete = function (event) {
  72433. callback(_this.manifestVersionFound);
  72434. };
  72435. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72436. // Put the scene into the database
  72437. var addRequest = transaction.objectStore("versions").put(newVersion);
  72438. addRequest.onsuccess = function (event) {
  72439. };
  72440. addRequest.onerror = function (event) {
  72441. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72442. };
  72443. }
  72444. catch (ex) {
  72445. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  72446. callback(-1);
  72447. }
  72448. }
  72449. else {
  72450. callback(-1);
  72451. }
  72452. };
  72453. /**
  72454. * Loads a file from database
  72455. * @param url defines the URL to load from
  72456. * @param sceneLoaded defines a callback to call on success
  72457. * @param progressCallBack defines a callback to call when progress changed
  72458. * @param errorCallback defines a callback to call on error
  72459. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  72460. */
  72461. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  72462. var _this = this;
  72463. var completeUrl = Database._ReturnFullUrlLocation(url);
  72464. var saveAndLoadFile = function () {
  72465. // the scene is not yet in the DB, let's try to save it
  72466. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72467. };
  72468. this._checkVersionFromDB(completeUrl, function (version) {
  72469. if (version !== -1) {
  72470. if (!_this.mustUpdateRessources) {
  72471. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  72472. }
  72473. else {
  72474. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72475. }
  72476. }
  72477. else {
  72478. if (errorCallback) {
  72479. errorCallback();
  72480. }
  72481. }
  72482. });
  72483. };
  72484. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  72485. if (this.isSupported && this.db) {
  72486. var targetStore;
  72487. if (url.indexOf(".babylon") !== -1) {
  72488. targetStore = "scenes";
  72489. }
  72490. else {
  72491. targetStore = "textures";
  72492. }
  72493. var file;
  72494. var transaction = this.db.transaction([targetStore]);
  72495. transaction.oncomplete = function (event) {
  72496. if (file) {
  72497. callback(file.data);
  72498. }
  72499. // file was not found in DB
  72500. else {
  72501. notInDBCallback();
  72502. }
  72503. };
  72504. transaction.onabort = function (event) {
  72505. notInDBCallback();
  72506. };
  72507. var getRequest = transaction.objectStore(targetStore).get(url);
  72508. getRequest.onsuccess = function (event) {
  72509. file = (event.target).result;
  72510. };
  72511. getRequest.onerror = function (event) {
  72512. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  72513. notInDBCallback();
  72514. };
  72515. }
  72516. else {
  72517. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72518. callback();
  72519. }
  72520. };
  72521. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  72522. var _this = this;
  72523. if (this.isSupported) {
  72524. var targetStore;
  72525. if (url.indexOf(".babylon") !== -1) {
  72526. targetStore = "scenes";
  72527. }
  72528. else {
  72529. targetStore = "textures";
  72530. }
  72531. // Create XHR
  72532. var xhr = new XMLHttpRequest();
  72533. var fileData;
  72534. xhr.open("GET", url + "?" + Date.now(), true);
  72535. if (useArrayBuffer) {
  72536. xhr.responseType = "arraybuffer";
  72537. }
  72538. if (progressCallback) {
  72539. xhr.onprogress = progressCallback;
  72540. }
  72541. xhr.addEventListener("load", function () {
  72542. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  72543. // Blob as response (XHR2)
  72544. //fileData = xhr.responseText;
  72545. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  72546. if (!_this.hasReachedQuota && _this.db) {
  72547. // Open a transaction to the database
  72548. var transaction = _this.db.transaction([targetStore], "readwrite");
  72549. // the transaction could abort because of a QuotaExceededError error
  72550. transaction.onabort = function (event) {
  72551. try {
  72552. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72553. var error = event.srcElement['error'];
  72554. if (error && error.name === "QuotaExceededError") {
  72555. _this.hasReachedQuota = true;
  72556. }
  72557. }
  72558. catch (ex) { }
  72559. callback(fileData);
  72560. };
  72561. transaction.oncomplete = function (event) {
  72562. callback(fileData);
  72563. };
  72564. var newFile;
  72565. if (targetStore === "scenes") {
  72566. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72567. }
  72568. else {
  72569. newFile = { textureUrl: url, data: fileData };
  72570. }
  72571. try {
  72572. // Put the scene into the database
  72573. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72574. addRequest.onsuccess = function (event) {
  72575. };
  72576. addRequest.onerror = function (event) {
  72577. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72578. };
  72579. }
  72580. catch (ex) {
  72581. callback(fileData);
  72582. }
  72583. }
  72584. else {
  72585. callback(fileData);
  72586. }
  72587. }
  72588. else {
  72589. if (xhr.status >= 400 && errorCallback) {
  72590. errorCallback(xhr);
  72591. }
  72592. else {
  72593. callback();
  72594. }
  72595. }
  72596. }, false);
  72597. xhr.addEventListener("error", function (event) {
  72598. BABYLON.Tools.Error("error on XHR request.");
  72599. callback();
  72600. }, false);
  72601. xhr.send();
  72602. }
  72603. else {
  72604. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72605. callback();
  72606. }
  72607. };
  72608. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72609. Database.IsUASupportingBlobStorage = true;
  72610. /** Gets a boolean indicating if Database storate is enabled */
  72611. Database.IDBStorageEnabled = true;
  72612. Database._ParseURL = function (url) {
  72613. var a = document.createElement('a');
  72614. a.href = url;
  72615. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72616. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72617. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72618. return absLocation;
  72619. };
  72620. Database._ReturnFullUrlLocation = function (url) {
  72621. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72622. return (Database._ParseURL(window.location.href) + url);
  72623. }
  72624. else {
  72625. return url;
  72626. }
  72627. };
  72628. return Database;
  72629. }());
  72630. BABYLON.Database = Database;
  72631. })(BABYLON || (BABYLON = {}));
  72632. //# sourceMappingURL=babylon.database.js.map
  72633. var BABYLON;
  72634. (function (BABYLON) {
  72635. var FresnelParameters = /** @class */ (function () {
  72636. function FresnelParameters() {
  72637. this._isEnabled = true;
  72638. this.leftColor = BABYLON.Color3.White();
  72639. this.rightColor = BABYLON.Color3.Black();
  72640. this.bias = 0;
  72641. this.power = 1;
  72642. }
  72643. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72644. get: function () {
  72645. return this._isEnabled;
  72646. },
  72647. set: function (value) {
  72648. if (this._isEnabled === value) {
  72649. return;
  72650. }
  72651. this._isEnabled = value;
  72652. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72653. },
  72654. enumerable: true,
  72655. configurable: true
  72656. });
  72657. FresnelParameters.prototype.clone = function () {
  72658. var newFresnelParameters = new FresnelParameters();
  72659. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72660. return newFresnelParameters;
  72661. };
  72662. FresnelParameters.prototype.serialize = function () {
  72663. var serializationObject = {};
  72664. serializationObject.isEnabled = this.isEnabled;
  72665. serializationObject.leftColor = this.leftColor.asArray();
  72666. serializationObject.rightColor = this.rightColor.asArray();
  72667. serializationObject.bias = this.bias;
  72668. serializationObject.power = this.power;
  72669. return serializationObject;
  72670. };
  72671. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72672. var fresnelParameters = new FresnelParameters();
  72673. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72674. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72675. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72676. fresnelParameters.bias = parsedFresnelParameters.bias;
  72677. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72678. return fresnelParameters;
  72679. };
  72680. return FresnelParameters;
  72681. }());
  72682. BABYLON.FresnelParameters = FresnelParameters;
  72683. })(BABYLON || (BABYLON = {}));
  72684. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72685. var BABYLON;
  72686. (function (BABYLON) {
  72687. var MultiMaterial = /** @class */ (function (_super) {
  72688. __extends(MultiMaterial, _super);
  72689. function MultiMaterial(name, scene) {
  72690. var _this = _super.call(this, name, scene, true) || this;
  72691. scene.multiMaterials.push(_this);
  72692. _this.subMaterials = new Array();
  72693. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72694. return _this;
  72695. }
  72696. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72697. get: function () {
  72698. return this._subMaterials;
  72699. },
  72700. set: function (value) {
  72701. this._subMaterials = value;
  72702. this._hookArray(value);
  72703. },
  72704. enumerable: true,
  72705. configurable: true
  72706. });
  72707. MultiMaterial.prototype._hookArray = function (array) {
  72708. var _this = this;
  72709. var oldPush = array.push;
  72710. array.push = function () {
  72711. var items = [];
  72712. for (var _i = 0; _i < arguments.length; _i++) {
  72713. items[_i] = arguments[_i];
  72714. }
  72715. var result = oldPush.apply(array, items);
  72716. _this._markAllSubMeshesAsTexturesDirty();
  72717. return result;
  72718. };
  72719. var oldSplice = array.splice;
  72720. array.splice = function (index, deleteCount) {
  72721. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72722. _this._markAllSubMeshesAsTexturesDirty();
  72723. return deleted;
  72724. };
  72725. };
  72726. // Properties
  72727. MultiMaterial.prototype.getSubMaterial = function (index) {
  72728. if (index < 0 || index >= this.subMaterials.length) {
  72729. return this.getScene().defaultMaterial;
  72730. }
  72731. return this.subMaterials[index];
  72732. };
  72733. MultiMaterial.prototype.getActiveTextures = function () {
  72734. var _a;
  72735. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72736. if (subMaterial) {
  72737. return subMaterial.getActiveTextures();
  72738. }
  72739. else {
  72740. return [];
  72741. }
  72742. }));
  72743. };
  72744. // Methods
  72745. MultiMaterial.prototype.getClassName = function () {
  72746. return "MultiMaterial";
  72747. };
  72748. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72749. for (var index = 0; index < this.subMaterials.length; index++) {
  72750. var subMaterial = this.subMaterials[index];
  72751. if (subMaterial) {
  72752. if (subMaterial.storeEffectOnSubMeshes) {
  72753. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72754. return false;
  72755. }
  72756. continue;
  72757. }
  72758. if (!subMaterial.isReady(mesh)) {
  72759. return false;
  72760. }
  72761. }
  72762. }
  72763. return true;
  72764. };
  72765. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72766. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72767. for (var index = 0; index < this.subMaterials.length; index++) {
  72768. var subMaterial = null;
  72769. var current = this.subMaterials[index];
  72770. if (cloneChildren && current) {
  72771. subMaterial = current.clone(name + "-" + current.name);
  72772. }
  72773. else {
  72774. subMaterial = this.subMaterials[index];
  72775. }
  72776. newMultiMaterial.subMaterials.push(subMaterial);
  72777. }
  72778. return newMultiMaterial;
  72779. };
  72780. MultiMaterial.prototype.serialize = function () {
  72781. var serializationObject = {};
  72782. serializationObject.name = this.name;
  72783. serializationObject.id = this.id;
  72784. if (BABYLON.Tags) {
  72785. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72786. }
  72787. serializationObject.materials = [];
  72788. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72789. var subMat = this.subMaterials[matIndex];
  72790. if (subMat) {
  72791. serializationObject.materials.push(subMat.id);
  72792. }
  72793. else {
  72794. serializationObject.materials.push(null);
  72795. }
  72796. }
  72797. return serializationObject;
  72798. };
  72799. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72800. var scene = this.getScene();
  72801. if (!scene) {
  72802. return;
  72803. }
  72804. var index = scene.multiMaterials.indexOf(this);
  72805. if (index >= 0) {
  72806. scene.multiMaterials.splice(index, 1);
  72807. }
  72808. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72809. };
  72810. return MultiMaterial;
  72811. }(BABYLON.Material));
  72812. BABYLON.MultiMaterial = MultiMaterial;
  72813. })(BABYLON || (BABYLON = {}));
  72814. //# sourceMappingURL=babylon.multiMaterial.js.map
  72815. var BABYLON;
  72816. (function (BABYLON) {
  72817. var FreeCameraTouchInput = /** @class */ (function () {
  72818. function FreeCameraTouchInput() {
  72819. this._offsetX = null;
  72820. this._offsetY = null;
  72821. this._pointerPressed = new Array();
  72822. this.touchAngularSensibility = 200000.0;
  72823. this.touchMoveSensibility = 250.0;
  72824. }
  72825. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72826. var _this = this;
  72827. var previousPosition = null;
  72828. if (this._pointerInput === undefined) {
  72829. this._onLostFocus = function (evt) {
  72830. _this._offsetX = null;
  72831. _this._offsetY = null;
  72832. };
  72833. this._pointerInput = function (p, s) {
  72834. var evt = p.event;
  72835. if (evt.pointerType === "mouse") {
  72836. return;
  72837. }
  72838. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72839. if (!noPreventDefault) {
  72840. evt.preventDefault();
  72841. }
  72842. _this._pointerPressed.push(evt.pointerId);
  72843. if (_this._pointerPressed.length !== 1) {
  72844. return;
  72845. }
  72846. previousPosition = {
  72847. x: evt.clientX,
  72848. y: evt.clientY
  72849. };
  72850. }
  72851. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  72852. if (!noPreventDefault) {
  72853. evt.preventDefault();
  72854. }
  72855. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72856. if (index === -1) {
  72857. return;
  72858. }
  72859. _this._pointerPressed.splice(index, 1);
  72860. if (index != 0) {
  72861. return;
  72862. }
  72863. previousPosition = null;
  72864. _this._offsetX = null;
  72865. _this._offsetY = null;
  72866. }
  72867. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  72868. if (!noPreventDefault) {
  72869. evt.preventDefault();
  72870. }
  72871. if (!previousPosition) {
  72872. return;
  72873. }
  72874. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72875. if (index != 0) {
  72876. return;
  72877. }
  72878. _this._offsetX = evt.clientX - previousPosition.x;
  72879. _this._offsetY = -(evt.clientY - previousPosition.y);
  72880. }
  72881. };
  72882. }
  72883. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  72884. if (this._onLostFocus) {
  72885. element.addEventListener("blur", this._onLostFocus);
  72886. }
  72887. };
  72888. FreeCameraTouchInput.prototype.detachControl = function (element) {
  72889. if (this._pointerInput && element) {
  72890. if (this._observer) {
  72891. this.camera.getScene().onPointerObservable.remove(this._observer);
  72892. this._observer = null;
  72893. }
  72894. if (this._onLostFocus) {
  72895. element.removeEventListener("blur", this._onLostFocus);
  72896. this._onLostFocus = null;
  72897. }
  72898. this._pointerPressed = [];
  72899. this._offsetX = null;
  72900. this._offsetY = null;
  72901. }
  72902. };
  72903. FreeCameraTouchInput.prototype.checkInputs = function () {
  72904. if (this._offsetX && this._offsetY) {
  72905. var camera = this.camera;
  72906. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  72907. if (this._pointerPressed.length > 1) {
  72908. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  72909. }
  72910. else {
  72911. var speed = camera._computeLocalCameraSpeed();
  72912. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  72913. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  72914. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  72915. }
  72916. }
  72917. };
  72918. FreeCameraTouchInput.prototype.getClassName = function () {
  72919. return "FreeCameraTouchInput";
  72920. };
  72921. FreeCameraTouchInput.prototype.getSimpleName = function () {
  72922. return "touch";
  72923. };
  72924. __decorate([
  72925. BABYLON.serialize()
  72926. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  72927. __decorate([
  72928. BABYLON.serialize()
  72929. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  72930. return FreeCameraTouchInput;
  72931. }());
  72932. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  72933. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72934. })(BABYLON || (BABYLON = {}));
  72935. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72936. var BABYLON;
  72937. (function (BABYLON) {
  72938. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72939. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72940. });
  72941. // We're mainly based on the logic defined into the FreeCamera code
  72942. var TouchCamera = /** @class */ (function (_super) {
  72943. __extends(TouchCamera, _super);
  72944. //-- end properties for backward compatibility for inputs
  72945. function TouchCamera(name, position, scene) {
  72946. var _this = _super.call(this, name, position, scene) || this;
  72947. _this.inputs.addTouch();
  72948. _this._setupInputs();
  72949. return _this;
  72950. }
  72951. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72952. //-- Begin properties for backward compatibility for inputs
  72953. get: function () {
  72954. var touch = this.inputs.attached["touch"];
  72955. if (touch)
  72956. return touch.touchAngularSensibility;
  72957. return 0;
  72958. },
  72959. set: function (value) {
  72960. var touch = this.inputs.attached["touch"];
  72961. if (touch)
  72962. touch.touchAngularSensibility = value;
  72963. },
  72964. enumerable: true,
  72965. configurable: true
  72966. });
  72967. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72968. get: function () {
  72969. var touch = this.inputs.attached["touch"];
  72970. if (touch)
  72971. return touch.touchMoveSensibility;
  72972. return 0;
  72973. },
  72974. set: function (value) {
  72975. var touch = this.inputs.attached["touch"];
  72976. if (touch)
  72977. touch.touchMoveSensibility = value;
  72978. },
  72979. enumerable: true,
  72980. configurable: true
  72981. });
  72982. TouchCamera.prototype.getClassName = function () {
  72983. return "TouchCamera";
  72984. };
  72985. /** @hidden */
  72986. TouchCamera.prototype._setupInputs = function () {
  72987. var mouse = this.inputs.attached["mouse"];
  72988. if (mouse) {
  72989. mouse.touchEnabled = false;
  72990. }
  72991. };
  72992. return TouchCamera;
  72993. }(BABYLON.FreeCamera));
  72994. BABYLON.TouchCamera = TouchCamera;
  72995. })(BABYLON || (BABYLON = {}));
  72996. //# sourceMappingURL=babylon.touchCamera.js.map
  72997. var BABYLON;
  72998. (function (BABYLON) {
  72999. var ProceduralTexture = /** @class */ (function (_super) {
  73000. __extends(ProceduralTexture, _super);
  73001. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  73002. if (fallbackTexture === void 0) { fallbackTexture = null; }
  73003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73004. if (isCube === void 0) { isCube = false; }
  73005. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73006. _this.isCube = isCube;
  73007. _this.isEnabled = true;
  73008. _this._currentRefreshId = -1;
  73009. _this._refreshRate = 1;
  73010. _this._vertexBuffers = {};
  73011. _this._uniforms = new Array();
  73012. _this._samplers = new Array();
  73013. /** @hidden */
  73014. _this._textures = {};
  73015. _this._floats = {};
  73016. _this._ints = {};
  73017. _this._floatsArrays = {};
  73018. _this._colors3 = {};
  73019. _this._colors4 = {};
  73020. _this._vectors2 = {};
  73021. _this._vectors3 = {};
  73022. _this._matrices = {};
  73023. _this._fallbackTextureUsed = false;
  73024. scene = _this.getScene();
  73025. scene.proceduralTextures.push(_this);
  73026. _this._engine = scene.getEngine();
  73027. _this.name = name;
  73028. _this.isRenderTarget = true;
  73029. _this._size = size;
  73030. _this._generateMipMaps = generateMipMaps;
  73031. _this.setFragment(fragment);
  73032. _this._fallbackTexture = fallbackTexture;
  73033. if (isCube) {
  73034. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  73035. _this.setFloat("face", 0);
  73036. }
  73037. else {
  73038. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  73039. }
  73040. // VBO
  73041. var vertices = [];
  73042. vertices.push(1, 1);
  73043. vertices.push(-1, 1);
  73044. vertices.push(-1, -1);
  73045. vertices.push(1, -1);
  73046. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73047. _this._createIndexBuffer();
  73048. return _this;
  73049. }
  73050. ProceduralTexture.prototype._createIndexBuffer = function () {
  73051. var engine = this._engine;
  73052. // Indices
  73053. var indices = [];
  73054. indices.push(0);
  73055. indices.push(1);
  73056. indices.push(2);
  73057. indices.push(0);
  73058. indices.push(2);
  73059. indices.push(3);
  73060. this._indexBuffer = engine.createIndexBuffer(indices);
  73061. };
  73062. /** @hidden */
  73063. ProceduralTexture.prototype._rebuild = function () {
  73064. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73065. if (vb) {
  73066. vb._rebuild();
  73067. }
  73068. this._createIndexBuffer();
  73069. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73070. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73071. }
  73072. };
  73073. ProceduralTexture.prototype.reset = function () {
  73074. if (this._effect === undefined) {
  73075. return;
  73076. }
  73077. var engine = this._engine;
  73078. engine._releaseEffect(this._effect);
  73079. };
  73080. ProceduralTexture.prototype.isReady = function () {
  73081. var _this = this;
  73082. var engine = this._engine;
  73083. var shaders;
  73084. if (!this._fragment) {
  73085. return false;
  73086. }
  73087. if (this._fallbackTextureUsed) {
  73088. return true;
  73089. }
  73090. if (this._fragment.fragmentElement !== undefined) {
  73091. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  73092. }
  73093. else {
  73094. shaders = { vertex: "procedural", fragment: this._fragment };
  73095. }
  73096. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  73097. _this.releaseInternalTexture();
  73098. if (_this._fallbackTexture) {
  73099. _this._texture = _this._fallbackTexture._texture;
  73100. if (_this._texture) {
  73101. _this._texture.incrementReferences();
  73102. }
  73103. }
  73104. _this._fallbackTextureUsed = true;
  73105. });
  73106. return this._effect.isReady();
  73107. };
  73108. ProceduralTexture.prototype.resetRefreshCounter = function () {
  73109. this._currentRefreshId = -1;
  73110. };
  73111. ProceduralTexture.prototype.setFragment = function (fragment) {
  73112. this._fragment = fragment;
  73113. };
  73114. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  73115. get: function () {
  73116. return this._refreshRate;
  73117. },
  73118. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73119. set: function (value) {
  73120. this._refreshRate = value;
  73121. this.resetRefreshCounter();
  73122. },
  73123. enumerable: true,
  73124. configurable: true
  73125. });
  73126. /** @hidden */
  73127. ProceduralTexture.prototype._shouldRender = function () {
  73128. if (!this.isEnabled || !this.isReady() || !this._texture) {
  73129. return false;
  73130. }
  73131. if (this._fallbackTextureUsed) {
  73132. return false;
  73133. }
  73134. if (this._currentRefreshId === -1) { // At least render once
  73135. this._currentRefreshId = 1;
  73136. return true;
  73137. }
  73138. if (this.refreshRate === this._currentRefreshId) {
  73139. this._currentRefreshId = 1;
  73140. return true;
  73141. }
  73142. this._currentRefreshId++;
  73143. return false;
  73144. };
  73145. ProceduralTexture.prototype.getRenderSize = function () {
  73146. return this._size;
  73147. };
  73148. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  73149. if (this._fallbackTextureUsed) {
  73150. return;
  73151. }
  73152. this.releaseInternalTexture();
  73153. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  73154. // Update properties
  73155. this._size = size;
  73156. this._generateMipMaps = generateMipMaps;
  73157. };
  73158. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  73159. if (this._uniforms.indexOf(uniformName) === -1) {
  73160. this._uniforms.push(uniformName);
  73161. }
  73162. };
  73163. ProceduralTexture.prototype.setTexture = function (name, texture) {
  73164. if (this._samplers.indexOf(name) === -1) {
  73165. this._samplers.push(name);
  73166. }
  73167. this._textures[name] = texture;
  73168. return this;
  73169. };
  73170. ProceduralTexture.prototype.setFloat = function (name, value) {
  73171. this._checkUniform(name);
  73172. this._floats[name] = value;
  73173. return this;
  73174. };
  73175. /**
  73176. * Set the value of an uniform to an integer value
  73177. * @param name defines the name of the uniform
  73178. * @param value defines the value to set
  73179. * @returns the current procedural texture
  73180. */
  73181. ProceduralTexture.prototype.setInt = function (name, value) {
  73182. this._checkUniform(name);
  73183. this._ints[name] = value;
  73184. return this;
  73185. };
  73186. ProceduralTexture.prototype.setFloats = function (name, value) {
  73187. this._checkUniform(name);
  73188. this._floatsArrays[name] = value;
  73189. return this;
  73190. };
  73191. ProceduralTexture.prototype.setColor3 = function (name, value) {
  73192. this._checkUniform(name);
  73193. this._colors3[name] = value;
  73194. return this;
  73195. };
  73196. ProceduralTexture.prototype.setColor4 = function (name, value) {
  73197. this._checkUniform(name);
  73198. this._colors4[name] = value;
  73199. return this;
  73200. };
  73201. ProceduralTexture.prototype.setVector2 = function (name, value) {
  73202. this._checkUniform(name);
  73203. this._vectors2[name] = value;
  73204. return this;
  73205. };
  73206. ProceduralTexture.prototype.setVector3 = function (name, value) {
  73207. this._checkUniform(name);
  73208. this._vectors3[name] = value;
  73209. return this;
  73210. };
  73211. ProceduralTexture.prototype.setMatrix = function (name, value) {
  73212. this._checkUniform(name);
  73213. this._matrices[name] = value;
  73214. return this;
  73215. };
  73216. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73217. var scene = this.getScene();
  73218. if (!scene) {
  73219. return;
  73220. }
  73221. var engine = this._engine;
  73222. // Render
  73223. engine.enableEffect(this._effect);
  73224. engine.setState(false);
  73225. // Texture
  73226. for (var name in this._textures) {
  73227. this._effect.setTexture(name, this._textures[name]);
  73228. }
  73229. // Float
  73230. for (name in this._ints) {
  73231. this._effect.setInt(name, this._ints[name]);
  73232. }
  73233. // Float
  73234. for (name in this._floats) {
  73235. this._effect.setFloat(name, this._floats[name]);
  73236. }
  73237. // Floats
  73238. for (name in this._floatsArrays) {
  73239. this._effect.setArray(name, this._floatsArrays[name]);
  73240. }
  73241. // Color3
  73242. for (name in this._colors3) {
  73243. this._effect.setColor3(name, this._colors3[name]);
  73244. }
  73245. // Color4
  73246. for (name in this._colors4) {
  73247. var color = this._colors4[name];
  73248. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73249. }
  73250. // Vector2
  73251. for (name in this._vectors2) {
  73252. this._effect.setVector2(name, this._vectors2[name]);
  73253. }
  73254. // Vector3
  73255. for (name in this._vectors3) {
  73256. this._effect.setVector3(name, this._vectors3[name]);
  73257. }
  73258. // Matrix
  73259. for (name in this._matrices) {
  73260. this._effect.setMatrix(name, this._matrices[name]);
  73261. }
  73262. if (!this._texture) {
  73263. return;
  73264. }
  73265. if (this.isCube) {
  73266. for (var face = 0; face < 6; face++) {
  73267. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73268. // VBOs
  73269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73270. this._effect.setFloat("face", face);
  73271. // Clear
  73272. engine.clear(scene.clearColor, true, true, true);
  73273. // Draw order
  73274. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73275. // Mipmaps
  73276. if (face === 5) {
  73277. engine.generateMipMapsForCubemap(this._texture);
  73278. }
  73279. }
  73280. }
  73281. else {
  73282. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73283. // VBOs
  73284. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73285. // Clear
  73286. engine.clear(scene.clearColor, true, true, true);
  73287. // Draw order
  73288. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73289. }
  73290. // Unbind
  73291. engine.unBindFramebuffer(this._texture, this.isCube);
  73292. if (this.onGenerated) {
  73293. this.onGenerated();
  73294. }
  73295. };
  73296. ProceduralTexture.prototype.clone = function () {
  73297. var textureSize = this.getSize();
  73298. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73299. // Base texture
  73300. newTexture.hasAlpha = this.hasAlpha;
  73301. newTexture.level = this.level;
  73302. // RenderTarget Texture
  73303. newTexture.coordinatesMode = this.coordinatesMode;
  73304. return newTexture;
  73305. };
  73306. ProceduralTexture.prototype.dispose = function () {
  73307. var scene = this.getScene();
  73308. if (!scene) {
  73309. return;
  73310. }
  73311. var index = scene.proceduralTextures.indexOf(this);
  73312. if (index >= 0) {
  73313. scene.proceduralTextures.splice(index, 1);
  73314. }
  73315. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73316. if (vertexBuffer) {
  73317. vertexBuffer.dispose();
  73318. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73319. }
  73320. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73321. this._indexBuffer = null;
  73322. }
  73323. _super.prototype.dispose.call(this);
  73324. };
  73325. __decorate([
  73326. BABYLON.serialize()
  73327. ], ProceduralTexture.prototype, "_size", void 0);
  73328. __decorate([
  73329. BABYLON.serialize()
  73330. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73331. __decorate([
  73332. BABYLON.serialize()
  73333. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73334. __decorate([
  73335. BABYLON.serialize()
  73336. ], ProceduralTexture.prototype, "refreshRate", null);
  73337. return ProceduralTexture;
  73338. }(BABYLON.Texture));
  73339. BABYLON.ProceduralTexture = ProceduralTexture;
  73340. })(BABYLON || (BABYLON = {}));
  73341. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73342. var BABYLON;
  73343. (function (BABYLON) {
  73344. var CustomProceduralTexture = /** @class */ (function (_super) {
  73345. __extends(CustomProceduralTexture, _super);
  73346. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73347. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73348. _this._animate = true;
  73349. _this._time = 0;
  73350. _this._texturePath = texturePath;
  73351. //Try to load json
  73352. _this.loadJson(texturePath);
  73353. _this.refreshRate = 1;
  73354. return _this;
  73355. }
  73356. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73357. var _this = this;
  73358. var noConfigFile = function () {
  73359. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73360. try {
  73361. _this.setFragment(_this._texturePath);
  73362. }
  73363. catch (ex) {
  73364. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73365. }
  73366. };
  73367. var configFileUrl = jsonUrl + "/config.json";
  73368. var xhr = new XMLHttpRequest();
  73369. xhr.open("GET", configFileUrl, true);
  73370. xhr.addEventListener("load", function () {
  73371. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73372. try {
  73373. _this._config = JSON.parse(xhr.response);
  73374. _this.updateShaderUniforms();
  73375. _this.updateTextures();
  73376. _this.setFragment(_this._texturePath + "/custom");
  73377. _this._animate = _this._config.animate;
  73378. _this.refreshRate = _this._config.refreshrate;
  73379. }
  73380. catch (ex) {
  73381. noConfigFile();
  73382. }
  73383. }
  73384. else {
  73385. noConfigFile();
  73386. }
  73387. }, false);
  73388. xhr.addEventListener("error", function () {
  73389. noConfigFile();
  73390. }, false);
  73391. try {
  73392. xhr.send();
  73393. }
  73394. catch (ex) {
  73395. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  73396. }
  73397. };
  73398. CustomProceduralTexture.prototype.isReady = function () {
  73399. if (!_super.prototype.isReady.call(this)) {
  73400. return false;
  73401. }
  73402. for (var name in this._textures) {
  73403. var texture = this._textures[name];
  73404. if (!texture.isReady()) {
  73405. return false;
  73406. }
  73407. }
  73408. return true;
  73409. };
  73410. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73411. var scene = this.getScene();
  73412. if (this._animate && scene) {
  73413. this._time += scene.getAnimationRatio() * 0.03;
  73414. this.updateShaderUniforms();
  73415. }
  73416. _super.prototype.render.call(this, useCameraPostProcess);
  73417. };
  73418. CustomProceduralTexture.prototype.updateTextures = function () {
  73419. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  73420. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  73421. }
  73422. };
  73423. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  73424. if (this._config) {
  73425. for (var j = 0; j < this._config.uniforms.length; j++) {
  73426. var uniform = this._config.uniforms[j];
  73427. switch (uniform.type) {
  73428. case "float":
  73429. this.setFloat(uniform.name, uniform.value);
  73430. break;
  73431. case "color3":
  73432. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  73433. break;
  73434. case "color4":
  73435. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  73436. break;
  73437. case "vector2":
  73438. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  73439. break;
  73440. case "vector3":
  73441. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  73442. break;
  73443. }
  73444. }
  73445. }
  73446. this.setFloat("time", this._time);
  73447. };
  73448. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  73449. get: function () {
  73450. return this._animate;
  73451. },
  73452. set: function (value) {
  73453. this._animate = value;
  73454. },
  73455. enumerable: true,
  73456. configurable: true
  73457. });
  73458. return CustomProceduralTexture;
  73459. }(BABYLON.ProceduralTexture));
  73460. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  73461. })(BABYLON || (BABYLON = {}));
  73462. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  73463. var BABYLON;
  73464. (function (BABYLON) {
  73465. var FreeCameraGamepadInput = /** @class */ (function () {
  73466. function FreeCameraGamepadInput() {
  73467. this.gamepadAngularSensibility = 200;
  73468. this.gamepadMoveSensibility = 40;
  73469. // private members
  73470. this._cameraTransform = BABYLON.Matrix.Identity();
  73471. this._deltaTransform = BABYLON.Vector3.Zero();
  73472. this._vector3 = BABYLON.Vector3.Zero();
  73473. this._vector2 = BABYLON.Vector2.Zero();
  73474. }
  73475. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73476. var _this = this;
  73477. var manager = this.camera.getScene().gamepadManager;
  73478. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73479. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73480. // prioritize XBOX gamepads.
  73481. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73482. _this.gamepad = gamepad;
  73483. }
  73484. }
  73485. });
  73486. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73487. if (_this.gamepad === gamepad) {
  73488. _this.gamepad = null;
  73489. }
  73490. });
  73491. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73492. };
  73493. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  73494. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73495. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73496. this.gamepad = null;
  73497. };
  73498. FreeCameraGamepadInput.prototype.checkInputs = function () {
  73499. if (this.gamepad && this.gamepad.leftStick) {
  73500. var camera = this.camera;
  73501. var LSValues = this.gamepad.leftStick;
  73502. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  73503. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73504. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  73505. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  73506. var RSValues = this.gamepad.rightStick;
  73507. if (RSValues) {
  73508. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  73509. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  73510. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  73511. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  73512. }
  73513. else {
  73514. RSValues = { x: 0, y: 0 };
  73515. }
  73516. if (!camera.rotationQuaternion) {
  73517. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  73518. }
  73519. else {
  73520. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  73521. }
  73522. var speed = camera._computeLocalCameraSpeed() * 50.0;
  73523. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  73524. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  73525. camera.cameraDirection.addInPlace(this._deltaTransform);
  73526. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  73527. camera.cameraRotation.addInPlace(this._vector2);
  73528. }
  73529. };
  73530. FreeCameraGamepadInput.prototype.getClassName = function () {
  73531. return "FreeCameraGamepadInput";
  73532. };
  73533. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  73534. return "gamepad";
  73535. };
  73536. __decorate([
  73537. BABYLON.serialize()
  73538. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  73539. __decorate([
  73540. BABYLON.serialize()
  73541. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73542. return FreeCameraGamepadInput;
  73543. }());
  73544. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  73545. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  73546. })(BABYLON || (BABYLON = {}));
  73547. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  73548. var BABYLON;
  73549. (function (BABYLON) {
  73550. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  73551. function ArcRotateCameraGamepadInput() {
  73552. this.gamepadRotationSensibility = 80;
  73553. this.gamepadMoveSensibility = 40;
  73554. }
  73555. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73556. var _this = this;
  73557. var manager = this.camera.getScene().gamepadManager;
  73558. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73559. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73560. // prioritize XBOX gamepads.
  73561. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73562. _this.gamepad = gamepad;
  73563. }
  73564. }
  73565. });
  73566. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73567. if (_this.gamepad === gamepad) {
  73568. _this.gamepad = null;
  73569. }
  73570. });
  73571. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73572. };
  73573. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73574. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73575. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73576. this.gamepad = null;
  73577. };
  73578. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73579. if (this.gamepad) {
  73580. var camera = this.camera;
  73581. var RSValues = this.gamepad.rightStick;
  73582. if (RSValues) {
  73583. if (RSValues.x != 0) {
  73584. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73585. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73586. camera.inertialAlphaOffset += normalizedRX;
  73587. }
  73588. }
  73589. if (RSValues.y != 0) {
  73590. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73591. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73592. camera.inertialBetaOffset += normalizedRY;
  73593. }
  73594. }
  73595. }
  73596. var LSValues = this.gamepad.leftStick;
  73597. if (LSValues && LSValues.y != 0) {
  73598. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73599. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73600. this.camera.inertialRadiusOffset -= normalizedLY;
  73601. }
  73602. }
  73603. }
  73604. };
  73605. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73606. return "ArcRotateCameraGamepadInput";
  73607. };
  73608. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73609. return "gamepad";
  73610. };
  73611. __decorate([
  73612. BABYLON.serialize()
  73613. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73614. __decorate([
  73615. BABYLON.serialize()
  73616. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73617. return ArcRotateCameraGamepadInput;
  73618. }());
  73619. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73620. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73621. })(BABYLON || (BABYLON = {}));
  73622. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73623. var BABYLON;
  73624. (function (BABYLON) {
  73625. var GamepadManager = /** @class */ (function () {
  73626. function GamepadManager(_scene) {
  73627. var _this = this;
  73628. this._scene = _scene;
  73629. this._babylonGamepads = [];
  73630. this._oneGamepadConnected = false;
  73631. /** @hidden */
  73632. this._isMonitoring = false;
  73633. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73634. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73635. this._gamepadEventSupported = false;
  73636. }
  73637. else {
  73638. this._gamepadEventSupported = 'GamepadEvent' in window;
  73639. this._gamepadSupport = (navigator.getGamepads ||
  73640. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73641. }
  73642. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73643. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73644. for (var i in _this._babylonGamepads) {
  73645. var gamepad = _this._babylonGamepads[i];
  73646. if (gamepad && gamepad._isConnected) {
  73647. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73648. }
  73649. }
  73650. });
  73651. this._onGamepadConnectedEvent = function (evt) {
  73652. var gamepad = evt.gamepad;
  73653. if (gamepad.index in _this._babylonGamepads) {
  73654. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73655. return;
  73656. }
  73657. }
  73658. var newGamepad;
  73659. if (_this._babylonGamepads[gamepad.index]) {
  73660. newGamepad = _this._babylonGamepads[gamepad.index];
  73661. newGamepad.browserGamepad = gamepad;
  73662. newGamepad._isConnected = true;
  73663. }
  73664. else {
  73665. newGamepad = _this._addNewGamepad(gamepad);
  73666. }
  73667. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73668. _this._startMonitoringGamepads();
  73669. };
  73670. this._onGamepadDisconnectedEvent = function (evt) {
  73671. var gamepad = evt.gamepad;
  73672. // Remove the gamepad from the list of gamepads to monitor.
  73673. for (var i in _this._babylonGamepads) {
  73674. if (_this._babylonGamepads[i].index === gamepad.index) {
  73675. var disconnectedGamepad = _this._babylonGamepads[i];
  73676. disconnectedGamepad._isConnected = false;
  73677. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73678. break;
  73679. }
  73680. }
  73681. };
  73682. if (this._gamepadSupport) {
  73683. //first add already-connected gamepads
  73684. this._updateGamepadObjects();
  73685. if (this._babylonGamepads.length) {
  73686. this._startMonitoringGamepads();
  73687. }
  73688. // Checking if the gamepad connected event is supported (like in Firefox)
  73689. if (this._gamepadEventSupported) {
  73690. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73691. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73692. }
  73693. else {
  73694. this._startMonitoringGamepads();
  73695. }
  73696. }
  73697. }
  73698. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73699. get: function () {
  73700. return this._babylonGamepads;
  73701. },
  73702. enumerable: true,
  73703. configurable: true
  73704. });
  73705. GamepadManager.prototype.getGamepadByType = function (type) {
  73706. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73707. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73708. var gamepad = _a[_i];
  73709. if (gamepad && gamepad.type === type) {
  73710. return gamepad;
  73711. }
  73712. }
  73713. return null;
  73714. };
  73715. GamepadManager.prototype.dispose = function () {
  73716. if (this._gamepadEventSupported) {
  73717. if (this._onGamepadConnectedEvent) {
  73718. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73719. }
  73720. if (this._onGamepadDisconnectedEvent) {
  73721. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73722. }
  73723. this._onGamepadConnectedEvent = null;
  73724. this._onGamepadDisconnectedEvent = null;
  73725. }
  73726. this._babylonGamepads.forEach(function (gamepad) {
  73727. gamepad.dispose();
  73728. });
  73729. this.onGamepadConnectedObservable.clear();
  73730. this.onGamepadDisconnectedObservable.clear();
  73731. this._oneGamepadConnected = false;
  73732. this._stopMonitoringGamepads();
  73733. this._babylonGamepads = [];
  73734. };
  73735. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73736. if (!this._oneGamepadConnected) {
  73737. this._oneGamepadConnected = true;
  73738. }
  73739. var newGamepad;
  73740. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73741. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73742. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73743. }
  73744. // if pose is supported, use the (WebVR) pose enabled controller
  73745. else if (gamepad.pose) {
  73746. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73747. }
  73748. else {
  73749. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73750. }
  73751. this._babylonGamepads[newGamepad.index] = newGamepad;
  73752. return newGamepad;
  73753. };
  73754. GamepadManager.prototype._startMonitoringGamepads = function () {
  73755. if (!this._isMonitoring) {
  73756. this._isMonitoring = true;
  73757. //back-comp
  73758. if (!this._scene) {
  73759. this._checkGamepadsStatus();
  73760. }
  73761. }
  73762. };
  73763. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73764. this._isMonitoring = false;
  73765. };
  73766. /** @hidden */
  73767. GamepadManager.prototype._checkGamepadsStatus = function () {
  73768. var _this = this;
  73769. // Hack to be compatible Chrome
  73770. this._updateGamepadObjects();
  73771. for (var i in this._babylonGamepads) {
  73772. var gamepad = this._babylonGamepads[i];
  73773. if (!gamepad || !gamepad.isConnected) {
  73774. continue;
  73775. }
  73776. gamepad.update();
  73777. }
  73778. if (this._isMonitoring && !this._scene) {
  73779. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73780. }
  73781. };
  73782. // This function is called only on Chrome, which does not properly support
  73783. // connection/disconnection events and forces you to recopy again the gamepad object
  73784. GamepadManager.prototype._updateGamepadObjects = function () {
  73785. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73786. for (var i = 0; i < gamepads.length; i++) {
  73787. var gamepad = gamepads[i];
  73788. if (gamepad) {
  73789. if (!this._babylonGamepads[gamepad.index]) {
  73790. var newGamepad = this._addNewGamepad(gamepad);
  73791. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73792. }
  73793. else {
  73794. // Forced to copy again this object for Chrome for unknown reason
  73795. this._babylonGamepads[i].browserGamepad = gamepad;
  73796. if (!this._babylonGamepads[i].isConnected) {
  73797. this._babylonGamepads[i]._isConnected = true;
  73798. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73799. }
  73800. }
  73801. }
  73802. }
  73803. };
  73804. return GamepadManager;
  73805. }());
  73806. BABYLON.GamepadManager = GamepadManager;
  73807. })(BABYLON || (BABYLON = {}));
  73808. //# sourceMappingURL=babylon.gamepadManager.js.map
  73809. var BABYLON;
  73810. (function (BABYLON) {
  73811. var StickValues = /** @class */ (function () {
  73812. function StickValues(x, y) {
  73813. this.x = x;
  73814. this.y = y;
  73815. }
  73816. return StickValues;
  73817. }());
  73818. BABYLON.StickValues = StickValues;
  73819. var Gamepad = /** @class */ (function () {
  73820. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73821. if (leftStickX === void 0) { leftStickX = 0; }
  73822. if (leftStickY === void 0) { leftStickY = 1; }
  73823. if (rightStickX === void 0) { rightStickX = 2; }
  73824. if (rightStickY === void 0) { rightStickY = 3; }
  73825. this.id = id;
  73826. this.index = index;
  73827. this.browserGamepad = browserGamepad;
  73828. this._leftStick = { x: 0, y: 0 };
  73829. this._rightStick = { x: 0, y: 0 };
  73830. /** @hidden */
  73831. this._isConnected = true;
  73832. this._invertLeftStickY = false;
  73833. this.type = Gamepad.GAMEPAD;
  73834. this._leftStickAxisX = leftStickX;
  73835. this._leftStickAxisY = leftStickY;
  73836. this._rightStickAxisX = rightStickX;
  73837. this._rightStickAxisY = rightStickY;
  73838. if (this.browserGamepad.axes.length >= 2) {
  73839. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73840. }
  73841. if (this.browserGamepad.axes.length >= 4) {
  73842. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73843. }
  73844. }
  73845. Object.defineProperty(Gamepad.prototype, "isConnected", {
  73846. get: function () {
  73847. return this._isConnected;
  73848. },
  73849. enumerable: true,
  73850. configurable: true
  73851. });
  73852. Gamepad.prototype.onleftstickchanged = function (callback) {
  73853. this._onleftstickchanged = callback;
  73854. };
  73855. Gamepad.prototype.onrightstickchanged = function (callback) {
  73856. this._onrightstickchanged = callback;
  73857. };
  73858. Object.defineProperty(Gamepad.prototype, "leftStick", {
  73859. get: function () {
  73860. return this._leftStick;
  73861. },
  73862. set: function (newValues) {
  73863. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  73864. this._onleftstickchanged(newValues);
  73865. }
  73866. this._leftStick = newValues;
  73867. },
  73868. enumerable: true,
  73869. configurable: true
  73870. });
  73871. Object.defineProperty(Gamepad.prototype, "rightStick", {
  73872. get: function () {
  73873. return this._rightStick;
  73874. },
  73875. set: function (newValues) {
  73876. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  73877. this._onrightstickchanged(newValues);
  73878. }
  73879. this._rightStick = newValues;
  73880. },
  73881. enumerable: true,
  73882. configurable: true
  73883. });
  73884. Gamepad.prototype.update = function () {
  73885. if (this._leftStick) {
  73886. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73887. if (this._invertLeftStickY) {
  73888. this.leftStick.y *= -1;
  73889. }
  73890. }
  73891. if (this._rightStick) {
  73892. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73893. }
  73894. };
  73895. Gamepad.prototype.dispose = function () {
  73896. };
  73897. Gamepad.GAMEPAD = 0;
  73898. Gamepad.GENERIC = 1;
  73899. Gamepad.XBOX = 2;
  73900. Gamepad.POSE_ENABLED = 3;
  73901. return Gamepad;
  73902. }());
  73903. BABYLON.Gamepad = Gamepad;
  73904. var GenericPad = /** @class */ (function (_super) {
  73905. __extends(GenericPad, _super);
  73906. function GenericPad(id, index, browserGamepad) {
  73907. var _this = _super.call(this, id, index, browserGamepad) || this;
  73908. _this.onButtonDownObservable = new BABYLON.Observable();
  73909. _this.onButtonUpObservable = new BABYLON.Observable();
  73910. _this.type = Gamepad.GENERIC;
  73911. _this._buttons = new Array(browserGamepad.buttons.length);
  73912. return _this;
  73913. }
  73914. GenericPad.prototype.onbuttondown = function (callback) {
  73915. this._onbuttondown = callback;
  73916. };
  73917. GenericPad.prototype.onbuttonup = function (callback) {
  73918. this._onbuttonup = callback;
  73919. };
  73920. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  73921. if (newValue !== currentValue) {
  73922. if (newValue === 1) {
  73923. if (this._onbuttondown) {
  73924. this._onbuttondown(buttonIndex);
  73925. }
  73926. this.onButtonDownObservable.notifyObservers(buttonIndex);
  73927. }
  73928. if (newValue === 0) {
  73929. if (this._onbuttonup) {
  73930. this._onbuttonup(buttonIndex);
  73931. }
  73932. this.onButtonUpObservable.notifyObservers(buttonIndex);
  73933. }
  73934. }
  73935. return newValue;
  73936. };
  73937. GenericPad.prototype.update = function () {
  73938. _super.prototype.update.call(this);
  73939. for (var index = 0; index < this._buttons.length; index++) {
  73940. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  73941. }
  73942. };
  73943. GenericPad.prototype.dispose = function () {
  73944. _super.prototype.dispose.call(this);
  73945. this.onButtonDownObservable.clear();
  73946. this.onButtonUpObservable.clear();
  73947. };
  73948. return GenericPad;
  73949. }(Gamepad));
  73950. BABYLON.GenericPad = GenericPad;
  73951. })(BABYLON || (BABYLON = {}));
  73952. //# sourceMappingURL=babylon.gamepad.js.map
  73953. var BABYLON;
  73954. (function (BABYLON) {
  73955. /**
  73956. * Defines supported buttons for XBox360 compatible gamepads
  73957. */
  73958. var Xbox360Button;
  73959. (function (Xbox360Button) {
  73960. /** A */
  73961. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73962. /** B */
  73963. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73964. /** X */
  73965. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73966. /** Y */
  73967. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73968. /** Start */
  73969. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73970. /** Back */
  73971. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73972. /** Left button */
  73973. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73974. /** Right button */
  73975. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73976. /** Left stick */
  73977. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73978. /** Right stick */
  73979. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73980. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73981. /** Defines values for XBox360 DPad */
  73982. var Xbox360Dpad;
  73983. (function (Xbox360Dpad) {
  73984. /** Up */
  73985. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  73986. /** Down */
  73987. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  73988. /** Left */
  73989. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  73990. /** Right */
  73991. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  73992. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  73993. /**
  73994. * Defines a XBox360 gamepad
  73995. */
  73996. var Xbox360Pad = /** @class */ (function (_super) {
  73997. __extends(Xbox360Pad, _super);
  73998. /**
  73999. * Creates a new XBox360 gamepad object
  74000. * @param id defines the id of this gamepad
  74001. * @param index defines its index
  74002. * @param gamepad defines the internal HTML gamepad object
  74003. * @param xboxOne defines if it is a XBox One gamepad
  74004. */
  74005. function Xbox360Pad(id, index, gamepad, xboxOne) {
  74006. if (xboxOne === void 0) { xboxOne = false; }
  74007. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  74008. _this._leftTrigger = 0;
  74009. _this._rightTrigger = 0;
  74010. /** Observable raised when a button is pressed */
  74011. _this.onButtonDownObservable = new BABYLON.Observable();
  74012. /** Observable raised when a button is released */
  74013. _this.onButtonUpObservable = new BABYLON.Observable();
  74014. /** Observable raised when a pad is pressed */
  74015. _this.onPadDownObservable = new BABYLON.Observable();
  74016. /** Observable raised when a pad is released */
  74017. _this.onPadUpObservable = new BABYLON.Observable();
  74018. _this._buttonA = 0;
  74019. _this._buttonB = 0;
  74020. _this._buttonX = 0;
  74021. _this._buttonY = 0;
  74022. _this._buttonBack = 0;
  74023. _this._buttonStart = 0;
  74024. _this._buttonLB = 0;
  74025. _this._buttonRB = 0;
  74026. _this._buttonLeftStick = 0;
  74027. _this._buttonRightStick = 0;
  74028. _this._dPadUp = 0;
  74029. _this._dPadDown = 0;
  74030. _this._dPadLeft = 0;
  74031. _this._dPadRight = 0;
  74032. _this._isXboxOnePad = false;
  74033. _this.type = BABYLON.Gamepad.XBOX;
  74034. _this._isXboxOnePad = xboxOne;
  74035. return _this;
  74036. }
  74037. /**
  74038. * Defines the callback to call when left trigger is pressed
  74039. * @param callback defines the callback to use
  74040. */
  74041. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  74042. this._onlefttriggerchanged = callback;
  74043. };
  74044. /**
  74045. * Defines the callback to call when right trigger is pressed
  74046. * @param callback defines the callback to use
  74047. */
  74048. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  74049. this._onrighttriggerchanged = callback;
  74050. };
  74051. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  74052. /**
  74053. * Gets or sets left trigger value
  74054. */
  74055. get: function () {
  74056. return this._leftTrigger;
  74057. },
  74058. set: function (newValue) {
  74059. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  74060. this._onlefttriggerchanged(newValue);
  74061. }
  74062. this._leftTrigger = newValue;
  74063. },
  74064. enumerable: true,
  74065. configurable: true
  74066. });
  74067. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  74068. /**
  74069. * Gets or sets right trigger value
  74070. */
  74071. get: function () {
  74072. return this._rightTrigger;
  74073. },
  74074. set: function (newValue) {
  74075. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  74076. this._onrighttriggerchanged(newValue);
  74077. }
  74078. this._rightTrigger = newValue;
  74079. },
  74080. enumerable: true,
  74081. configurable: true
  74082. });
  74083. /**
  74084. * Defines the callback to call when a button is pressed
  74085. * @param callback defines the callback to use
  74086. */
  74087. Xbox360Pad.prototype.onbuttondown = function (callback) {
  74088. this._onbuttondown = callback;
  74089. };
  74090. /**
  74091. * Defines the callback to call when a button is released
  74092. * @param callback defines the callback to use
  74093. */
  74094. Xbox360Pad.prototype.onbuttonup = function (callback) {
  74095. this._onbuttonup = callback;
  74096. };
  74097. /**
  74098. * Defines the callback to call when a pad is pressed
  74099. * @param callback defines the callback to use
  74100. */
  74101. Xbox360Pad.prototype.ondpaddown = function (callback) {
  74102. this._ondpaddown = callback;
  74103. };
  74104. /**
  74105. * Defines the callback to call when a pad is released
  74106. * @param callback defines the callback to use
  74107. */
  74108. Xbox360Pad.prototype.ondpadup = function (callback) {
  74109. this._ondpadup = callback;
  74110. };
  74111. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  74112. if (newValue !== currentValue) {
  74113. if (newValue === 1) {
  74114. if (this._onbuttondown) {
  74115. this._onbuttondown(buttonType);
  74116. }
  74117. this.onButtonDownObservable.notifyObservers(buttonType);
  74118. }
  74119. if (newValue === 0) {
  74120. if (this._onbuttonup) {
  74121. this._onbuttonup(buttonType);
  74122. }
  74123. this.onButtonUpObservable.notifyObservers(buttonType);
  74124. }
  74125. }
  74126. return newValue;
  74127. };
  74128. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  74129. if (newValue !== currentValue) {
  74130. if (newValue === 1) {
  74131. if (this._ondpaddown) {
  74132. this._ondpaddown(buttonType);
  74133. }
  74134. this.onPadDownObservable.notifyObservers(buttonType);
  74135. }
  74136. if (newValue === 0) {
  74137. if (this._ondpadup) {
  74138. this._ondpadup(buttonType);
  74139. }
  74140. this.onPadUpObservable.notifyObservers(buttonType);
  74141. }
  74142. }
  74143. return newValue;
  74144. };
  74145. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  74146. /** Gets or sets value of A button */
  74147. get: function () {
  74148. return this._buttonA;
  74149. },
  74150. set: function (value) {
  74151. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  74152. },
  74153. enumerable: true,
  74154. configurable: true
  74155. });
  74156. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  74157. /** Gets or sets value of B button */
  74158. get: function () {
  74159. return this._buttonB;
  74160. },
  74161. set: function (value) {
  74162. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  74163. },
  74164. enumerable: true,
  74165. configurable: true
  74166. });
  74167. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  74168. /** Gets or sets value of X button */
  74169. get: function () {
  74170. return this._buttonX;
  74171. },
  74172. set: function (value) {
  74173. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  74174. },
  74175. enumerable: true,
  74176. configurable: true
  74177. });
  74178. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  74179. /** Gets or sets value of Y button */
  74180. get: function () {
  74181. return this._buttonY;
  74182. },
  74183. set: function (value) {
  74184. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  74185. },
  74186. enumerable: true,
  74187. configurable: true
  74188. });
  74189. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  74190. /** Gets or sets value of Start button */
  74191. get: function () {
  74192. return this._buttonStart;
  74193. },
  74194. set: function (value) {
  74195. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  74196. },
  74197. enumerable: true,
  74198. configurable: true
  74199. });
  74200. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  74201. /** Gets or sets value of Back button */
  74202. get: function () {
  74203. return this._buttonBack;
  74204. },
  74205. set: function (value) {
  74206. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  74207. },
  74208. enumerable: true,
  74209. configurable: true
  74210. });
  74211. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  74212. /** Gets or sets value of Left button */
  74213. get: function () {
  74214. return this._buttonLB;
  74215. },
  74216. set: function (value) {
  74217. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  74218. },
  74219. enumerable: true,
  74220. configurable: true
  74221. });
  74222. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  74223. /** Gets or sets value of Right button */
  74224. get: function () {
  74225. return this._buttonRB;
  74226. },
  74227. set: function (value) {
  74228. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  74229. },
  74230. enumerable: true,
  74231. configurable: true
  74232. });
  74233. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  74234. /** Gets or sets value of left stick */
  74235. get: function () {
  74236. return this._buttonLeftStick;
  74237. },
  74238. set: function (value) {
  74239. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  74240. },
  74241. enumerable: true,
  74242. configurable: true
  74243. });
  74244. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74245. /** Gets or sets value of right stick */
  74246. get: function () {
  74247. return this._buttonRightStick;
  74248. },
  74249. set: function (value) {
  74250. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74251. },
  74252. enumerable: true,
  74253. configurable: true
  74254. });
  74255. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74256. /** Gets or sets value of DPad up */
  74257. get: function () {
  74258. return this._dPadUp;
  74259. },
  74260. set: function (value) {
  74261. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74262. },
  74263. enumerable: true,
  74264. configurable: true
  74265. });
  74266. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74267. /** Gets or sets value of DPad down */
  74268. get: function () {
  74269. return this._dPadDown;
  74270. },
  74271. set: function (value) {
  74272. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74273. },
  74274. enumerable: true,
  74275. configurable: true
  74276. });
  74277. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74278. /** Gets or sets value of DPad left */
  74279. get: function () {
  74280. return this._dPadLeft;
  74281. },
  74282. set: function (value) {
  74283. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74284. },
  74285. enumerable: true,
  74286. configurable: true
  74287. });
  74288. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74289. /** Gets or sets value of DPad right */
  74290. get: function () {
  74291. return this._dPadRight;
  74292. },
  74293. set: function (value) {
  74294. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74295. },
  74296. enumerable: true,
  74297. configurable: true
  74298. });
  74299. /**
  74300. * Force the gamepad to synchronize with device values
  74301. */
  74302. Xbox360Pad.prototype.update = function () {
  74303. _super.prototype.update.call(this);
  74304. if (this._isXboxOnePad) {
  74305. this.buttonA = this.browserGamepad.buttons[0].value;
  74306. this.buttonB = this.browserGamepad.buttons[1].value;
  74307. this.buttonX = this.browserGamepad.buttons[2].value;
  74308. this.buttonY = this.browserGamepad.buttons[3].value;
  74309. this.buttonLB = this.browserGamepad.buttons[4].value;
  74310. this.buttonRB = this.browserGamepad.buttons[5].value;
  74311. this.leftTrigger = this.browserGamepad.axes[2];
  74312. this.rightTrigger = this.browserGamepad.axes[5];
  74313. this.buttonBack = this.browserGamepad.buttons[9].value;
  74314. this.buttonStart = this.browserGamepad.buttons[8].value;
  74315. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74316. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74317. this.dPadUp = this.browserGamepad.buttons[11].value;
  74318. this.dPadDown = this.browserGamepad.buttons[12].value;
  74319. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74320. this.dPadRight = this.browserGamepad.buttons[14].value;
  74321. }
  74322. else {
  74323. this.buttonA = this.browserGamepad.buttons[0].value;
  74324. this.buttonB = this.browserGamepad.buttons[1].value;
  74325. this.buttonX = this.browserGamepad.buttons[2].value;
  74326. this.buttonY = this.browserGamepad.buttons[3].value;
  74327. this.buttonLB = this.browserGamepad.buttons[4].value;
  74328. this.buttonRB = this.browserGamepad.buttons[5].value;
  74329. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74330. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74331. this.buttonBack = this.browserGamepad.buttons[8].value;
  74332. this.buttonStart = this.browserGamepad.buttons[9].value;
  74333. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74334. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74335. this.dPadUp = this.browserGamepad.buttons[12].value;
  74336. this.dPadDown = this.browserGamepad.buttons[13].value;
  74337. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74338. this.dPadRight = this.browserGamepad.buttons[15].value;
  74339. }
  74340. };
  74341. Xbox360Pad.prototype.dispose = function () {
  74342. _super.prototype.dispose.call(this);
  74343. this.onButtonDownObservable.clear();
  74344. this.onButtonUpObservable.clear();
  74345. this.onPadDownObservable.clear();
  74346. this.onPadUpObservable.clear();
  74347. };
  74348. return Xbox360Pad;
  74349. }(BABYLON.Gamepad));
  74350. BABYLON.Xbox360Pad = Xbox360Pad;
  74351. })(BABYLON || (BABYLON = {}));
  74352. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74353. var BABYLON;
  74354. (function (BABYLON) {
  74355. /**
  74356. * Defines the types of pose enabled controllers that are supported
  74357. */
  74358. var PoseEnabledControllerType;
  74359. (function (PoseEnabledControllerType) {
  74360. /**
  74361. * HTC Vive
  74362. */
  74363. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74364. /**
  74365. * Oculus Rift
  74366. */
  74367. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74368. /**
  74369. * Windows mixed reality
  74370. */
  74371. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74372. /**
  74373. * Samsung gear VR
  74374. */
  74375. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  74376. /**
  74377. * Google Daydream
  74378. */
  74379. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  74380. /**
  74381. * Generic
  74382. */
  74383. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  74384. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  74385. /**
  74386. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74387. */
  74388. var PoseEnabledControllerHelper = /** @class */ (function () {
  74389. function PoseEnabledControllerHelper() {
  74390. }
  74391. /**
  74392. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74393. * @param vrGamepad the gamepad to initialized
  74394. * @returns a vr controller of the type the gamepad identified as
  74395. */
  74396. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  74397. // Oculus Touch
  74398. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  74399. return new BABYLON.OculusTouchController(vrGamepad);
  74400. }
  74401. // Windows Mixed Reality controllers
  74402. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  74403. return new BABYLON.WindowsMotionController(vrGamepad);
  74404. }
  74405. // HTC Vive
  74406. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  74407. return new BABYLON.ViveController(vrGamepad);
  74408. }
  74409. // Samsung/Oculus Gear VR or Oculus Go
  74410. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  74411. return new BABYLON.GearVRController(vrGamepad);
  74412. }
  74413. // Google Daydream
  74414. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  74415. return new BABYLON.DaydreamController(vrGamepad);
  74416. }
  74417. // Generic
  74418. else {
  74419. return new BABYLON.GenericController(vrGamepad);
  74420. }
  74421. };
  74422. return PoseEnabledControllerHelper;
  74423. }());
  74424. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  74425. /**
  74426. * Defines the PoseEnabledController object that contains state of a vr capable controller
  74427. */
  74428. var PoseEnabledController = /** @class */ (function (_super) {
  74429. __extends(PoseEnabledController, _super);
  74430. /**
  74431. * Creates a new PoseEnabledController from a gamepad
  74432. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  74433. */
  74434. function PoseEnabledController(browserGamepad) {
  74435. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  74436. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74437. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74438. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  74439. /**
  74440. * The device position in babylon space
  74441. */
  74442. _this.devicePosition = BABYLON.Vector3.Zero();
  74443. /**
  74444. * The device rotation in babylon space
  74445. */
  74446. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  74447. /**
  74448. * The scale factor of the device in babylon space
  74449. */
  74450. _this.deviceScaleFactor = 1;
  74451. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  74452. /**
  74453. * Internal, matrix used to convert room space to babylon space
  74454. * @hidden
  74455. */
  74456. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74457. /**
  74458. * Node to be used when casting a ray from the controller
  74459. * @hidden
  74460. */
  74461. _this._pointingPoseNode = null;
  74462. _this._workingMatrix = BABYLON.Matrix.Identity();
  74463. /**
  74464. * @hidden
  74465. */
  74466. _this._meshAttachedObservable = new BABYLON.Observable();
  74467. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  74468. _this.controllerType = PoseEnabledControllerType.GENERIC;
  74469. _this.position = BABYLON.Vector3.Zero();
  74470. _this.rotationQuaternion = new BABYLON.Quaternion();
  74471. _this._calculatedPosition = BABYLON.Vector3.Zero();
  74472. _this._calculatedRotation = new BABYLON.Quaternion();
  74473. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  74474. return _this;
  74475. }
  74476. /**
  74477. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  74478. */
  74479. PoseEnabledController.prototype.update = function () {
  74480. _super.prototype.update.call(this);
  74481. this._updatePoseAndMesh();
  74482. };
  74483. /**
  74484. * Updates only the pose device and mesh without doing any button event checking
  74485. */
  74486. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  74487. var pose = this.browserGamepad.pose;
  74488. this.updateFromDevice(pose);
  74489. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  74490. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  74491. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74492. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  74493. if (this._mesh) {
  74494. this._mesh.position.copyFrom(this.devicePosition);
  74495. if (this._mesh.rotationQuaternion) {
  74496. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  74497. }
  74498. }
  74499. };
  74500. /**
  74501. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74502. * @param poseData raw pose fromthe device
  74503. */
  74504. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  74505. if (poseData) {
  74506. this.rawPose = poseData;
  74507. if (poseData.position) {
  74508. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  74509. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  74510. this._deviceRoomPosition.z *= -1;
  74511. }
  74512. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  74513. this._calculatedPosition.addInPlace(this.position);
  74514. }
  74515. var pose = this.rawPose;
  74516. if (poseData.orientation && pose.orientation) {
  74517. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  74518. if (this._mesh) {
  74519. if (this._mesh.getScene().useRightHandedSystem) {
  74520. this._deviceRoomRotationQuaternion.z *= -1;
  74521. this._deviceRoomRotationQuaternion.w *= -1;
  74522. }
  74523. else {
  74524. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  74525. }
  74526. }
  74527. // if the camera is set, rotate to the camera's rotation
  74528. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  74529. }
  74530. }
  74531. };
  74532. /**
  74533. * Attaches a mesh to the controller
  74534. * @param mesh the mesh to be attached
  74535. */
  74536. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  74537. if (this._mesh) {
  74538. this._mesh.parent = null;
  74539. }
  74540. this._mesh = mesh;
  74541. if (this._poseControlledCamera) {
  74542. this._mesh.parent = this._poseControlledCamera;
  74543. }
  74544. if (!this._mesh.rotationQuaternion) {
  74545. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  74546. }
  74547. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  74548. this._updatePoseAndMesh();
  74549. if (this._pointingPoseNode) {
  74550. var parents = [];
  74551. var obj = this._pointingPoseNode;
  74552. while (obj.parent) {
  74553. parents.push(obj.parent);
  74554. obj = obj.parent;
  74555. }
  74556. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74557. }
  74558. this._meshAttachedObservable.notifyObservers(mesh);
  74559. };
  74560. /**
  74561. * Attaches the controllers mesh to a camera
  74562. * @param camera the camera the mesh should be attached to
  74563. */
  74564. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74565. this._poseControlledCamera = camera;
  74566. if (this._mesh) {
  74567. this._mesh.parent = this._poseControlledCamera;
  74568. }
  74569. };
  74570. /**
  74571. * Disposes of the controller
  74572. */
  74573. PoseEnabledController.prototype.dispose = function () {
  74574. if (this._mesh) {
  74575. this._mesh.dispose();
  74576. }
  74577. this._mesh = null;
  74578. _super.prototype.dispose.call(this);
  74579. };
  74580. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74581. /**
  74582. * The mesh that is attached to the controller
  74583. */
  74584. get: function () {
  74585. return this._mesh;
  74586. },
  74587. enumerable: true,
  74588. configurable: true
  74589. });
  74590. /**
  74591. * Gets the ray of the controller in the direction the controller is pointing
  74592. * @param length the length the resulting ray should be
  74593. * @returns a ray in the direction the controller is pointing
  74594. */
  74595. PoseEnabledController.prototype.getForwardRay = function (length) {
  74596. if (length === void 0) { length = 100; }
  74597. if (!this.mesh) {
  74598. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74599. }
  74600. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74601. var origin = m.getTranslation();
  74602. var forward = new BABYLON.Vector3(0, 0, -1);
  74603. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74604. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74605. return new BABYLON.Ray(origin, direction, length);
  74606. };
  74607. /**
  74608. * Name of the child mesh that can be used to cast a ray from the controller
  74609. */
  74610. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74611. return PoseEnabledController;
  74612. }(BABYLON.Gamepad));
  74613. BABYLON.PoseEnabledController = PoseEnabledController;
  74614. })(BABYLON || (BABYLON = {}));
  74615. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74616. var BABYLON;
  74617. (function (BABYLON) {
  74618. /**
  74619. * Defines the WebVRController object that represents controllers tracked in 3D space
  74620. */
  74621. var WebVRController = /** @class */ (function (_super) {
  74622. __extends(WebVRController, _super);
  74623. /**
  74624. * Creates a new WebVRController from a gamepad
  74625. * @param vrGamepad the gamepad that the WebVRController should be created from
  74626. */
  74627. function WebVRController(vrGamepad) {
  74628. var _this = _super.call(this, vrGamepad) || this;
  74629. // Observables
  74630. /**
  74631. * Fired when the trigger state has changed
  74632. */
  74633. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74634. /**
  74635. * Fired when the main button state has changed
  74636. */
  74637. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74638. /**
  74639. * Fired when the secondary button state has changed
  74640. */
  74641. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74642. /**
  74643. * Fired when the pad state has changed
  74644. */
  74645. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74646. /**
  74647. * Fired when controllers stick values have changed
  74648. */
  74649. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74650. /**
  74651. * X and Y axis corrisponding to the controllers joystick
  74652. */
  74653. _this.pad = { x: 0, y: 0 };
  74654. // avoid GC, store state in a tmp object
  74655. _this._changes = {
  74656. pressChanged: false,
  74657. touchChanged: false,
  74658. valueChanged: false,
  74659. changed: false
  74660. };
  74661. _this._buttons = new Array(vrGamepad.buttons.length);
  74662. _this.hand = vrGamepad.hand;
  74663. return _this;
  74664. }
  74665. /**
  74666. * Fired when a controller button's state has changed
  74667. * @param callback the callback containing the button that was modified
  74668. */
  74669. WebVRController.prototype.onButtonStateChange = function (callback) {
  74670. this._onButtonStateChange = callback;
  74671. };
  74672. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74673. /**
  74674. * The default controller model for the controller
  74675. */
  74676. get: function () {
  74677. return this._defaultModel;
  74678. },
  74679. enumerable: true,
  74680. configurable: true
  74681. });
  74682. /**
  74683. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74684. */
  74685. WebVRController.prototype.update = function () {
  74686. _super.prototype.update.call(this);
  74687. for (var index = 0; index < this._buttons.length; index++) {
  74688. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74689. }
  74690. ;
  74691. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74692. this.pad.x = this.leftStick.x;
  74693. this.pad.y = this.leftStick.y;
  74694. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74695. }
  74696. };
  74697. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74698. if (!newState) {
  74699. newState = {
  74700. pressed: false,
  74701. touched: false,
  74702. value: 0
  74703. };
  74704. }
  74705. if (!currentState) {
  74706. this._buttons[buttonIndex] = {
  74707. pressed: newState.pressed,
  74708. touched: newState.touched,
  74709. value: newState.value
  74710. };
  74711. return;
  74712. }
  74713. this._checkChanges(newState, currentState);
  74714. if (this._changes.changed) {
  74715. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74716. this._handleButtonChange(buttonIndex, newState, this._changes);
  74717. }
  74718. this._buttons[buttonIndex].pressed = newState.pressed;
  74719. this._buttons[buttonIndex].touched = newState.touched;
  74720. // oculus triggers are never 0, thou not touched.
  74721. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74722. };
  74723. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74724. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74725. this._changes.touchChanged = newState.touched !== currentState.touched;
  74726. this._changes.valueChanged = newState.value !== currentState.value;
  74727. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74728. return this._changes;
  74729. };
  74730. /**
  74731. * Disposes of th webVRCOntroller
  74732. */
  74733. WebVRController.prototype.dispose = function () {
  74734. _super.prototype.dispose.call(this);
  74735. this.onTriggerStateChangedObservable.clear();
  74736. this.onMainButtonStateChangedObservable.clear();
  74737. this.onSecondaryButtonStateChangedObservable.clear();
  74738. this.onPadStateChangedObservable.clear();
  74739. this.onPadValuesChangedObservable.clear();
  74740. };
  74741. return WebVRController;
  74742. }(BABYLON.PoseEnabledController));
  74743. BABYLON.WebVRController = WebVRController;
  74744. })(BABYLON || (BABYLON = {}));
  74745. //# sourceMappingURL=babylon.webVRController.js.map
  74746. var BABYLON;
  74747. (function (BABYLON) {
  74748. /**
  74749. * Oculus Touch Controller
  74750. */
  74751. var OculusTouchController = /** @class */ (function (_super) {
  74752. __extends(OculusTouchController, _super);
  74753. /**
  74754. * Creates a new OculusTouchController from a gamepad
  74755. * @param vrGamepad the gamepad that the controller should be created from
  74756. */
  74757. function OculusTouchController(vrGamepad) {
  74758. var _this = _super.call(this, vrGamepad) || this;
  74759. /**
  74760. * Fired when the secondary trigger on this controller is modified
  74761. */
  74762. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74763. /**
  74764. * Fired when the thumb rest on this controller is modified
  74765. */
  74766. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74767. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74768. return _this;
  74769. }
  74770. /**
  74771. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74772. * @param scene scene in which to add meshes
  74773. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74774. */
  74775. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74776. var _this = this;
  74777. var meshName;
  74778. // Hand
  74779. if (this.hand === 'left') {
  74780. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74781. }
  74782. else { // Right is the default if no hand is specified
  74783. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74784. }
  74785. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74786. /*
  74787. Parent Mesh name: oculus_touch_left
  74788. - body
  74789. - trigger
  74790. - thumbstick
  74791. - grip
  74792. - button_y
  74793. - button_x
  74794. - button_enter
  74795. */
  74796. _this._defaultModel = newMeshes[1];
  74797. _this.attachToMesh(_this._defaultModel);
  74798. if (meshLoaded) {
  74799. meshLoaded(_this._defaultModel);
  74800. }
  74801. });
  74802. };
  74803. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74804. /**
  74805. * Fired when the A button on this controller is modified
  74806. */
  74807. get: function () {
  74808. if (this.hand === 'right') {
  74809. return this.onMainButtonStateChangedObservable;
  74810. }
  74811. else {
  74812. throw new Error('No A button on left hand');
  74813. }
  74814. },
  74815. enumerable: true,
  74816. configurable: true
  74817. });
  74818. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74819. /**
  74820. * Fired when the B button on this controller is modified
  74821. */
  74822. get: function () {
  74823. if (this.hand === 'right') {
  74824. return this.onSecondaryButtonStateChangedObservable;
  74825. }
  74826. else {
  74827. throw new Error('No B button on left hand');
  74828. }
  74829. },
  74830. enumerable: true,
  74831. configurable: true
  74832. });
  74833. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74834. /**
  74835. * Fired when the X button on this controller is modified
  74836. */
  74837. get: function () {
  74838. if (this.hand === 'left') {
  74839. return this.onMainButtonStateChangedObservable;
  74840. }
  74841. else {
  74842. throw new Error('No X button on right hand');
  74843. }
  74844. },
  74845. enumerable: true,
  74846. configurable: true
  74847. });
  74848. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  74849. /**
  74850. * Fired when the Y button on this controller is modified
  74851. */
  74852. get: function () {
  74853. if (this.hand === 'left') {
  74854. return this.onSecondaryButtonStateChangedObservable;
  74855. }
  74856. else {
  74857. throw new Error('No Y button on right hand');
  74858. }
  74859. },
  74860. enumerable: true,
  74861. configurable: true
  74862. });
  74863. /**
  74864. * Called once for each button that changed state since the last frame
  74865. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  74866. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  74867. * 2) secondary trigger (same)
  74868. * 3) A (right) X (left), touch, pressed = value
  74869. * 4) B / Y
  74870. * 5) thumb rest
  74871. * @param buttonIdx Which button index changed
  74872. * @param state New state of the button
  74873. * @param changes Which properties on the state changed since last frame
  74874. */
  74875. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74876. var notifyObject = state; //{ state: state, changes: changes };
  74877. var triggerDirection = this.hand === 'right' ? -1 : 1;
  74878. switch (buttonIdx) {
  74879. case 0:
  74880. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74881. return;
  74882. case 1: // index trigger
  74883. if (this._defaultModel) {
  74884. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  74885. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  74886. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  74887. }
  74888. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74889. return;
  74890. case 2: // secondary trigger
  74891. if (this._defaultModel) {
  74892. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  74893. }
  74894. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  74895. return;
  74896. case 3:
  74897. if (this._defaultModel) {
  74898. if (notifyObject.pressed) {
  74899. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  74900. }
  74901. else {
  74902. (this._defaultModel.getChildren()[1]).position.y = 0;
  74903. }
  74904. }
  74905. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74906. return;
  74907. case 4:
  74908. if (this._defaultModel) {
  74909. if (notifyObject.pressed) {
  74910. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74911. }
  74912. else {
  74913. (this._defaultModel.getChildren()[2]).position.y = 0;
  74914. }
  74915. }
  74916. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74917. return;
  74918. case 5:
  74919. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  74920. return;
  74921. }
  74922. };
  74923. /**
  74924. * Base Url for the controller model.
  74925. */
  74926. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  74927. /**
  74928. * File name for the left controller model.
  74929. */
  74930. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  74931. /**
  74932. * File name for the right controller model.
  74933. */
  74934. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  74935. return OculusTouchController;
  74936. }(BABYLON.WebVRController));
  74937. BABYLON.OculusTouchController = OculusTouchController;
  74938. })(BABYLON || (BABYLON = {}));
  74939. //# sourceMappingURL=babylon.oculusTouchController.js.map
  74940. var BABYLON;
  74941. (function (BABYLON) {
  74942. /**
  74943. * Vive Controller
  74944. */
  74945. var ViveController = /** @class */ (function (_super) {
  74946. __extends(ViveController, _super);
  74947. /**
  74948. * Creates a new ViveController from a gamepad
  74949. * @param vrGamepad the gamepad that the controller should be created from
  74950. */
  74951. function ViveController(vrGamepad) {
  74952. var _this = _super.call(this, vrGamepad) || this;
  74953. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74954. _this._invertLeftStickY = true;
  74955. return _this;
  74956. }
  74957. /**
  74958. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74959. * @param scene scene in which to add meshes
  74960. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74961. */
  74962. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74963. var _this = this;
  74964. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74965. /*
  74966. Parent Mesh name: ViveWand
  74967. - body
  74968. - r_gripper
  74969. - l_gripper
  74970. - menu_button
  74971. - system_button
  74972. - trackpad
  74973. - trigger
  74974. - LED
  74975. */
  74976. _this._defaultModel = newMeshes[1];
  74977. _this.attachToMesh(_this._defaultModel);
  74978. if (meshLoaded) {
  74979. meshLoaded(_this._defaultModel);
  74980. }
  74981. });
  74982. };
  74983. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  74984. /**
  74985. * Fired when the left button on this controller is modified
  74986. */
  74987. get: function () {
  74988. return this.onMainButtonStateChangedObservable;
  74989. },
  74990. enumerable: true,
  74991. configurable: true
  74992. });
  74993. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  74994. /**
  74995. * Fired when the right button on this controller is modified
  74996. */
  74997. get: function () {
  74998. return this.onMainButtonStateChangedObservable;
  74999. },
  75000. enumerable: true,
  75001. configurable: true
  75002. });
  75003. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  75004. /**
  75005. * Fired when the menu button on this controller is modified
  75006. */
  75007. get: function () {
  75008. return this.onSecondaryButtonStateChangedObservable;
  75009. },
  75010. enumerable: true,
  75011. configurable: true
  75012. });
  75013. /**
  75014. * Called once for each button that changed state since the last frame
  75015. * Vive mapping:
  75016. * 0: touchpad
  75017. * 1: trigger
  75018. * 2: left AND right buttons
  75019. * 3: menu button
  75020. * @param buttonIdx Which button index changed
  75021. * @param state New state of the button
  75022. * @param changes Which properties on the state changed since last frame
  75023. */
  75024. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75025. var notifyObject = state; //{ state: state, changes: changes };
  75026. switch (buttonIdx) {
  75027. case 0:
  75028. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75029. return;
  75030. case 1: // index trigger
  75031. if (this._defaultModel) {
  75032. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  75033. }
  75034. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75035. return;
  75036. case 2: // left AND right button
  75037. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75038. return;
  75039. case 3:
  75040. if (this._defaultModel) {
  75041. if (notifyObject.pressed) {
  75042. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75043. }
  75044. else {
  75045. (this._defaultModel.getChildren()[2]).position.y = 0;
  75046. }
  75047. }
  75048. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75049. return;
  75050. }
  75051. };
  75052. /**
  75053. * Base Url for the controller model.
  75054. */
  75055. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  75056. /**
  75057. * File name for the controller model.
  75058. */
  75059. ViveController.MODEL_FILENAME = 'wand.babylon';
  75060. return ViveController;
  75061. }(BABYLON.WebVRController));
  75062. BABYLON.ViveController = ViveController;
  75063. })(BABYLON || (BABYLON = {}));
  75064. //# sourceMappingURL=babylon.viveController.js.map
  75065. var BABYLON;
  75066. (function (BABYLON) {
  75067. /**
  75068. * Generic Controller
  75069. */
  75070. var GenericController = /** @class */ (function (_super) {
  75071. __extends(GenericController, _super);
  75072. /**
  75073. * Creates a new GenericController from a gamepad
  75074. * @param vrGamepad the gamepad that the controller should be created from
  75075. */
  75076. function GenericController(vrGamepad) {
  75077. return _super.call(this, vrGamepad) || this;
  75078. }
  75079. /**
  75080. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75081. * @param scene scene in which to add meshes
  75082. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75083. */
  75084. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75085. var _this = this;
  75086. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  75087. _this._defaultModel = newMeshes[1];
  75088. _this.attachToMesh(_this._defaultModel);
  75089. if (meshLoaded) {
  75090. meshLoaded(_this._defaultModel);
  75091. }
  75092. });
  75093. };
  75094. /**
  75095. * Called once for each button that changed state since the last frame
  75096. * @param buttonIdx Which button index changed
  75097. * @param state New state of the button
  75098. * @param changes Which properties on the state changed since last frame
  75099. */
  75100. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75101. console.log("Button id: " + buttonIdx + "state: ");
  75102. console.dir(state);
  75103. };
  75104. /**
  75105. * Base Url for the controller model.
  75106. */
  75107. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75108. /**
  75109. * File name for the controller model.
  75110. */
  75111. GenericController.MODEL_FILENAME = 'generic.babylon';
  75112. return GenericController;
  75113. }(BABYLON.WebVRController));
  75114. BABYLON.GenericController = GenericController;
  75115. })(BABYLON || (BABYLON = {}));
  75116. //# sourceMappingURL=babylon.genericController.js.map
  75117. var BABYLON;
  75118. (function (BABYLON) {
  75119. /**
  75120. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  75121. */
  75122. var LoadedMeshInfo = /** @class */ (function () {
  75123. function LoadedMeshInfo() {
  75124. /**
  75125. * Map of the button meshes contained in the controller
  75126. */
  75127. this.buttonMeshes = {};
  75128. /**
  75129. * Map of the axis meshes contained in the controller
  75130. */
  75131. this.axisMeshes = {};
  75132. }
  75133. return LoadedMeshInfo;
  75134. }());
  75135. /**
  75136. * Defines the WindowsMotionController object that the state of the windows motion controller
  75137. */
  75138. var WindowsMotionController = /** @class */ (function (_super) {
  75139. __extends(WindowsMotionController, _super);
  75140. /**
  75141. * Creates a new WindowsMotionController from a gamepad
  75142. * @param vrGamepad the gamepad that the controller should be created from
  75143. */
  75144. function WindowsMotionController(vrGamepad) {
  75145. var _this = _super.call(this, vrGamepad) || this;
  75146. _this._mapping = {
  75147. // Semantic button names
  75148. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  75149. // A mapping of the button name to glTF model node name
  75150. // that should be transformed by button value.
  75151. buttonMeshNames: {
  75152. 'trigger': 'SELECT',
  75153. 'menu': 'MENU',
  75154. 'grip': 'GRASP',
  75155. 'thumbstick': 'THUMBSTICK_PRESS',
  75156. 'trackpad': 'TOUCHPAD_PRESS'
  75157. },
  75158. // This mapping is used to translate from the Motion Controller to Babylon semantics
  75159. buttonObservableNames: {
  75160. 'trigger': 'onTriggerStateChangedObservable',
  75161. 'menu': 'onSecondaryButtonStateChangedObservable',
  75162. 'grip': 'onMainButtonStateChangedObservable',
  75163. 'thumbstick': 'onPadStateChangedObservable',
  75164. 'trackpad': 'onTrackpadChangedObservable'
  75165. },
  75166. // A mapping of the axis name to glTF model node name
  75167. // that should be transformed by axis value.
  75168. // This array mirrors the browserGamepad.axes array, such that
  75169. // the mesh corresponding to axis 0 is in this array index 0.
  75170. axisMeshNames: [
  75171. 'THUMBSTICK_X',
  75172. 'THUMBSTICK_Y',
  75173. 'TOUCHPAD_TOUCH_X',
  75174. 'TOUCHPAD_TOUCH_Y'
  75175. ],
  75176. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  75177. };
  75178. /**
  75179. * Fired when the trackpad on this controller is clicked
  75180. */
  75181. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  75182. /**
  75183. * Fired when the trackpad on this controller is modified
  75184. */
  75185. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  75186. /**
  75187. * The current x and y values of this controller's trackpad
  75188. */
  75189. _this.trackpad = { x: 0, y: 0 };
  75190. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  75191. _this._loadedMeshInfo = null;
  75192. return _this;
  75193. }
  75194. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  75195. /**
  75196. * Fired when the trigger on this controller is modified
  75197. */
  75198. get: function () {
  75199. return this.onTriggerStateChangedObservable;
  75200. },
  75201. enumerable: true,
  75202. configurable: true
  75203. });
  75204. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  75205. /**
  75206. * Fired when the menu button on this controller is modified
  75207. */
  75208. get: function () {
  75209. return this.onSecondaryButtonStateChangedObservable;
  75210. },
  75211. enumerable: true,
  75212. configurable: true
  75213. });
  75214. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  75215. /**
  75216. * Fired when the grip button on this controller is modified
  75217. */
  75218. get: function () {
  75219. return this.onMainButtonStateChangedObservable;
  75220. },
  75221. enumerable: true,
  75222. configurable: true
  75223. });
  75224. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  75225. /**
  75226. * Fired when the thumbstick button on this controller is modified
  75227. */
  75228. get: function () {
  75229. return this.onPadStateChangedObservable;
  75230. },
  75231. enumerable: true,
  75232. configurable: true
  75233. });
  75234. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  75235. /**
  75236. * Fired when the touchpad button on this controller is modified
  75237. */
  75238. get: function () {
  75239. return this.onTrackpadChangedObservable;
  75240. },
  75241. enumerable: true,
  75242. configurable: true
  75243. });
  75244. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75245. /**
  75246. * Fired when the touchpad values on this controller are modified
  75247. */
  75248. get: function () {
  75249. return this.onTrackpadValuesChangedObservable;
  75250. },
  75251. enumerable: true,
  75252. configurable: true
  75253. });
  75254. WindowsMotionController.prototype._updateTrackpad = function () {
  75255. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75256. this.trackpad.x = this.browserGamepad["axes"][2];
  75257. this.trackpad.y = this.browserGamepad["axes"][3];
  75258. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75259. }
  75260. };
  75261. /**
  75262. * Called once per frame by the engine.
  75263. */
  75264. WindowsMotionController.prototype.update = function () {
  75265. _super.prototype.update.call(this);
  75266. if (this.browserGamepad.axes) {
  75267. this._updateTrackpad();
  75268. // Only need to animate axes if there is a loaded mesh
  75269. if (this._loadedMeshInfo) {
  75270. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75271. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75272. }
  75273. }
  75274. }
  75275. };
  75276. /**
  75277. * Called once for each button that changed state since the last frame
  75278. * @param buttonIdx Which button index changed
  75279. * @param state New state of the button
  75280. * @param changes Which properties on the state changed since last frame
  75281. */
  75282. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75283. var buttonName = this._mapping.buttons[buttonIdx];
  75284. if (!buttonName) {
  75285. return;
  75286. }
  75287. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75288. this._updateTrackpad();
  75289. // Only emit events for buttons that we know how to map from index to name
  75290. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75291. if (observable) {
  75292. observable.notifyObservers(state);
  75293. }
  75294. this._lerpButtonTransform(buttonName, state.value);
  75295. };
  75296. /**
  75297. * Moves the buttons on the controller mesh based on their current state
  75298. * @param buttonName the name of the button to move
  75299. * @param buttonValue the value of the button which determines the buttons new position
  75300. */
  75301. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75302. // If there is no loaded mesh, there is nothing to transform.
  75303. if (!this._loadedMeshInfo) {
  75304. return;
  75305. }
  75306. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75307. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75308. return;
  75309. }
  75310. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75311. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75312. };
  75313. /**
  75314. * Moves the axis on the controller mesh based on its current state
  75315. * @param axis the index of the axis
  75316. * @param axisValue the value of the axis which determines the meshes new position
  75317. * @hidden
  75318. */
  75319. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75320. if (!this._loadedMeshInfo) {
  75321. return;
  75322. }
  75323. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75324. if (!meshInfo) {
  75325. return;
  75326. }
  75327. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75328. return;
  75329. }
  75330. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75331. var lerpValue = axisValue * 0.5 + 0.5;
  75332. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75333. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75334. };
  75335. /**
  75336. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75337. * @param scene scene in which to add meshes
  75338. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75339. */
  75340. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75341. var _this = this;
  75342. if (forceDefault === void 0) { forceDefault = false; }
  75343. var path;
  75344. var filename;
  75345. // Checking if GLB loader is present
  75346. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75347. // Determine the device specific folder based on the ID suffix
  75348. var device = 'default';
  75349. if (this.id && !forceDefault) {
  75350. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75351. device = ((match && match[0]) || device);
  75352. }
  75353. // Hand
  75354. if (this.hand === 'left') {
  75355. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75356. }
  75357. else { // Right is the default if no hand is specified
  75358. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75359. }
  75360. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75361. }
  75362. else {
  75363. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75364. path = BABYLON.GenericController.MODEL_BASE_URL;
  75365. filename = BABYLON.GenericController.MODEL_FILENAME;
  75366. }
  75367. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75368. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75369. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75370. if (!_this._loadedMeshInfo) {
  75371. return;
  75372. }
  75373. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75374. _this.attachToMesh(_this._defaultModel);
  75375. if (meshLoaded) {
  75376. meshLoaded(_this._defaultModel);
  75377. }
  75378. }, null, function (scene, message) {
  75379. BABYLON.Tools.Log(message);
  75380. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  75381. if (!forceDefault) {
  75382. _this.initControllerMesh(scene, meshLoaded, true);
  75383. }
  75384. });
  75385. };
  75386. /**
  75387. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  75388. * can be transformed by button presses and axes values, based on this._mapping.
  75389. *
  75390. * @param scene scene in which the meshes exist
  75391. * @param meshes list of meshes that make up the controller model to process
  75392. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  75393. */
  75394. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  75395. var loadedMeshInfo = null;
  75396. // Create a new mesh to contain the glTF hierarchy
  75397. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  75398. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  75399. var childMesh = null;
  75400. for (var i = 0; i < meshes.length; i++) {
  75401. var mesh = meshes[i];
  75402. if (!mesh.parent) {
  75403. // Exclude controller meshes from picking results
  75404. mesh.isPickable = false;
  75405. // Handle root node, attach to the new parentMesh
  75406. childMesh = mesh;
  75407. break;
  75408. }
  75409. }
  75410. if (childMesh) {
  75411. childMesh.setParent(parentMesh);
  75412. // Create our mesh info. Note that this method will always return non-null.
  75413. loadedMeshInfo = this.createMeshInfo(parentMesh);
  75414. }
  75415. else {
  75416. BABYLON.Tools.Warn('Could not find root node in model file.');
  75417. }
  75418. return loadedMeshInfo;
  75419. };
  75420. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  75421. var loadedMeshInfo = new LoadedMeshInfo();
  75422. var i;
  75423. loadedMeshInfo.rootNode = rootNode;
  75424. // Reset the caches
  75425. loadedMeshInfo.buttonMeshes = {};
  75426. loadedMeshInfo.axisMeshes = {};
  75427. // Button Meshes
  75428. for (i = 0; i < this._mapping.buttons.length; i++) {
  75429. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  75430. if (!buttonMeshName) {
  75431. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  75432. continue;
  75433. }
  75434. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  75435. if (!buttonMesh) {
  75436. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  75437. continue;
  75438. }
  75439. var buttonMeshInfo = {
  75440. index: i,
  75441. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  75442. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  75443. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  75444. };
  75445. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  75446. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  75447. }
  75448. else {
  75449. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  75450. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  75451. '(VALUE: ' + !!buttonMeshInfo.value +
  75452. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  75453. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  75454. ')');
  75455. }
  75456. }
  75457. // Axis Meshes
  75458. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  75459. var axisMeshName = this._mapping.axisMeshNames[i];
  75460. if (!axisMeshName) {
  75461. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  75462. continue;
  75463. }
  75464. var axisMesh = getChildByName(rootNode, axisMeshName);
  75465. if (!axisMesh) {
  75466. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  75467. continue;
  75468. }
  75469. var axisMeshInfo = {
  75470. index: i,
  75471. value: getImmediateChildByName(axisMesh, 'VALUE'),
  75472. min: getImmediateChildByName(axisMesh, 'MIN'),
  75473. max: getImmediateChildByName(axisMesh, 'MAX')
  75474. };
  75475. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  75476. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  75477. }
  75478. else {
  75479. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  75480. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  75481. '(VALUE: ' + !!axisMeshInfo.value +
  75482. ', MIN: ' + !!axisMeshInfo.min +
  75483. ', MAX:' + !!axisMeshInfo.max +
  75484. ')');
  75485. }
  75486. }
  75487. // Pointing Ray
  75488. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  75489. if (!loadedMeshInfo.pointingPoseNode) {
  75490. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  75491. }
  75492. else {
  75493. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  75494. }
  75495. return loadedMeshInfo;
  75496. // Look through all children recursively. This will return null if no mesh exists with the given name.
  75497. function getChildByName(node, name) {
  75498. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  75499. }
  75500. // Look through only immediate children. This will return null if no mesh exists with the given name.
  75501. function getImmediateChildByName(node, name) {
  75502. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  75503. }
  75504. };
  75505. /**
  75506. * Gets the ray of the controller in the direction the controller is pointing
  75507. * @param length the length the resulting ray should be
  75508. * @returns a ray in the direction the controller is pointing
  75509. */
  75510. WindowsMotionController.prototype.getForwardRay = function (length) {
  75511. if (length === void 0) { length = 100; }
  75512. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  75513. return _super.prototype.getForwardRay.call(this, length);
  75514. }
  75515. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  75516. var origin = m.getTranslation();
  75517. var forward = new BABYLON.Vector3(0, 0, -1);
  75518. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75519. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75520. return new BABYLON.Ray(origin, direction, length);
  75521. };
  75522. /**
  75523. * Disposes of the controller
  75524. */
  75525. WindowsMotionController.prototype.dispose = function () {
  75526. _super.prototype.dispose.call(this);
  75527. this.onTrackpadChangedObservable.clear();
  75528. };
  75529. /**
  75530. * The base url used to load the left and right controller models
  75531. */
  75532. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  75533. /**
  75534. * The name of the left controller model file
  75535. */
  75536. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  75537. /**
  75538. * The name of the right controller model file
  75539. */
  75540. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  75541. /**
  75542. * The controller name prefix for this controller type
  75543. */
  75544. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  75545. /**
  75546. * The controller id pattern for this controller type
  75547. */
  75548. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  75549. return WindowsMotionController;
  75550. }(BABYLON.WebVRController));
  75551. BABYLON.WindowsMotionController = WindowsMotionController;
  75552. })(BABYLON || (BABYLON = {}));
  75553. //# sourceMappingURL=babylon.windowsMotionController.js.map
  75554. var BABYLON;
  75555. (function (BABYLON) {
  75556. /**
  75557. * Gear VR Controller
  75558. */
  75559. var GearVRController = /** @class */ (function (_super) {
  75560. __extends(GearVRController, _super);
  75561. /**
  75562. * Creates a new GearVRController from a gamepad
  75563. * @param vrGamepad the gamepad that the controller should be created from
  75564. */
  75565. function GearVRController(vrGamepad) {
  75566. var _this = _super.call(this, vrGamepad) || this;
  75567. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75568. _this._draggedRoomRotation = 0;
  75569. _this._tmpVector = new BABYLON.Vector3();
  75570. _this._buttonIndexToObservableNameMap = [
  75571. 'onTrackpadChangedObservable',
  75572. 'onTriggerStateChangedObservable' // Trigger
  75573. ];
  75574. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75575. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75576. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75577. return _this;
  75578. }
  75579. /**
  75580. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75581. * @param poseData raw pose fromthe device
  75582. */
  75583. GearVRController.prototype.updateFromDevice = function (poseData) {
  75584. _super.prototype.updateFromDevice.call(this, poseData);
  75585. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75586. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75587. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75588. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75589. // Find the radian distance away that the headset is from the controllers rotation
  75590. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75591. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75592. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75593. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75594. this._draggedRoomRotation += rotationAmount;
  75595. // Rotate controller around headset
  75596. var sin = Math.sin(-rotationAmount);
  75597. var cos = Math.cos(-rotationAmount);
  75598. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75599. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75600. }
  75601. }
  75602. }
  75603. };
  75604. /**
  75605. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75606. * @param scene scene in which to add meshes
  75607. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75608. */
  75609. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75610. var _this = this;
  75611. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75612. // Offset the controller so it will rotate around the users wrist
  75613. var mesh = new BABYLON.Mesh("", scene);
  75614. newMeshes[1].parent = mesh;
  75615. newMeshes[1].position.z = -0.15;
  75616. _this._defaultModel = mesh;
  75617. _this.attachToMesh(_this._defaultModel);
  75618. if (meshLoaded) {
  75619. meshLoaded(_this._defaultModel);
  75620. }
  75621. });
  75622. };
  75623. /**
  75624. * Called once for each button that changed state since the last frame
  75625. * @param buttonIdx Which button index changed
  75626. * @param state New state of the button
  75627. * @param changes Which properties on the state changed since last frame
  75628. */
  75629. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75630. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75631. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75632. // Only emit events for buttons that we know how to map from index to observable
  75633. var observable = this[observableName];
  75634. if (observable) {
  75635. observable.notifyObservers(state);
  75636. }
  75637. }
  75638. };
  75639. /**
  75640. * Base Url for the controller model.
  75641. */
  75642. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75643. /**
  75644. * File name for the controller model.
  75645. */
  75646. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75647. /**
  75648. * Gamepad Id prefix used to identify this controller.
  75649. */
  75650. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75651. return GearVRController;
  75652. }(BABYLON.WebVRController));
  75653. BABYLON.GearVRController = GearVRController;
  75654. })(BABYLON || (BABYLON = {}));
  75655. //# sourceMappingURL=babylon.gearVRController.js.map
  75656. var BABYLON;
  75657. (function (BABYLON) {
  75658. /**
  75659. * Google Daydream controller
  75660. */
  75661. var DaydreamController = /** @class */ (function (_super) {
  75662. __extends(DaydreamController, _super);
  75663. /**
  75664. * Creates a new DaydreamController from a gamepad
  75665. * @param vrGamepad the gamepad that the controller should be created from
  75666. */
  75667. function DaydreamController(vrGamepad) {
  75668. var _this = _super.call(this, vrGamepad) || this;
  75669. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75670. return _this;
  75671. }
  75672. /**
  75673. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75674. * @param scene scene in which to add meshes
  75675. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75676. */
  75677. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75678. var _this = this;
  75679. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75680. _this._defaultModel = newMeshes[1];
  75681. _this.attachToMesh(_this._defaultModel);
  75682. if (meshLoaded) {
  75683. meshLoaded(_this._defaultModel);
  75684. }
  75685. });
  75686. };
  75687. /**
  75688. * Called once for each button that changed state since the last frame
  75689. * @param buttonIdx Which button index changed
  75690. * @param state New state of the button
  75691. * @param changes Which properties on the state changed since last frame
  75692. */
  75693. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75694. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75695. if (buttonIdx === 0) {
  75696. var observable = this.onTriggerStateChangedObservable;
  75697. if (observable) {
  75698. observable.notifyObservers(state);
  75699. }
  75700. }
  75701. else {
  75702. // If the app or home buttons are ever made available
  75703. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75704. }
  75705. };
  75706. /**
  75707. * Base Url for the controller model.
  75708. */
  75709. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75710. /**
  75711. * File name for the controller model.
  75712. */
  75713. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75714. /**
  75715. * Gamepad Id prefix used to identify Daydream Controller.
  75716. */
  75717. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75718. return DaydreamController;
  75719. }(BABYLON.WebVRController));
  75720. BABYLON.DaydreamController = DaydreamController;
  75721. })(BABYLON || (BABYLON = {}));
  75722. //# sourceMappingURL=babylon.daydreamController.js.map
  75723. var BABYLON;
  75724. (function (BABYLON) {
  75725. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75726. get: function () {
  75727. if (!this._gamepadManager) {
  75728. this._gamepadManager = new BABYLON.GamepadManager(this);
  75729. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75730. if (!component) {
  75731. component = new GamepadSystemSceneComponent(this);
  75732. this._addComponent(component);
  75733. }
  75734. }
  75735. return this._gamepadManager;
  75736. },
  75737. enumerable: true,
  75738. configurable: true
  75739. });
  75740. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75741. this.add(new BABYLON.FreeCameraGamepadInput());
  75742. return this;
  75743. };
  75744. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75745. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75746. return this;
  75747. };
  75748. /**
  75749. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75750. */
  75751. var GamepadSystemSceneComponent = /** @class */ (function () {
  75752. /**
  75753. * Creates a new instance of the component for the given scene
  75754. * @param scene Defines the scene to register the component in
  75755. */
  75756. function GamepadSystemSceneComponent(scene) {
  75757. /**
  75758. * The component name helpfull to identify the component in the list of scene components.
  75759. */
  75760. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75761. this.scene = scene;
  75762. }
  75763. /**
  75764. * Registers the component in a given scene
  75765. */
  75766. GamepadSystemSceneComponent.prototype.register = function () {
  75767. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75768. };
  75769. /**
  75770. * Rebuilds the elements related to this component in case of
  75771. * context lost for instance.
  75772. */
  75773. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75774. // Nothing to do for gamepads
  75775. };
  75776. /**
  75777. * Disposes the component and the associated ressources
  75778. */
  75779. GamepadSystemSceneComponent.prototype.dispose = function () {
  75780. var gamepadManager = this.scene._gamepadManager;
  75781. if (gamepadManager) {
  75782. gamepadManager.dispose();
  75783. this.scene._gamepadManager = null;
  75784. }
  75785. };
  75786. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75787. var gamepadManager = this.scene._gamepadManager;
  75788. if (gamepadManager && gamepadManager._isMonitoring) {
  75789. gamepadManager._checkGamepadsStatus();
  75790. }
  75791. };
  75792. return GamepadSystemSceneComponent;
  75793. }());
  75794. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75795. })(BABYLON || (BABYLON = {}));
  75796. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75797. var BABYLON;
  75798. (function (BABYLON) {
  75799. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75800. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75801. });
  75802. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75803. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75804. });
  75805. var FollowCamera = /** @class */ (function (_super) {
  75806. __extends(FollowCamera, _super);
  75807. function FollowCamera(name, position, scene, lockedTarget) {
  75808. if (lockedTarget === void 0) { lockedTarget = null; }
  75809. var _this = _super.call(this, name, position, scene) || this;
  75810. _this.radius = 12;
  75811. _this.rotationOffset = 0;
  75812. _this.heightOffset = 4;
  75813. _this.cameraAcceleration = 0.05;
  75814. _this.maxCameraSpeed = 20;
  75815. _this.lockedTarget = lockedTarget;
  75816. return _this;
  75817. }
  75818. FollowCamera.prototype.getRadians = function (degrees) {
  75819. return degrees * Math.PI / 180;
  75820. };
  75821. FollowCamera.prototype.follow = function (cameraTarget) {
  75822. if (!cameraTarget)
  75823. return;
  75824. var yRotation;
  75825. if (cameraTarget.rotationQuaternion) {
  75826. var rotMatrix = new BABYLON.Matrix();
  75827. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75828. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75829. }
  75830. else {
  75831. yRotation = cameraTarget.rotation.y;
  75832. }
  75833. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75834. var targetPosition = cameraTarget.getAbsolutePosition();
  75835. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  75836. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  75837. var dx = targetX - this.position.x;
  75838. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  75839. var dz = (targetZ) - this.position.z;
  75840. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  75841. var vy = dy * this.cameraAcceleration;
  75842. var vz = dz * this.cameraAcceleration * 2;
  75843. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  75844. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75845. }
  75846. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  75847. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75848. }
  75849. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  75850. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75851. }
  75852. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  75853. this.setTarget(targetPosition);
  75854. };
  75855. /** @hidden */
  75856. FollowCamera.prototype._checkInputs = function () {
  75857. _super.prototype._checkInputs.call(this);
  75858. if (this.lockedTarget) {
  75859. this.follow(this.lockedTarget);
  75860. }
  75861. };
  75862. FollowCamera.prototype.getClassName = function () {
  75863. return "FollowCamera";
  75864. };
  75865. __decorate([
  75866. BABYLON.serialize()
  75867. ], FollowCamera.prototype, "radius", void 0);
  75868. __decorate([
  75869. BABYLON.serialize()
  75870. ], FollowCamera.prototype, "rotationOffset", void 0);
  75871. __decorate([
  75872. BABYLON.serialize()
  75873. ], FollowCamera.prototype, "heightOffset", void 0);
  75874. __decorate([
  75875. BABYLON.serialize()
  75876. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  75877. __decorate([
  75878. BABYLON.serialize()
  75879. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  75880. __decorate([
  75881. BABYLON.serializeAsMeshReference("lockedTargetId")
  75882. ], FollowCamera.prototype, "lockedTarget", void 0);
  75883. return FollowCamera;
  75884. }(BABYLON.TargetCamera));
  75885. BABYLON.FollowCamera = FollowCamera;
  75886. var ArcFollowCamera = /** @class */ (function (_super) {
  75887. __extends(ArcFollowCamera, _super);
  75888. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  75889. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  75890. _this.alpha = alpha;
  75891. _this.beta = beta;
  75892. _this.radius = radius;
  75893. _this.target = target;
  75894. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  75895. _this.follow();
  75896. return _this;
  75897. }
  75898. ArcFollowCamera.prototype.follow = function () {
  75899. if (!this.target) {
  75900. return;
  75901. }
  75902. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  75903. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  75904. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  75905. var targetPosition = this.target.getAbsolutePosition();
  75906. this.position = targetPosition.add(this._cartesianCoordinates);
  75907. this.setTarget(targetPosition);
  75908. };
  75909. /** @hidden */
  75910. ArcFollowCamera.prototype._checkInputs = function () {
  75911. _super.prototype._checkInputs.call(this);
  75912. this.follow();
  75913. };
  75914. ArcFollowCamera.prototype.getClassName = function () {
  75915. return "ArcFollowCamera";
  75916. };
  75917. return ArcFollowCamera;
  75918. }(BABYLON.TargetCamera));
  75919. BABYLON.ArcFollowCamera = ArcFollowCamera;
  75920. })(BABYLON || (BABYLON = {}));
  75921. //# sourceMappingURL=babylon.followCamera.js.map
  75922. var BABYLON;
  75923. (function (BABYLON) {
  75924. // We're mainly based on the logic defined into the FreeCamera code
  75925. var UniversalCamera = /** @class */ (function (_super) {
  75926. __extends(UniversalCamera, _super);
  75927. //-- end properties for backward compatibility for inputs
  75928. function UniversalCamera(name, position, scene) {
  75929. var _this = _super.call(this, name, position, scene) || this;
  75930. _this.inputs.addGamepad();
  75931. return _this;
  75932. }
  75933. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  75934. //-- Begin properties for backward compatibility for inputs
  75935. get: function () {
  75936. var gamepad = this.inputs.attached["gamepad"];
  75937. if (gamepad)
  75938. return gamepad.gamepadAngularSensibility;
  75939. return 0;
  75940. },
  75941. set: function (value) {
  75942. var gamepad = this.inputs.attached["gamepad"];
  75943. if (gamepad)
  75944. gamepad.gamepadAngularSensibility = value;
  75945. },
  75946. enumerable: true,
  75947. configurable: true
  75948. });
  75949. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75950. get: function () {
  75951. var gamepad = this.inputs.attached["gamepad"];
  75952. if (gamepad)
  75953. return gamepad.gamepadMoveSensibility;
  75954. return 0;
  75955. },
  75956. set: function (value) {
  75957. var gamepad = this.inputs.attached["gamepad"];
  75958. if (gamepad)
  75959. gamepad.gamepadMoveSensibility = value;
  75960. },
  75961. enumerable: true,
  75962. configurable: true
  75963. });
  75964. UniversalCamera.prototype.getClassName = function () {
  75965. return "UniversalCamera";
  75966. };
  75967. return UniversalCamera;
  75968. }(BABYLON.TouchCamera));
  75969. BABYLON.UniversalCamera = UniversalCamera;
  75970. })(BABYLON || (BABYLON = {}));
  75971. //# sourceMappingURL=babylon.universalCamera.js.map
  75972. var BABYLON;
  75973. (function (BABYLON) {
  75974. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75975. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75976. });
  75977. // We're mainly based on the logic defined into the FreeCamera code
  75978. var GamepadCamera = /** @class */ (function (_super) {
  75979. __extends(GamepadCamera, _super);
  75980. //-- end properties for backward compatibility for inputs
  75981. function GamepadCamera(name, position, scene) {
  75982. return _super.call(this, name, position, scene) || this;
  75983. }
  75984. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  75985. //-- Begin properties for backward compatibility for inputs
  75986. get: function () {
  75987. var gamepad = this.inputs.attached["gamepad"];
  75988. if (gamepad)
  75989. return gamepad.gamepadAngularSensibility;
  75990. return 0;
  75991. },
  75992. set: function (value) {
  75993. var gamepad = this.inputs.attached["gamepad"];
  75994. if (gamepad)
  75995. gamepad.gamepadAngularSensibility = value;
  75996. },
  75997. enumerable: true,
  75998. configurable: true
  75999. });
  76000. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  76001. get: function () {
  76002. var gamepad = this.inputs.attached["gamepad"];
  76003. if (gamepad)
  76004. return gamepad.gamepadMoveSensibility;
  76005. return 0;
  76006. },
  76007. set: function (value) {
  76008. var gamepad = this.inputs.attached["gamepad"];
  76009. if (gamepad)
  76010. gamepad.gamepadMoveSensibility = value;
  76011. },
  76012. enumerable: true,
  76013. configurable: true
  76014. });
  76015. GamepadCamera.prototype.getClassName = function () {
  76016. return "GamepadCamera";
  76017. };
  76018. return GamepadCamera;
  76019. }(BABYLON.UniversalCamera));
  76020. BABYLON.GamepadCamera = GamepadCamera;
  76021. })(BABYLON || (BABYLON = {}));
  76022. //# sourceMappingURL=babylon.gamepadCamera.js.map
  76023. var BABYLON;
  76024. (function (BABYLON) {
  76025. var PostProcessRenderPipelineManager = /** @class */ (function () {
  76026. function PostProcessRenderPipelineManager() {
  76027. this._renderPipelines = {};
  76028. }
  76029. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  76030. this._renderPipelines[renderPipeline._name] = renderPipeline;
  76031. };
  76032. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  76033. if (unique === void 0) { unique = false; }
  76034. var renderPipeline = this._renderPipelines[renderPipelineName];
  76035. if (!renderPipeline) {
  76036. return;
  76037. }
  76038. renderPipeline._attachCameras(cameras, unique);
  76039. };
  76040. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  76041. var renderPipeline = this._renderPipelines[renderPipelineName];
  76042. if (!renderPipeline) {
  76043. return;
  76044. }
  76045. renderPipeline._detachCameras(cameras);
  76046. };
  76047. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76048. var renderPipeline = this._renderPipelines[renderPipelineName];
  76049. if (!renderPipeline) {
  76050. return;
  76051. }
  76052. renderPipeline._enableEffect(renderEffectName, cameras);
  76053. };
  76054. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76055. var renderPipeline = this._renderPipelines[renderPipelineName];
  76056. if (!renderPipeline) {
  76057. return;
  76058. }
  76059. renderPipeline._disableEffect(renderEffectName, cameras);
  76060. };
  76061. PostProcessRenderPipelineManager.prototype.update = function () {
  76062. for (var renderPipelineName in this._renderPipelines) {
  76063. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76064. var pipeline = this._renderPipelines[renderPipelineName];
  76065. if (!pipeline.isSupported) {
  76066. pipeline.dispose();
  76067. delete this._renderPipelines[renderPipelineName];
  76068. }
  76069. else {
  76070. pipeline._update();
  76071. }
  76072. }
  76073. }
  76074. };
  76075. /** @hidden */
  76076. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  76077. for (var renderPipelineName in this._renderPipelines) {
  76078. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76079. var pipeline = this._renderPipelines[renderPipelineName];
  76080. pipeline._rebuild();
  76081. }
  76082. }
  76083. };
  76084. PostProcessRenderPipelineManager.prototype.dispose = function () {
  76085. for (var renderPipelineName in this._renderPipelines) {
  76086. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76087. var pipeline = this._renderPipelines[renderPipelineName];
  76088. pipeline.dispose();
  76089. }
  76090. }
  76091. };
  76092. return PostProcessRenderPipelineManager;
  76093. }());
  76094. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  76095. })(BABYLON || (BABYLON = {}));
  76096. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  76097. var BABYLON;
  76098. (function (BABYLON) {
  76099. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  76100. get: function () {
  76101. if (!this._postProcessRenderPipelineManager) {
  76102. // Register the G Buffer component to the scene.
  76103. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  76104. if (!component) {
  76105. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  76106. this._addComponent(component);
  76107. }
  76108. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  76109. }
  76110. return this._postProcessRenderPipelineManager;
  76111. },
  76112. enumerable: true,
  76113. configurable: true
  76114. });
  76115. /**
  76116. * Defines the Render Pipeline scene component responsible to rendering pipelines
  76117. */
  76118. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  76119. /**
  76120. * Creates a new instance of the component for the given scene
  76121. * @param scene Defines the scene to register the component in
  76122. */
  76123. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  76124. /**
  76125. * The component name helpfull to identify the component in the list of scene components.
  76126. */
  76127. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  76128. this.scene = scene;
  76129. }
  76130. /**
  76131. * Registers the component in a given scene
  76132. */
  76133. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  76134. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  76135. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  76136. };
  76137. /**
  76138. * Rebuilds the elements related to this component in case of
  76139. * context lost for instance.
  76140. */
  76141. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  76142. // Nothing to do for this component
  76143. };
  76144. /**
  76145. * Disposes the component and the associated ressources
  76146. */
  76147. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  76148. if (this.scene._postProcessRenderPipelineManager) {
  76149. this.scene._postProcessRenderPipelineManager.dispose();
  76150. }
  76151. };
  76152. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76153. if (this.scene._postProcessRenderPipelineManager) {
  76154. this.scene._postProcessRenderPipelineManager.update();
  76155. }
  76156. };
  76157. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  76158. if (this.scene._postProcessRenderPipelineManager) {
  76159. this.scene._postProcessRenderPipelineManager._rebuild();
  76160. }
  76161. };
  76162. return PostProcessRenderPipelineManagerSceneComponent;
  76163. }());
  76164. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  76165. })(BABYLON || (BABYLON = {}));
  76166. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  76167. var BABYLON;
  76168. (function (BABYLON) {
  76169. /**
  76170. * This represents a set of one or more post processes in Babylon.
  76171. * A post process can be used to apply a shader to a texture after it is rendered.
  76172. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  76173. */
  76174. var PostProcessRenderEffect = /** @class */ (function () {
  76175. /**
  76176. * Instantiates a post process render effect.
  76177. * A post process can be used to apply a shader to a texture after it is rendered.
  76178. * @param engine The engine the effect is tied to
  76179. * @param name The name of the effect
  76180. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  76181. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  76182. */
  76183. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  76184. this._name = name;
  76185. this._singleInstance = singleInstance || true;
  76186. this._getPostProcesses = getPostProcesses;
  76187. this._cameras = {};
  76188. this._indicesForCamera = {};
  76189. this._postProcesses = {};
  76190. }
  76191. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  76192. /**
  76193. * Checks if all the post processes in the effect are supported.
  76194. */
  76195. get: function () {
  76196. for (var index in this._postProcesses) {
  76197. if (this._postProcesses.hasOwnProperty(index)) {
  76198. var pps = this._postProcesses[index];
  76199. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  76200. if (!pps[ppIndex].isSupported) {
  76201. return false;
  76202. }
  76203. }
  76204. }
  76205. }
  76206. return true;
  76207. },
  76208. enumerable: true,
  76209. configurable: true
  76210. });
  76211. /**
  76212. * Updates the current state of the effect
  76213. * @hidden
  76214. */
  76215. PostProcessRenderEffect.prototype._update = function () {
  76216. };
  76217. /**
  76218. * Attaches the effect on cameras
  76219. * @param cameras The camera to attach to.
  76220. * @hidden
  76221. */
  76222. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  76223. var _this = this;
  76224. var cameraKey;
  76225. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76226. if (!cams) {
  76227. return;
  76228. }
  76229. for (var i = 0; i < cams.length; i++) {
  76230. var camera = cams[i];
  76231. var cameraName = camera.name;
  76232. if (this._singleInstance) {
  76233. cameraKey = 0;
  76234. }
  76235. else {
  76236. cameraKey = cameraName;
  76237. }
  76238. if (!this._postProcesses[cameraKey]) {
  76239. var postProcess = this._getPostProcesses();
  76240. if (postProcess) {
  76241. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  76242. }
  76243. }
  76244. if (!this._indicesForCamera[cameraName]) {
  76245. this._indicesForCamera[cameraName] = [];
  76246. }
  76247. this._postProcesses[cameraKey].forEach(function (postProcess) {
  76248. var index = camera.attachPostProcess(postProcess);
  76249. _this._indicesForCamera[cameraName].push(index);
  76250. });
  76251. if (!this._cameras[cameraName]) {
  76252. this._cameras[cameraName] = camera;
  76253. }
  76254. }
  76255. };
  76256. /**
  76257. * Detatches the effect on cameras
  76258. * @param cameras The camera to detatch from.
  76259. * @hidden
  76260. */
  76261. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  76262. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76263. if (!cams) {
  76264. return;
  76265. }
  76266. for (var i = 0; i < cams.length; i++) {
  76267. var camera = cams[i];
  76268. var cameraName = camera.name;
  76269. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76270. camera.detachPostProcess(postProcess);
  76271. });
  76272. if (this._cameras[cameraName]) {
  76273. //this._indicesForCamera.splice(index, 1);
  76274. this._cameras[cameraName] = null;
  76275. }
  76276. }
  76277. };
  76278. /**
  76279. * Enables the effect on given cameras
  76280. * @param cameras The camera to enable.
  76281. * @hidden
  76282. */
  76283. PostProcessRenderEffect.prototype._enable = function (cameras) {
  76284. var _this = this;
  76285. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76286. if (!cams) {
  76287. return;
  76288. }
  76289. for (var i = 0; i < cams.length; i++) {
  76290. var camera = cams[i];
  76291. var cameraName = camera.name;
  76292. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76293. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76294. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76295. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76296. });
  76297. }
  76298. }
  76299. }
  76300. };
  76301. /**
  76302. * Disables the effect on the given cameras
  76303. * @param cameras The camera to disable.
  76304. * @hidden
  76305. */
  76306. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76307. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76308. if (!cams) {
  76309. return;
  76310. }
  76311. for (var i = 0; i < cams.length; i++) {
  76312. var camera = cams[i];
  76313. var cameraName = camera.name;
  76314. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76315. camera.detachPostProcess(postProcess);
  76316. });
  76317. }
  76318. };
  76319. /**
  76320. * Gets a list of the post processes contained in the effect.
  76321. * @param camera The camera to get the post processes on.
  76322. * @returns The list of the post processes in the effect.
  76323. */
  76324. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76325. if (this._singleInstance) {
  76326. return this._postProcesses[0];
  76327. }
  76328. else {
  76329. if (!camera) {
  76330. return null;
  76331. }
  76332. return this._postProcesses[camera.name];
  76333. }
  76334. };
  76335. return PostProcessRenderEffect;
  76336. }());
  76337. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76338. })(BABYLON || (BABYLON = {}));
  76339. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76340. var BABYLON;
  76341. (function (BABYLON) {
  76342. var PostProcessRenderPipeline = /** @class */ (function () {
  76343. function PostProcessRenderPipeline(engine, name) {
  76344. this.engine = engine;
  76345. this._name = name;
  76346. this._renderEffects = {};
  76347. this._renderEffectsForIsolatedPass = new Array();
  76348. this._cameras = [];
  76349. }
  76350. PostProcessRenderPipeline.prototype.getClassName = function () {
  76351. return "PostProcessRenderPipeline";
  76352. };
  76353. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76354. get: function () {
  76355. for (var renderEffectName in this._renderEffects) {
  76356. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76357. if (!this._renderEffects[renderEffectName].isSupported) {
  76358. return false;
  76359. }
  76360. }
  76361. }
  76362. return true;
  76363. },
  76364. enumerable: true,
  76365. configurable: true
  76366. });
  76367. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76368. this._renderEffects[renderEffect._name] = renderEffect;
  76369. };
  76370. // private
  76371. /** @hidden */
  76372. PostProcessRenderPipeline.prototype._rebuild = function () {
  76373. };
  76374. /** @hidden */
  76375. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  76376. var renderEffects = this._renderEffects[renderEffectName];
  76377. if (!renderEffects) {
  76378. return;
  76379. }
  76380. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76381. };
  76382. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  76383. var renderEffects = this._renderEffects[renderEffectName];
  76384. if (!renderEffects) {
  76385. return;
  76386. }
  76387. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76388. };
  76389. /** @hidden */
  76390. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  76391. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76392. if (!cams) {
  76393. return;
  76394. }
  76395. var indicesToDelete = [];
  76396. var i;
  76397. for (i = 0; i < cams.length; i++) {
  76398. var camera = cams[i];
  76399. var cameraName = camera.name;
  76400. if (this._cameras.indexOf(camera) === -1) {
  76401. this._cameras[cameraName] = camera;
  76402. }
  76403. else if (unique) {
  76404. indicesToDelete.push(i);
  76405. }
  76406. }
  76407. for (i = 0; i < indicesToDelete.length; i++) {
  76408. cameras.splice(indicesToDelete[i], 1);
  76409. }
  76410. for (var renderEffectName in this._renderEffects) {
  76411. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76412. this._renderEffects[renderEffectName]._attachCameras(cams);
  76413. }
  76414. }
  76415. };
  76416. /** @hidden */
  76417. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  76418. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76419. if (!cams) {
  76420. return;
  76421. }
  76422. for (var renderEffectName in this._renderEffects) {
  76423. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76424. this._renderEffects[renderEffectName]._detachCameras(cams);
  76425. }
  76426. }
  76427. for (var i = 0; i < cams.length; i++) {
  76428. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  76429. }
  76430. };
  76431. /** @hidden */
  76432. PostProcessRenderPipeline.prototype._update = function () {
  76433. for (var renderEffectName in this._renderEffects) {
  76434. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76435. this._renderEffects[renderEffectName]._update();
  76436. }
  76437. }
  76438. for (var i = 0; i < this._cameras.length; i++) {
  76439. var cameraName = this._cameras[i].name;
  76440. if (this._renderEffectsForIsolatedPass[cameraName]) {
  76441. this._renderEffectsForIsolatedPass[cameraName]._update();
  76442. }
  76443. }
  76444. };
  76445. /** @hidden */
  76446. PostProcessRenderPipeline.prototype._reset = function () {
  76447. this._renderEffects = {};
  76448. this._renderEffectsForIsolatedPass = new Array();
  76449. };
  76450. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  76451. // 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)
  76452. var effectKeys = Object.keys(this._renderEffects);
  76453. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  76454. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  76455. if (postProcesses) {
  76456. postProcesses[0].samples = sampleCount;
  76457. return true;
  76458. }
  76459. }
  76460. return false;
  76461. };
  76462. PostProcessRenderPipeline.prototype.dispose = function () {
  76463. // Must be implemented by children
  76464. };
  76465. __decorate([
  76466. BABYLON.serialize()
  76467. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  76468. return PostProcessRenderPipeline;
  76469. }());
  76470. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  76471. })(BABYLON || (BABYLON = {}));
  76472. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  76473. var BABYLON;
  76474. (function (BABYLON) {
  76475. /**
  76476. * This represents a depth renderer in Babylon.
  76477. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  76478. */
  76479. var DepthRenderer = /** @class */ (function () {
  76480. /**
  76481. * Instantiates a depth renderer
  76482. * @param scene The scene the renderer belongs to
  76483. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  76484. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  76485. */
  76486. function DepthRenderer(scene, type, camera) {
  76487. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  76488. if (camera === void 0) { camera = null; }
  76489. var _this = this;
  76490. this._scene = scene;
  76491. // Register the G Buffer component to the scene.
  76492. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  76493. if (!component) {
  76494. component = new BABYLON.DepthRendererSceneComponent(scene);
  76495. scene._addComponent(component);
  76496. }
  76497. this._camera = camera;
  76498. var engine = scene.getEngine();
  76499. // Render target
  76500. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  76501. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76502. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76503. this._depthMap.refreshRate = 1;
  76504. this._depthMap.renderParticles = false;
  76505. this._depthMap.renderList = null;
  76506. // Camera to get depth map from to support multiple concurrent cameras
  76507. this._depthMap.activeCamera = this._camera;
  76508. this._depthMap.ignoreCameraViewport = true;
  76509. this._depthMap.useCameraPostProcesses = false;
  76510. // set default depth value to 1.0 (far away)
  76511. this._depthMap.onClearObservable.add(function (engine) {
  76512. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  76513. });
  76514. // Custom render function
  76515. var renderSubMesh = function (subMesh) {
  76516. var mesh = subMesh.getRenderingMesh();
  76517. var scene = _this._scene;
  76518. var engine = scene.getEngine();
  76519. var material = subMesh.getMaterial();
  76520. if (!material) {
  76521. return;
  76522. }
  76523. // Culling and reverse (right handed system)
  76524. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76525. // Managing instances
  76526. var batch = mesh._getInstancesRenderList(subMesh._id);
  76527. if (batch.mustReturn) {
  76528. return;
  76529. }
  76530. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76531. var camera = _this._camera || scene.activeCamera;
  76532. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  76533. engine.enableEffect(_this._effect);
  76534. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76535. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76536. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  76537. // Alpha test
  76538. if (material && material.needAlphaTesting()) {
  76539. var alphaTexture = material.getAlphaTestTexture();
  76540. if (alphaTexture) {
  76541. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76542. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76543. }
  76544. }
  76545. // Bones
  76546. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76547. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76548. }
  76549. // Draw
  76550. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76551. }
  76552. };
  76553. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76554. var index;
  76555. if (depthOnlySubMeshes.length) {
  76556. engine.setColorWrite(false);
  76557. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76558. renderSubMesh(depthOnlySubMeshes.data[index]);
  76559. }
  76560. engine.setColorWrite(true);
  76561. }
  76562. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76563. renderSubMesh(opaqueSubMeshes.data[index]);
  76564. }
  76565. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76566. renderSubMesh(alphaTestSubMeshes.data[index]);
  76567. }
  76568. };
  76569. }
  76570. /**
  76571. * Creates the depth rendering effect and checks if the effect is ready.
  76572. * @param subMesh The submesh to be used to render the depth map of
  76573. * @param useInstances If multiple world instances should be used
  76574. * @returns if the depth renderer is ready to render the depth map
  76575. */
  76576. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  76577. var material = subMesh.getMaterial();
  76578. if (material.disableDepthWrite) {
  76579. return false;
  76580. }
  76581. var defines = [];
  76582. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76583. var mesh = subMesh.getMesh();
  76584. // Alpha test
  76585. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  76586. defines.push("#define ALPHATEST");
  76587. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76588. attribs.push(BABYLON.VertexBuffer.UVKind);
  76589. defines.push("#define UV1");
  76590. }
  76591. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76592. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76593. defines.push("#define UV2");
  76594. }
  76595. }
  76596. // Bones
  76597. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76598. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76599. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76600. if (mesh.numBoneInfluencers > 4) {
  76601. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76602. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76603. }
  76604. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76605. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76606. }
  76607. else {
  76608. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76609. }
  76610. // Instances
  76611. if (useInstances) {
  76612. defines.push("#define INSTANCES");
  76613. attribs.push("world0");
  76614. attribs.push("world1");
  76615. attribs.push("world2");
  76616. attribs.push("world3");
  76617. }
  76618. // Get correct effect
  76619. var join = defines.join("\n");
  76620. if (this._cachedDefines !== join) {
  76621. this._cachedDefines = join;
  76622. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  76623. }
  76624. return this._effect.isReady();
  76625. };
  76626. /**
  76627. * Gets the texture which the depth map will be written to.
  76628. * @returns The depth map texture
  76629. */
  76630. DepthRenderer.prototype.getDepthMap = function () {
  76631. return this._depthMap;
  76632. };
  76633. /**
  76634. * Disposes of the depth renderer.
  76635. */
  76636. DepthRenderer.prototype.dispose = function () {
  76637. this._depthMap.dispose();
  76638. };
  76639. return DepthRenderer;
  76640. }());
  76641. BABYLON.DepthRenderer = DepthRenderer;
  76642. })(BABYLON || (BABYLON = {}));
  76643. //# sourceMappingURL=babylon.depthRenderer.js.map
  76644. var BABYLON;
  76645. (function (BABYLON) {
  76646. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  76647. camera = camera || this.activeCamera;
  76648. if (!camera) {
  76649. throw "No camera available to enable depth renderer";
  76650. }
  76651. if (!this._depthRenderer) {
  76652. this._depthRenderer = {};
  76653. }
  76654. if (!this._depthRenderer[camera.id]) {
  76655. var textureType = 0;
  76656. if (this.getEngine().getCaps().textureHalfFloatRender) {
  76657. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76658. }
  76659. else if (this.getEngine().getCaps().textureFloatRender) {
  76660. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76661. }
  76662. else {
  76663. throw "Depth renderer does not support int texture type";
  76664. }
  76665. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  76666. }
  76667. return this._depthRenderer[camera.id];
  76668. };
  76669. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  76670. camera = camera || this.activeCamera;
  76671. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  76672. return;
  76673. }
  76674. this._depthRenderer[camera.id].dispose();
  76675. delete this._depthRenderer[camera.id];
  76676. };
  76677. /**
  76678. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  76679. * in several rendering techniques.
  76680. */
  76681. var DepthRendererSceneComponent = /** @class */ (function () {
  76682. /**
  76683. * Creates a new instance of the component for the given scene
  76684. * @param scene Defines the scene to register the component in
  76685. */
  76686. function DepthRendererSceneComponent(scene) {
  76687. /**
  76688. * The component name helpfull to identify the component in the list of scene components.
  76689. */
  76690. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  76691. this.scene = scene;
  76692. }
  76693. /**
  76694. * Registers the component in a given scene
  76695. */
  76696. DepthRendererSceneComponent.prototype.register = function () {
  76697. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  76698. };
  76699. /**
  76700. * Rebuilds the elements related to this component in case of
  76701. * context lost for instance.
  76702. */
  76703. DepthRendererSceneComponent.prototype.rebuild = function () {
  76704. // Nothing to do for this component
  76705. };
  76706. /**
  76707. * Disposes the component and the associated ressources
  76708. */
  76709. DepthRendererSceneComponent.prototype.dispose = function () {
  76710. for (var key in this.scene._depthRenderer) {
  76711. this.scene._depthRenderer[key].dispose();
  76712. }
  76713. };
  76714. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76715. if (this.scene._depthRenderer) {
  76716. for (var key in this.scene._depthRenderer) {
  76717. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  76718. }
  76719. }
  76720. };
  76721. return DepthRendererSceneComponent;
  76722. }());
  76723. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  76724. })(BABYLON || (BABYLON = {}));
  76725. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  76726. var BABYLON;
  76727. (function (BABYLON) {
  76728. /**
  76729. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76730. */
  76731. var GeometryBufferRenderer = /** @class */ (function () {
  76732. /**
  76733. * Creates a new G Buffer for the scene
  76734. * @param scene The scene the buffer belongs to
  76735. * @param ratio How big is the buffer related to the main canvas.
  76736. */
  76737. function GeometryBufferRenderer(scene, ratio) {
  76738. if (ratio === void 0) { ratio = 1; }
  76739. this._enablePosition = false;
  76740. this._scene = scene;
  76741. this._ratio = ratio;
  76742. // Register the G Buffer component to the scene.
  76743. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  76744. if (!component) {
  76745. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  76746. scene._addComponent(component);
  76747. }
  76748. // Render target
  76749. this._createRenderTargets();
  76750. }
  76751. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76752. /**
  76753. * Set the render list (meshes to be rendered) used in the G buffer.
  76754. */
  76755. set: function (meshes) {
  76756. this._multiRenderTarget.renderList = meshes;
  76757. },
  76758. enumerable: true,
  76759. configurable: true
  76760. });
  76761. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76762. /**
  76763. * Gets wether or not G buffer are supported by the running hardware.
  76764. * This requires draw buffer supports
  76765. */
  76766. get: function () {
  76767. return this._multiRenderTarget.isSupported;
  76768. },
  76769. enumerable: true,
  76770. configurable: true
  76771. });
  76772. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76773. /**
  76774. * Gets wether or not position are enabled for the G buffer.
  76775. */
  76776. get: function () {
  76777. return this._enablePosition;
  76778. },
  76779. /**
  76780. * Sets wether or not position are enabled for the G buffer.
  76781. */
  76782. set: function (enable) {
  76783. this._enablePosition = enable;
  76784. this.dispose();
  76785. this._createRenderTargets();
  76786. },
  76787. enumerable: true,
  76788. configurable: true
  76789. });
  76790. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76791. /**
  76792. * Gets the scene associated with the buffer.
  76793. */
  76794. get: function () {
  76795. return this._scene;
  76796. },
  76797. enumerable: true,
  76798. configurable: true
  76799. });
  76800. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76801. /**
  76802. * Gets the ratio used by the buffer during its creation.
  76803. * How big is the buffer related to the main canvas.
  76804. */
  76805. get: function () {
  76806. return this._ratio;
  76807. },
  76808. enumerable: true,
  76809. configurable: true
  76810. });
  76811. /**
  76812. * Checks wether everything is ready to render a submesh to the G buffer.
  76813. * @param subMesh the submesh to check readiness for
  76814. * @param useInstances is the mesh drawn using instance or not
  76815. * @returns true if ready otherwise false
  76816. */
  76817. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76818. var material = subMesh.getMaterial();
  76819. if (material && material.disableDepthWrite) {
  76820. return false;
  76821. }
  76822. var defines = [];
  76823. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76824. var mesh = subMesh.getMesh();
  76825. // Alpha test
  76826. if (material && material.needAlphaTesting()) {
  76827. defines.push("#define ALPHATEST");
  76828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76829. attribs.push(BABYLON.VertexBuffer.UVKind);
  76830. defines.push("#define UV1");
  76831. }
  76832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76834. defines.push("#define UV2");
  76835. }
  76836. }
  76837. // Buffers
  76838. if (this._enablePosition) {
  76839. defines.push("#define POSITION");
  76840. }
  76841. // Bones
  76842. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76843. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76844. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76845. if (mesh.numBoneInfluencers > 4) {
  76846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76848. }
  76849. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76850. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76851. }
  76852. else {
  76853. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76854. }
  76855. // Instances
  76856. if (useInstances) {
  76857. defines.push("#define INSTANCES");
  76858. attribs.push("world0");
  76859. attribs.push("world1");
  76860. attribs.push("world2");
  76861. attribs.push("world3");
  76862. }
  76863. // Get correct effect
  76864. var join = defines.join("\n");
  76865. if (this._cachedDefines !== join) {
  76866. this._cachedDefines = join;
  76867. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76868. }
  76869. return this._effect.isReady();
  76870. };
  76871. /**
  76872. * Gets the current underlying G Buffer.
  76873. * @returns the buffer
  76874. */
  76875. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76876. return this._multiRenderTarget;
  76877. };
  76878. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76879. /**
  76880. * Gets the number of samples used to render the buffer (anti aliasing).
  76881. */
  76882. get: function () {
  76883. return this._multiRenderTarget.samples;
  76884. },
  76885. /**
  76886. * Sets the number of samples used to render the buffer (anti aliasing).
  76887. */
  76888. set: function (value) {
  76889. this._multiRenderTarget.samples = value;
  76890. },
  76891. enumerable: true,
  76892. configurable: true
  76893. });
  76894. /**
  76895. * Disposes the renderer and frees up associated resources.
  76896. */
  76897. GeometryBufferRenderer.prototype.dispose = function () {
  76898. this.getGBuffer().dispose();
  76899. };
  76900. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76901. var _this = this;
  76902. var engine = this._scene.getEngine();
  76903. var count = this._enablePosition ? 3 : 2;
  76904. 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 });
  76905. if (!this.isSupported) {
  76906. return;
  76907. }
  76908. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76909. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76910. this._multiRenderTarget.refreshRate = 1;
  76911. this._multiRenderTarget.renderParticles = false;
  76912. this._multiRenderTarget.renderList = null;
  76913. // set default depth value to 1.0 (far away)
  76914. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76915. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76916. });
  76917. // Custom render function
  76918. var renderSubMesh = function (subMesh) {
  76919. var mesh = subMesh.getRenderingMesh();
  76920. var scene = _this._scene;
  76921. var engine = scene.getEngine();
  76922. var material = subMesh.getMaterial();
  76923. if (!material) {
  76924. return;
  76925. }
  76926. // Culling
  76927. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76928. // Managing instances
  76929. var batch = mesh._getInstancesRenderList(subMesh._id);
  76930. if (batch.mustReturn) {
  76931. return;
  76932. }
  76933. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76934. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76935. engine.enableEffect(_this._effect);
  76936. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76937. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76938. _this._effect.setMatrix("view", scene.getViewMatrix());
  76939. // Alpha test
  76940. if (material && material.needAlphaTesting()) {
  76941. var alphaTexture = material.getAlphaTestTexture();
  76942. if (alphaTexture) {
  76943. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76944. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76945. }
  76946. }
  76947. // Bones
  76948. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76949. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76950. }
  76951. // Draw
  76952. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76953. }
  76954. };
  76955. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76956. var index;
  76957. if (depthOnlySubMeshes.length) {
  76958. engine.setColorWrite(false);
  76959. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76960. renderSubMesh(depthOnlySubMeshes.data[index]);
  76961. }
  76962. engine.setColorWrite(true);
  76963. }
  76964. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76965. renderSubMesh(opaqueSubMeshes.data[index]);
  76966. }
  76967. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76968. renderSubMesh(alphaTestSubMeshes.data[index]);
  76969. }
  76970. };
  76971. };
  76972. return GeometryBufferRenderer;
  76973. }());
  76974. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76975. })(BABYLON || (BABYLON = {}));
  76976. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76977. var BABYLON;
  76978. (function (BABYLON) {
  76979. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  76980. get: function () {
  76981. this._geometryBufferRenderer;
  76982. },
  76983. set: function (value) {
  76984. if (value && value.isSupported) {
  76985. this._geometryBufferRenderer = value;
  76986. }
  76987. ;
  76988. },
  76989. enumerable: true,
  76990. configurable: true
  76991. });
  76992. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  76993. if (ratio === void 0) { ratio = 1; }
  76994. if (this._geometryBufferRenderer) {
  76995. return this._geometryBufferRenderer;
  76996. }
  76997. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  76998. if (!this._geometryBufferRenderer.isSupported) {
  76999. this._geometryBufferRenderer = null;
  77000. }
  77001. return this._geometryBufferRenderer;
  77002. };
  77003. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  77004. if (!this._geometryBufferRenderer) {
  77005. return;
  77006. }
  77007. this._geometryBufferRenderer.dispose();
  77008. this._geometryBufferRenderer = null;
  77009. };
  77010. /**
  77011. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  77012. * in several rendering techniques.
  77013. */
  77014. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  77015. /**
  77016. * Creates a new instance of the component for the given scene
  77017. * @param scene Defines the scene to register the component in
  77018. */
  77019. function GeometryBufferRendererSceneComponent(scene) {
  77020. /**
  77021. * The component name helpfull to identify the component in the list of scene components.
  77022. */
  77023. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  77024. this.scene = scene;
  77025. }
  77026. /**
  77027. * Registers the component in a given scene
  77028. */
  77029. GeometryBufferRendererSceneComponent.prototype.register = function () {
  77030. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  77031. };
  77032. /**
  77033. * Rebuilds the elements related to this component in case of
  77034. * context lost for instance.
  77035. */
  77036. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  77037. // Nothing to do for this component
  77038. };
  77039. /**
  77040. * Disposes the component and the associated ressources
  77041. */
  77042. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  77043. // Nothing to do for this component
  77044. };
  77045. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77046. if (this.scene._geometryBufferRenderer) {
  77047. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  77048. }
  77049. };
  77050. return GeometryBufferRendererSceneComponent;
  77051. }());
  77052. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  77053. })(BABYLON || (BABYLON = {}));
  77054. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  77055. var BABYLON;
  77056. (function (BABYLON) {
  77057. var SSAORenderingPipeline = /** @class */ (function (_super) {
  77058. __extends(SSAORenderingPipeline, _super);
  77059. /**
  77060. * @constructor
  77061. * @param {string} name - The rendering pipeline name
  77062. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77063. * @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 }
  77064. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77065. */
  77066. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  77067. var _this = _super.call(this, scene.getEngine(), name) || this;
  77068. // Members
  77069. /**
  77070. * The PassPostProcess id in the pipeline that contains the original scene color
  77071. */
  77072. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77073. /**
  77074. * The SSAO PostProcess id in the pipeline
  77075. */
  77076. _this.SSAORenderEffect = "SSAORenderEffect";
  77077. /**
  77078. * The horizontal blur PostProcess id in the pipeline
  77079. */
  77080. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77081. /**
  77082. * The vertical blur PostProcess id in the pipeline
  77083. */
  77084. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77085. /**
  77086. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77087. */
  77088. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77089. /**
  77090. * The output strength of the SSAO post-process. Default value is 1.0.
  77091. */
  77092. _this.totalStrength = 1.0;
  77093. /**
  77094. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  77095. */
  77096. _this.radius = 0.0001;
  77097. /**
  77098. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  77099. * Must not be equal to fallOff and superior to fallOff.
  77100. * Default value is 0.975
  77101. */
  77102. _this.area = 0.0075;
  77103. /**
  77104. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  77105. * Must not be equal to area and inferior to area.
  77106. * Default value is 0.0
  77107. */
  77108. _this.fallOff = 0.000001;
  77109. /**
  77110. * The base color of the SSAO post-process
  77111. * The final result is "base + ssao" between [0, 1]
  77112. */
  77113. _this.base = 0.5;
  77114. _this._firstUpdate = true;
  77115. _this._scene = scene;
  77116. // Set up assets
  77117. _this._createRandomTexture();
  77118. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77119. var ssaoRatio = ratio.ssaoRatio || ratio;
  77120. var combineRatio = ratio.combineRatio || ratio;
  77121. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77122. _this._createSSAOPostProcess(ssaoRatio);
  77123. _this._createBlurPostProcess(ssaoRatio);
  77124. _this._createSSAOCombinePostProcess(combineRatio);
  77125. // Set up pipeline
  77126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77130. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77131. // Finish
  77132. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77133. if (cameras)
  77134. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77135. return _this;
  77136. }
  77137. // Public Methods
  77138. /**
  77139. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77140. */
  77141. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77142. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77143. for (var i = 0; i < this._scene.cameras.length; i++) {
  77144. var camera = this._scene.cameras[i];
  77145. this._originalColorPostProcess.dispose(camera);
  77146. this._ssaoPostProcess.dispose(camera);
  77147. this._blurHPostProcess.dispose(camera);
  77148. this._blurVPostProcess.dispose(camera);
  77149. this._ssaoCombinePostProcess.dispose(camera);
  77150. }
  77151. this._randomTexture.dispose();
  77152. if (disableDepthRender)
  77153. this._scene.disableDepthRenderer();
  77154. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77155. _super.prototype.dispose.call(this);
  77156. };
  77157. // Private Methods
  77158. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  77159. var _this = this;
  77160. var size = 16;
  77161. 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);
  77162. 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);
  77163. this._blurHPostProcess.onActivateObservable.add(function () {
  77164. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  77165. _this._blurHPostProcess.kernel = size * dw;
  77166. });
  77167. this._blurVPostProcess.onActivateObservable.add(function () {
  77168. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  77169. _this._blurVPostProcess.kernel = size * dw;
  77170. });
  77171. };
  77172. /** @hidden */
  77173. SSAORenderingPipeline.prototype._rebuild = function () {
  77174. this._firstUpdate = true;
  77175. _super.prototype._rebuild.call(this);
  77176. };
  77177. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77178. var _this = this;
  77179. var numSamples = 16;
  77180. var sampleSphere = [
  77181. 0.5381, 0.1856, -0.4319,
  77182. 0.1379, 0.2486, 0.4430,
  77183. 0.3371, 0.5679, -0.0057,
  77184. -0.6999, -0.0451, -0.0019,
  77185. 0.0689, -0.1598, -0.8547,
  77186. 0.0560, 0.0069, -0.1843,
  77187. -0.0146, 0.1402, 0.0762,
  77188. 0.0100, -0.1924, -0.0344,
  77189. -0.3577, -0.5301, -0.4358,
  77190. -0.3169, 0.1063, 0.0158,
  77191. 0.0103, -0.5869, 0.0046,
  77192. -0.0897, -0.4940, 0.3287,
  77193. 0.7119, -0.0154, -0.0918,
  77194. -0.0533, 0.0596, -0.5411,
  77195. 0.0352, -0.0631, 0.5460,
  77196. -0.4776, 0.2847, -0.0271
  77197. ];
  77198. var samplesFactor = 1.0 / numSamples;
  77199. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  77200. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77201. "area", "fallOff", "base", "range", "viewport"
  77202. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77203. this._ssaoPostProcess.onApply = function (effect) {
  77204. if (_this._firstUpdate) {
  77205. effect.setArray3("sampleSphere", sampleSphere);
  77206. effect.setFloat("samplesFactor", samplesFactor);
  77207. effect.setFloat("randTextureTiles", 4.0);
  77208. }
  77209. effect.setFloat("totalStrength", _this.totalStrength);
  77210. effect.setFloat("radius", _this.radius);
  77211. effect.setFloat("area", _this.area);
  77212. effect.setFloat("fallOff", _this.fallOff);
  77213. effect.setFloat("base", _this.base);
  77214. effect.setTexture("textureSampler", _this._depthTexture);
  77215. effect.setTexture("randomSampler", _this._randomTexture);
  77216. };
  77217. };
  77218. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77219. var _this = this;
  77220. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77221. this._ssaoCombinePostProcess.onApply = function (effect) {
  77222. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  77223. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77224. };
  77225. };
  77226. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  77227. var size = 512;
  77228. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77229. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77230. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77231. var context = this._randomTexture.getContext();
  77232. var rand = function (min, max) {
  77233. return Math.random() * (max - min) + min;
  77234. };
  77235. var randVector = BABYLON.Vector3.Zero();
  77236. for (var x = 0; x < size; x++) {
  77237. for (var y = 0; y < size; y++) {
  77238. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  77239. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  77240. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  77241. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77242. context.fillRect(x, y, 1, 1);
  77243. }
  77244. }
  77245. this._randomTexture.update(false);
  77246. };
  77247. __decorate([
  77248. BABYLON.serialize()
  77249. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  77250. __decorate([
  77251. BABYLON.serialize()
  77252. ], SSAORenderingPipeline.prototype, "radius", void 0);
  77253. __decorate([
  77254. BABYLON.serialize()
  77255. ], SSAORenderingPipeline.prototype, "area", void 0);
  77256. __decorate([
  77257. BABYLON.serialize()
  77258. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  77259. __decorate([
  77260. BABYLON.serialize()
  77261. ], SSAORenderingPipeline.prototype, "base", void 0);
  77262. return SSAORenderingPipeline;
  77263. }(BABYLON.PostProcessRenderPipeline));
  77264. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  77265. })(BABYLON || (BABYLON = {}));
  77266. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  77267. var BABYLON;
  77268. (function (BABYLON) {
  77269. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  77270. __extends(SSAO2RenderingPipeline, _super);
  77271. /**
  77272. * @constructor
  77273. * @param {string} name - The rendering pipeline name
  77274. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77275. * @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 }
  77276. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77277. */
  77278. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  77279. var _this = _super.call(this, scene.getEngine(), name) || this;
  77280. // Members
  77281. /**
  77282. * The PassPostProcess id in the pipeline that contains the original scene color
  77283. */
  77284. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77285. /**
  77286. * The SSAO PostProcess id in the pipeline
  77287. */
  77288. _this.SSAORenderEffect = "SSAORenderEffect";
  77289. /**
  77290. * The horizontal blur PostProcess id in the pipeline
  77291. */
  77292. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77293. /**
  77294. * The vertical blur PostProcess id in the pipeline
  77295. */
  77296. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77297. /**
  77298. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77299. */
  77300. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77301. /**
  77302. * The output strength of the SSAO post-process. Default value is 1.0.
  77303. */
  77304. _this.totalStrength = 1.0;
  77305. /**
  77306. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77307. */
  77308. _this.maxZ = 100.0;
  77309. /**
  77310. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77311. */
  77312. _this.minZAspect = 0.2;
  77313. _this._samples = 8;
  77314. _this._textureSamples = 1;
  77315. /**
  77316. * Are we using bilateral blur ?
  77317. */
  77318. _this._expensiveBlur = true;
  77319. /**
  77320. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77321. */
  77322. _this.radius = 2.0;
  77323. /**
  77324. * The base color of the SSAO post-process
  77325. * The final result is "base + ssao" between [0, 1]
  77326. */
  77327. _this.base = 0;
  77328. _this._firstUpdate = true;
  77329. _this._bits = new Uint32Array(1);
  77330. _this._scene = scene;
  77331. _this._ratio = ratio;
  77332. if (!_this.isSupported) {
  77333. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77334. return _this;
  77335. }
  77336. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77337. var blurRatio = _this._ratio.blurRatio || ratio;
  77338. // Set up assets
  77339. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77340. _this._createRandomTexture();
  77341. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77342. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77343. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77344. _this._originalColorPostProcess.samples = _this.textureSamples;
  77345. _this._createSSAOPostProcess(1.0);
  77346. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77347. _this._createSSAOCombinePostProcess(blurRatio);
  77348. // Set up pipeline
  77349. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77350. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77351. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77352. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77353. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77354. // Finish
  77355. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77356. if (cameras)
  77357. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77358. return _this;
  77359. }
  77360. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77361. get: function () {
  77362. return this._samples;
  77363. },
  77364. /**
  77365. * Number of samples used for the SSAO calculations. Default value is 8
  77366. */
  77367. set: function (n) {
  77368. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77369. this._samples = n;
  77370. this._sampleSphere = this._generateHemisphere();
  77371. this._firstUpdate = true;
  77372. },
  77373. enumerable: true,
  77374. configurable: true
  77375. });
  77376. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  77377. get: function () {
  77378. return this._textureSamples;
  77379. },
  77380. /**
  77381. * Number of samples to use for antialiasing
  77382. */
  77383. set: function (n) {
  77384. this._textureSamples = n;
  77385. this._originalColorPostProcess.samples = n;
  77386. this._blurHPostProcess.samples = n;
  77387. this._blurVPostProcess.samples = n;
  77388. this._ssaoPostProcess.samples = n;
  77389. this._ssaoCombinePostProcess.samples = n;
  77390. },
  77391. enumerable: true,
  77392. configurable: true
  77393. });
  77394. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  77395. get: function () {
  77396. return this._expensiveBlur;
  77397. },
  77398. set: function (b) {
  77399. 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"]);
  77400. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  77401. this._expensiveBlur = b;
  77402. this._firstUpdate = true;
  77403. },
  77404. enumerable: true,
  77405. configurable: true
  77406. });
  77407. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  77408. /**
  77409. * Support test.
  77410. */
  77411. get: function () {
  77412. var engine = BABYLON.Engine.LastCreatedEngine;
  77413. if (!engine) {
  77414. return false;
  77415. }
  77416. return engine.getCaps().drawBuffersExtension;
  77417. },
  77418. enumerable: true,
  77419. configurable: true
  77420. });
  77421. // Public Methods
  77422. /**
  77423. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77424. */
  77425. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  77426. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  77427. for (var i = 0; i < this._scene.cameras.length; i++) {
  77428. var camera = this._scene.cameras[i];
  77429. this._originalColorPostProcess.dispose(camera);
  77430. this._ssaoPostProcess.dispose(camera);
  77431. this._blurHPostProcess.dispose(camera);
  77432. this._blurVPostProcess.dispose(camera);
  77433. this._ssaoCombinePostProcess.dispose(camera);
  77434. }
  77435. this._randomTexture.dispose();
  77436. if (disableGeometryBufferRenderer)
  77437. this._scene.disableGeometryBufferRenderer();
  77438. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77439. _super.prototype.dispose.call(this);
  77440. };
  77441. // Private Methods
  77442. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  77443. var _this = this;
  77444. this._samplerOffsets = [];
  77445. var expensive = this.expensiveBlur;
  77446. for (var i = -8; i < 8; i++) {
  77447. this._samplerOffsets.push(i * 2 + 0.5);
  77448. }
  77449. 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");
  77450. this._blurHPostProcess.onApply = function (effect) {
  77451. if (!_this._scene.activeCamera) {
  77452. return;
  77453. }
  77454. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  77455. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77456. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77457. effect.setFloat("radius", _this.radius);
  77458. effect.setTexture("depthSampler", _this._depthTexture);
  77459. if (_this._firstUpdate) {
  77460. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77461. }
  77462. };
  77463. 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");
  77464. this._blurVPostProcess.onApply = function (effect) {
  77465. if (!_this._scene.activeCamera) {
  77466. return;
  77467. }
  77468. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  77469. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77470. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77471. effect.setFloat("radius", _this.radius);
  77472. effect.setTexture("depthSampler", _this._depthTexture);
  77473. if (_this._firstUpdate) {
  77474. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77475. _this._firstUpdate = false;
  77476. }
  77477. };
  77478. this._blurHPostProcess.samples = this.textureSamples;
  77479. this._blurVPostProcess.samples = this.textureSamples;
  77480. };
  77481. /** @hidden */
  77482. SSAO2RenderingPipeline.prototype._rebuild = function () {
  77483. this._firstUpdate = true;
  77484. _super.prototype._rebuild.call(this);
  77485. };
  77486. //Van der Corput radical inverse
  77487. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  77488. this._bits[0] = i;
  77489. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  77490. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  77491. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  77492. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  77493. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  77494. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  77495. };
  77496. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  77497. return [i / n, this._radicalInverse_VdC(i)];
  77498. };
  77499. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  77500. var phi = v * 2.0 * Math.PI;
  77501. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  77502. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  77503. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  77504. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  77505. };
  77506. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  77507. var numSamples = this.samples;
  77508. var result = [];
  77509. var vector;
  77510. var i = 0;
  77511. while (i < numSamples) {
  77512. if (numSamples < 16) {
  77513. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  77514. }
  77515. else {
  77516. var rand = this._hammersley(i, numSamples);
  77517. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  77518. }
  77519. result.push(vector.x, vector.y, vector.z);
  77520. i++;
  77521. }
  77522. return result;
  77523. };
  77524. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77525. var _this = this;
  77526. var numSamples = this.samples;
  77527. this._sampleSphere = this._generateHemisphere();
  77528. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  77529. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77530. "base", "range", "projection", "near", "far", "texelSize",
  77531. "xViewport", "yViewport", "maxZ", "minZAspect"
  77532. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77533. this._ssaoPostProcess.onApply = function (effect) {
  77534. if (_this._firstUpdate) {
  77535. effect.setArray3("sampleSphere", _this._sampleSphere);
  77536. effect.setFloat("randTextureTiles", 32.0);
  77537. }
  77538. if (!_this._scene.activeCamera) {
  77539. return;
  77540. }
  77541. effect.setFloat("samplesFactor", 1 / _this.samples);
  77542. effect.setFloat("totalStrength", _this.totalStrength);
  77543. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  77544. effect.setFloat("radius", _this.radius);
  77545. effect.setFloat("maxZ", _this.maxZ);
  77546. effect.setFloat("minZAspect", _this.minZAspect);
  77547. effect.setFloat("base", _this.base);
  77548. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77549. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77550. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  77551. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  77552. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  77553. effect.setTexture("textureSampler", _this._depthTexture);
  77554. effect.setTexture("normalSampler", _this._normalTexture);
  77555. effect.setTexture("randomSampler", _this._randomTexture);
  77556. };
  77557. this._ssaoPostProcess.samples = this.textureSamples;
  77558. };
  77559. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77560. var _this = this;
  77561. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77562. this._ssaoCombinePostProcess.onApply = function (effect) {
  77563. var viewport = _this._scene.activeCamera.viewport;
  77564. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  77565. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77566. };
  77567. this._ssaoCombinePostProcess.samples = this.textureSamples;
  77568. };
  77569. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  77570. var size = 128;
  77571. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77572. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77573. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77574. var context = this._randomTexture.getContext();
  77575. var rand = function (min, max) {
  77576. return Math.random() * (max - min) + min;
  77577. };
  77578. var randVector = BABYLON.Vector3.Zero();
  77579. for (var x = 0; x < size; x++) {
  77580. for (var y = 0; y < size; y++) {
  77581. randVector.x = rand(0.0, 1.0);
  77582. randVector.y = rand(0.0, 1.0);
  77583. randVector.z = 0.0;
  77584. randVector.normalize();
  77585. randVector.scaleInPlace(255);
  77586. randVector.x = Math.floor(randVector.x);
  77587. randVector.y = Math.floor(randVector.y);
  77588. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77589. context.fillRect(x, y, 1, 1);
  77590. }
  77591. }
  77592. this._randomTexture.update(false);
  77593. };
  77594. /**
  77595. * Serialize the rendering pipeline (Used when exporting)
  77596. * @returns the serialized object
  77597. */
  77598. SSAO2RenderingPipeline.prototype.serialize = function () {
  77599. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77600. serializationObject.customType = "SSAO2RenderingPipeline";
  77601. return serializationObject;
  77602. };
  77603. /**
  77604. * Parse the serialized pipeline
  77605. * @param source Source pipeline.
  77606. * @param scene The scene to load the pipeline to.
  77607. * @param rootUrl The URL of the serialized pipeline.
  77608. * @returns An instantiated pipeline from the serialized object.
  77609. */
  77610. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  77611. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77612. };
  77613. __decorate([
  77614. BABYLON.serialize()
  77615. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  77616. __decorate([
  77617. BABYLON.serialize()
  77618. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  77619. __decorate([
  77620. BABYLON.serialize()
  77621. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  77622. __decorate([
  77623. BABYLON.serialize("samples")
  77624. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  77625. __decorate([
  77626. BABYLON.serialize("textureSamples")
  77627. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  77628. __decorate([
  77629. BABYLON.serialize()
  77630. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  77631. __decorate([
  77632. BABYLON.serialize("expensiveBlur")
  77633. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  77634. __decorate([
  77635. BABYLON.serialize()
  77636. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  77637. __decorate([
  77638. BABYLON.serialize()
  77639. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  77640. return SSAO2RenderingPipeline;
  77641. }(BABYLON.PostProcessRenderPipeline));
  77642. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  77643. })(BABYLON || (BABYLON = {}));
  77644. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  77645. // BABYLON.JS Chromatic Aberration GLSL Shader
  77646. // Author: Olivier Guyot
  77647. // Separates very slightly R, G and B colors on the edges of the screen
  77648. // Inspired by Francois Tarlier & Martins Upitis
  77649. var BABYLON;
  77650. (function (BABYLON) {
  77651. var LensRenderingPipeline = /** @class */ (function (_super) {
  77652. __extends(LensRenderingPipeline, _super);
  77653. /**
  77654. * @constructor
  77655. *
  77656. * Effect parameters are as follow:
  77657. * {
  77658. * chromatic_aberration: number; // from 0 to x (1 for realism)
  77659. * edge_blur: number; // from 0 to x (1 for realism)
  77660. * distortion: number; // from 0 to x (1 for realism)
  77661. * grain_amount: number; // from 0 to 1
  77662. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  77663. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  77664. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  77665. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  77666. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  77667. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  77668. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  77669. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  77670. * }
  77671. * Note: if an effect parameter is unset, effect is disabled
  77672. *
  77673. * @param {string} name - The rendering pipeline name
  77674. * @param {object} parameters - An object containing all parameters (see above)
  77675. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77676. * @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)
  77677. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77678. */
  77679. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  77680. if (ratio === void 0) { ratio = 1.0; }
  77681. var _this = _super.call(this, scene.getEngine(), name) || this;
  77682. // Lens effects can be of the following:
  77683. // - chromatic aberration (slight shift of RGB colors)
  77684. // - blur on the edge of the lens
  77685. // - lens distortion
  77686. // - depth-of-field blur & highlights enhancing
  77687. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  77688. // - grain effect (noise or custom texture)
  77689. // Two additional texture samplers are needed:
  77690. // - depth map (for depth-of-field)
  77691. // - grain texture
  77692. /**
  77693. * The chromatic aberration PostProcess id in the pipeline
  77694. */
  77695. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  77696. /**
  77697. * The highlights enhancing PostProcess id in the pipeline
  77698. */
  77699. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  77700. /**
  77701. * The depth-of-field PostProcess id in the pipeline
  77702. */
  77703. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  77704. _this._scene = scene;
  77705. // Fetch texture samplers
  77706. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77707. if (parameters.grain_texture) {
  77708. _this._grainTexture = parameters.grain_texture;
  77709. }
  77710. else {
  77711. _this._createGrainTexture();
  77712. }
  77713. // save parameters
  77714. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  77715. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  77716. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  77717. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  77718. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  77719. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  77720. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  77721. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  77722. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  77723. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  77724. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  77725. // Create effects
  77726. _this._createChromaticAberrationPostProcess(ratio);
  77727. _this._createHighlightsPostProcess(ratio);
  77728. _this._createDepthOfFieldPostProcess(ratio / 4);
  77729. // Set up pipeline
  77730. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  77731. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  77732. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  77733. if (_this._highlightsGain === -1) {
  77734. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  77735. }
  77736. // Finish
  77737. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77738. if (cameras) {
  77739. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77740. }
  77741. return _this;
  77742. }
  77743. // public methods (self explanatory)
  77744. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  77745. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  77746. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  77747. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  77748. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  77749. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  77750. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  77751. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  77752. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  77753. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  77754. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  77755. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  77756. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  77757. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  77758. };
  77759. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  77760. this._highlightsPostProcess.updateEffect();
  77761. };
  77762. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  77763. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  77764. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  77765. this._highlightsGain = amount;
  77766. };
  77767. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  77768. if (this._highlightsGain === -1) {
  77769. this._highlightsGain = 1.0;
  77770. }
  77771. this._highlightsThreshold = amount;
  77772. };
  77773. LensRenderingPipeline.prototype.disableHighlights = function () {
  77774. this._highlightsGain = -1;
  77775. };
  77776. /**
  77777. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  77778. */
  77779. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77780. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77781. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77782. this._chromaticAberrationPostProcess = null;
  77783. this._highlightsPostProcess = null;
  77784. this._depthOfFieldPostProcess = null;
  77785. this._grainTexture.dispose();
  77786. if (disableDepthRender)
  77787. this._scene.disableDepthRenderer();
  77788. };
  77789. // colors shifting and distortion
  77790. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  77791. var _this = this;
  77792. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  77793. [], // samplers
  77794. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77795. this._chromaticAberrationPostProcess.onApply = function (effect) {
  77796. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  77797. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77798. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77799. effect.setFloat('radialIntensity', 1);
  77800. effect.setFloat2('direction', 17, 17);
  77801. effect.setFloat2('centerPosition', 0.5, 0.5);
  77802. };
  77803. };
  77804. // highlights enhancing
  77805. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  77806. var _this = this;
  77807. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  77808. [], // samplers
  77809. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  77810. this._highlightsPostProcess.onApply = function (effect) {
  77811. effect.setFloat('gain', _this._highlightsGain);
  77812. effect.setFloat('threshold', _this._highlightsThreshold);
  77813. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  77814. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77815. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77816. };
  77817. };
  77818. // colors shifting and distortion
  77819. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  77820. var _this = this;
  77821. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  77822. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  77823. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  77824. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77825. this._depthOfFieldPostProcess.onApply = function (effect) {
  77826. effect.setTexture("depthSampler", _this._depthTexture);
  77827. effect.setTexture("grainSampler", _this._grainTexture);
  77828. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  77829. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  77830. effect.setFloat('grain_amount', _this._grainAmount);
  77831. effect.setBool('blur_noise', _this._blurNoise);
  77832. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77833. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77834. effect.setFloat('distortion', _this._distortion);
  77835. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  77836. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  77837. effect.setFloat('aperture', _this._dofAperture);
  77838. effect.setFloat('darken', _this._dofDarken);
  77839. effect.setFloat('edge_blur', _this._edgeBlur);
  77840. effect.setBool('highlights', (_this._highlightsGain !== -1));
  77841. if (_this._scene.activeCamera) {
  77842. effect.setFloat('near', _this._scene.activeCamera.minZ);
  77843. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  77844. }
  77845. };
  77846. };
  77847. // creates a black and white random noise texture, 512x512
  77848. LensRenderingPipeline.prototype._createGrainTexture = function () {
  77849. var size = 512;
  77850. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77851. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77852. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77853. var context = this._grainTexture.getContext();
  77854. var rand = function (min, max) {
  77855. return Math.random() * (max - min) + min;
  77856. };
  77857. var value;
  77858. for (var x = 0; x < size; x++) {
  77859. for (var y = 0; y < size; y++) {
  77860. value = Math.floor(rand(0.42, 0.58) * 255);
  77861. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  77862. context.fillRect(x, y, 1, 1);
  77863. }
  77864. }
  77865. this._grainTexture.update(false);
  77866. };
  77867. return LensRenderingPipeline;
  77868. }(BABYLON.PostProcessRenderPipeline));
  77869. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  77870. })(BABYLON || (BABYLON = {}));
  77871. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  77872. var BABYLON;
  77873. (function (BABYLON) {
  77874. var StandardRenderingPipeline = /** @class */ (function (_super) {
  77875. __extends(StandardRenderingPipeline, _super);
  77876. /**
  77877. * @constructor
  77878. * @param {string} name - The rendering pipeline name
  77879. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77880. * @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)
  77881. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  77882. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77883. */
  77884. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  77885. if (originalPostProcess === void 0) { originalPostProcess = null; }
  77886. var _this = _super.call(this, scene.getEngine(), name) || this;
  77887. _this.downSampleX4PostProcess = null;
  77888. _this.brightPassPostProcess = null;
  77889. _this.blurHPostProcesses = [];
  77890. _this.blurVPostProcesses = [];
  77891. _this.textureAdderPostProcess = null;
  77892. _this.volumetricLightPostProcess = null;
  77893. _this.volumetricLightSmoothXPostProcess = null;
  77894. _this.volumetricLightSmoothYPostProcess = null;
  77895. _this.volumetricLightMergePostProces = null;
  77896. _this.volumetricLightFinalPostProcess = null;
  77897. _this.luminancePostProcess = null;
  77898. _this.luminanceDownSamplePostProcesses = [];
  77899. _this.hdrPostProcess = null;
  77900. _this.textureAdderFinalPostProcess = null;
  77901. _this.lensFlareFinalPostProcess = null;
  77902. _this.hdrFinalPostProcess = null;
  77903. _this.lensFlarePostProcess = null;
  77904. _this.lensFlareComposePostProcess = null;
  77905. _this.motionBlurPostProcess = null;
  77906. _this.depthOfFieldPostProcess = null;
  77907. // Values
  77908. _this.brightThreshold = 1.0;
  77909. _this.blurWidth = 512.0;
  77910. _this.horizontalBlur = false;
  77911. _this.exposure = 1.0;
  77912. _this.lensTexture = null;
  77913. _this.volumetricLightCoefficient = 0.2;
  77914. _this.volumetricLightPower = 4.0;
  77915. _this.volumetricLightBlurScale = 64.0;
  77916. _this.sourceLight = null;
  77917. _this.hdrMinimumLuminance = 1.0;
  77918. _this.hdrDecreaseRate = 0.5;
  77919. _this.hdrIncreaseRate = 0.5;
  77920. _this.lensColorTexture = null;
  77921. _this.lensFlareStrength = 20.0;
  77922. _this.lensFlareGhostDispersal = 1.4;
  77923. _this.lensFlareHaloWidth = 0.7;
  77924. _this.lensFlareDistortionStrength = 16.0;
  77925. _this.lensStarTexture = null;
  77926. _this.lensFlareDirtTexture = null;
  77927. _this.depthOfFieldDistance = 10.0;
  77928. _this.depthOfFieldBlurWidth = 64.0;
  77929. _this.motionStrength = 1.0;
  77930. // IAnimatable
  77931. _this.animations = [];
  77932. _this._currentDepthOfFieldSource = null;
  77933. _this._hdrCurrentLuminance = 1.0;
  77934. // Getters and setters
  77935. _this._bloomEnabled = true;
  77936. _this._depthOfFieldEnabled = false;
  77937. _this._vlsEnabled = false;
  77938. _this._lensFlareEnabled = false;
  77939. _this._hdrEnabled = false;
  77940. _this._motionBlurEnabled = false;
  77941. _this._motionBlurSamples = 64.0;
  77942. _this._volumetricLightStepsCount = 50.0;
  77943. _this._cameras = cameras || [];
  77944. // Initialize
  77945. _this._scene = scene;
  77946. _this._basePostProcess = originalPostProcess;
  77947. _this._ratio = ratio;
  77948. // Misc
  77949. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77950. // Finish
  77951. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77952. _this._buildPipeline();
  77953. return _this;
  77954. }
  77955. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  77956. get: function () {
  77957. return this._bloomEnabled;
  77958. },
  77959. set: function (enabled) {
  77960. if (this._bloomEnabled === enabled) {
  77961. return;
  77962. }
  77963. this._bloomEnabled = enabled;
  77964. this._buildPipeline();
  77965. },
  77966. enumerable: true,
  77967. configurable: true
  77968. });
  77969. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  77970. get: function () {
  77971. return this._depthOfFieldEnabled;
  77972. },
  77973. set: function (enabled) {
  77974. if (this._depthOfFieldEnabled === enabled) {
  77975. return;
  77976. }
  77977. this._depthOfFieldEnabled = enabled;
  77978. this._buildPipeline();
  77979. },
  77980. enumerable: true,
  77981. configurable: true
  77982. });
  77983. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  77984. get: function () {
  77985. return this._lensFlareEnabled;
  77986. },
  77987. set: function (enabled) {
  77988. if (this._lensFlareEnabled === enabled) {
  77989. return;
  77990. }
  77991. this._lensFlareEnabled = enabled;
  77992. this._buildPipeline();
  77993. },
  77994. enumerable: true,
  77995. configurable: true
  77996. });
  77997. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  77998. get: function () {
  77999. return this._hdrEnabled;
  78000. },
  78001. set: function (enabled) {
  78002. if (this._hdrEnabled === enabled) {
  78003. return;
  78004. }
  78005. this._hdrEnabled = enabled;
  78006. this._buildPipeline();
  78007. },
  78008. enumerable: true,
  78009. configurable: true
  78010. });
  78011. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  78012. get: function () {
  78013. return this._vlsEnabled;
  78014. },
  78015. set: function (enabled) {
  78016. if (this._vlsEnabled === enabled) {
  78017. return;
  78018. }
  78019. if (enabled) {
  78020. var geometry = this._scene.enableGeometryBufferRenderer();
  78021. if (!geometry) {
  78022. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  78023. return;
  78024. }
  78025. }
  78026. this._vlsEnabled = enabled;
  78027. this._buildPipeline();
  78028. },
  78029. enumerable: true,
  78030. configurable: true
  78031. });
  78032. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  78033. get: function () {
  78034. return this._motionBlurEnabled;
  78035. },
  78036. set: function (enabled) {
  78037. if (this._motionBlurEnabled === enabled) {
  78038. return;
  78039. }
  78040. this._motionBlurEnabled = enabled;
  78041. this._buildPipeline();
  78042. },
  78043. enumerable: true,
  78044. configurable: true
  78045. });
  78046. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  78047. get: function () {
  78048. return this._volumetricLightStepsCount;
  78049. },
  78050. set: function (count) {
  78051. if (this.volumetricLightPostProcess) {
  78052. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  78053. }
  78054. this._volumetricLightStepsCount = count;
  78055. },
  78056. enumerable: true,
  78057. configurable: true
  78058. });
  78059. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  78060. get: function () {
  78061. return this._motionBlurSamples;
  78062. },
  78063. set: function (samples) {
  78064. if (this.motionBlurPostProcess) {
  78065. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  78066. }
  78067. this._motionBlurSamples = samples;
  78068. },
  78069. enumerable: true,
  78070. configurable: true
  78071. });
  78072. StandardRenderingPipeline.prototype._buildPipeline = function () {
  78073. var _this = this;
  78074. var ratio = this._ratio;
  78075. var scene = this._scene;
  78076. this._disposePostProcesses();
  78077. this._reset();
  78078. // Create pass post-process
  78079. if (!this._basePostProcess) {
  78080. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  78081. this.originalPostProcess.onApply = function (effect) {
  78082. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  78083. };
  78084. }
  78085. else {
  78086. this.originalPostProcess = this._basePostProcess;
  78087. }
  78088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  78089. this._currentDepthOfFieldSource = this.originalPostProcess;
  78090. if (this._bloomEnabled) {
  78091. // Create down sample X4 post-process
  78092. this._createDownSampleX4PostProcess(scene, ratio / 2);
  78093. // Create bright pass post-process
  78094. this._createBrightPassPostProcess(scene, ratio / 2);
  78095. // Create gaussian blur post-processes (down sampling blurs)
  78096. this._createBlurPostProcesses(scene, ratio / 4, 1);
  78097. // Create texture adder post-process
  78098. this._createTextureAdderPostProcess(scene, ratio);
  78099. // Create depth-of-field source post-process
  78100. 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);
  78101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  78102. }
  78103. if (this._vlsEnabled) {
  78104. // Create volumetric light
  78105. this._createVolumetricLightPostProcess(scene, ratio);
  78106. // Create volumetric light final post-process
  78107. 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);
  78108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  78109. }
  78110. if (this._lensFlareEnabled) {
  78111. // Create lens flare post-process
  78112. this._createLensFlarePostProcess(scene, ratio);
  78113. // Create depth-of-field source post-process post lens-flare and disable it now
  78114. 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);
  78115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  78116. }
  78117. if (this._hdrEnabled) {
  78118. // Create luminance
  78119. this._createLuminancePostProcesses(scene, this._floatTextureType);
  78120. // Create HDR
  78121. this._createHdrPostProcess(scene, ratio);
  78122. // Create depth-of-field source post-process post hdr and disable it now
  78123. 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);
  78124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  78125. }
  78126. if (this._depthOfFieldEnabled) {
  78127. // Create gaussian blur used by depth-of-field
  78128. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  78129. // Create depth-of-field post-process
  78130. this._createDepthOfFieldPostProcess(scene, ratio);
  78131. }
  78132. if (this._motionBlurEnabled) {
  78133. // Create motion blur post-process
  78134. this._createMotionBlurPostProcess(scene, ratio);
  78135. }
  78136. if (this._cameras !== null) {
  78137. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78138. }
  78139. };
  78140. // Down Sample X4 Post-Processs
  78141. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  78142. var _this = this;
  78143. var downSampleX4Offsets = new Array(32);
  78144. 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);
  78145. this.downSampleX4PostProcess.onApply = function (effect) {
  78146. var id = 0;
  78147. var width = _this.downSampleX4PostProcess.width;
  78148. var height = _this.downSampleX4PostProcess.height;
  78149. for (var i = -2; i < 2; i++) {
  78150. for (var j = -2; j < 2; j++) {
  78151. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  78152. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  78153. id += 2;
  78154. }
  78155. }
  78156. effect.setArray2("dsOffsets", downSampleX4Offsets);
  78157. };
  78158. // Add to pipeline
  78159. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  78160. };
  78161. // Brightpass Post-Process
  78162. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  78163. var _this = this;
  78164. var brightOffsets = new Array(8);
  78165. 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);
  78166. this.brightPassPostProcess.onApply = function (effect) {
  78167. var sU = (1.0 / _this.brightPassPostProcess.width);
  78168. var sV = (1.0 / _this.brightPassPostProcess.height);
  78169. brightOffsets[0] = -0.5 * sU;
  78170. brightOffsets[1] = 0.5 * sV;
  78171. brightOffsets[2] = 0.5 * sU;
  78172. brightOffsets[3] = 0.5 * sV;
  78173. brightOffsets[4] = -0.5 * sU;
  78174. brightOffsets[5] = -0.5 * sV;
  78175. brightOffsets[6] = 0.5 * sU;
  78176. brightOffsets[7] = -0.5 * sV;
  78177. effect.setArray2("dsOffsets", brightOffsets);
  78178. effect.setFloat("brightThreshold", _this.brightThreshold);
  78179. };
  78180. // Add to pipeline
  78181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  78182. };
  78183. // Create blur H&V post-processes
  78184. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  78185. var _this = this;
  78186. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  78187. var engine = scene.getEngine();
  78188. 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);
  78189. 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);
  78190. blurX.onActivateObservable.add(function () {
  78191. var dw = blurX.width / engine.getRenderWidth();
  78192. blurX.kernel = _this[blurWidthKey] * dw;
  78193. });
  78194. blurY.onActivateObservable.add(function () {
  78195. var dw = blurY.height / engine.getRenderHeight();
  78196. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  78197. });
  78198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  78199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  78200. this.blurHPostProcesses.push(blurX);
  78201. this.blurVPostProcesses.push(blurY);
  78202. };
  78203. // Create texture adder post-process
  78204. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  78205. var _this = this;
  78206. 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);
  78207. this.textureAdderPostProcess.onApply = function (effect) {
  78208. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  78209. effect.setTexture("lensSampler", _this.lensTexture);
  78210. effect.setFloat("exposure", _this.exposure);
  78211. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  78212. };
  78213. // Add to pipeline
  78214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  78215. };
  78216. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  78217. var _this = this;
  78218. var geometryRenderer = scene.enableGeometryBufferRenderer();
  78219. geometryRenderer.enablePosition = true;
  78220. var geometry = geometryRenderer.getGBuffer();
  78221. // Base post-process
  78222. 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));
  78223. var depthValues = BABYLON.Vector2.Zero();
  78224. this.volumetricLightPostProcess.onApply = function (effect) {
  78225. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  78226. var generator = _this.sourceLight.getShadowGenerator();
  78227. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  78228. effect.setTexture("positionSampler", geometry.textures[2]);
  78229. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  78230. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  78231. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  78232. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  78233. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  78234. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  78235. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  78236. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  78237. effect.setVector2("depthValues", depthValues);
  78238. }
  78239. };
  78240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  78241. // Smooth
  78242. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  78243. // Merge
  78244. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  78245. this.volumetricLightMergePostProces.onApply = function (effect) {
  78246. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  78247. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  78248. };
  78249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  78250. };
  78251. // Create luminance
  78252. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  78253. var _this = this;
  78254. // Create luminance
  78255. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  78256. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  78257. var offsets = [];
  78258. this.luminancePostProcess.onApply = function (effect) {
  78259. var sU = (1.0 / _this.luminancePostProcess.width);
  78260. var sV = (1.0 / _this.luminancePostProcess.height);
  78261. offsets[0] = -0.5 * sU;
  78262. offsets[1] = 0.5 * sV;
  78263. offsets[2] = 0.5 * sU;
  78264. offsets[3] = 0.5 * sV;
  78265. offsets[4] = -0.5 * sU;
  78266. offsets[5] = -0.5 * sV;
  78267. offsets[6] = 0.5 * sU;
  78268. offsets[7] = -0.5 * sV;
  78269. effect.setArray2("lumOffsets", offsets);
  78270. };
  78271. // Add to pipeline
  78272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  78273. // Create down sample luminance
  78274. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  78275. var size = Math.pow(3, i);
  78276. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  78277. if (i === 0) {
  78278. defines += "#define FINAL_DOWN_SAMPLER";
  78279. }
  78280. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  78281. this.luminanceDownSamplePostProcesses.push(postProcess);
  78282. }
  78283. // Create callbacks and add effects
  78284. var lastLuminance = this.luminancePostProcess;
  78285. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  78286. var downSampleOffsets = new Array(18);
  78287. pp.onApply = function (effect) {
  78288. if (!lastLuminance) {
  78289. return;
  78290. }
  78291. var id = 0;
  78292. for (var x = -1; x < 2; x++) {
  78293. for (var y = -1; y < 2; y++) {
  78294. downSampleOffsets[id] = x / lastLuminance.width;
  78295. downSampleOffsets[id + 1] = y / lastLuminance.height;
  78296. id += 2;
  78297. }
  78298. }
  78299. effect.setArray2("dsOffsets", downSampleOffsets);
  78300. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  78301. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78302. lastLuminance = _this.luminancePostProcess;
  78303. }
  78304. else {
  78305. lastLuminance = pp;
  78306. }
  78307. };
  78308. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78309. pp.onAfterRender = function (effect) {
  78310. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  78311. 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);
  78312. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  78313. };
  78314. }
  78315. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  78316. });
  78317. };
  78318. // Create HDR post-process
  78319. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  78320. var _this = this;
  78321. 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);
  78322. var outputLiminance = 1;
  78323. var time = 0;
  78324. var lastTime = 0;
  78325. this.hdrPostProcess.onApply = function (effect) {
  78326. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  78327. time += scene.getEngine().getDeltaTime();
  78328. if (outputLiminance < 0) {
  78329. outputLiminance = _this._hdrCurrentLuminance;
  78330. }
  78331. else {
  78332. var dt = (lastTime - time) / 1000.0;
  78333. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  78334. outputLiminance += _this.hdrDecreaseRate * dt;
  78335. }
  78336. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  78337. outputLiminance -= _this.hdrIncreaseRate * dt;
  78338. }
  78339. else {
  78340. outputLiminance = _this._hdrCurrentLuminance;
  78341. }
  78342. }
  78343. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  78344. effect.setFloat("averageLuminance", outputLiminance);
  78345. lastTime = time;
  78346. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  78347. };
  78348. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  78349. };
  78350. // Create lens flare post-process
  78351. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  78352. var _this = this;
  78353. 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);
  78354. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  78355. this._createBlurPostProcesses(scene, ratio / 4, 2);
  78356. 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);
  78357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  78358. var resolution = new BABYLON.Vector2(0, 0);
  78359. // Lens flare
  78360. this.lensFlarePostProcess.onApply = function (effect) {
  78361. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  78362. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  78363. effect.setFloat("strength", _this.lensFlareStrength);
  78364. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  78365. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  78366. // Shift
  78367. resolution.x = _this.lensFlarePostProcess.width;
  78368. resolution.y = _this.lensFlarePostProcess.height;
  78369. effect.setVector2("resolution", resolution);
  78370. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  78371. };
  78372. // Compose
  78373. 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);
  78374. 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);
  78375. this.lensFlareComposePostProcess.onApply = function (effect) {
  78376. if (!_this._scene.activeCamera) {
  78377. return;
  78378. }
  78379. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78380. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  78381. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  78382. // Lens start rotation matrix
  78383. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  78384. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  78385. 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));
  78386. camRot *= 4.0;
  78387. 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);
  78388. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  78389. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  78390. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  78391. };
  78392. };
  78393. // Create depth-of-field post-process
  78394. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  78395. var _this = this;
  78396. 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);
  78397. this.depthOfFieldPostProcess.onApply = function (effect) {
  78398. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78399. effect.setTexture("depthSampler", _this._getDepthTexture());
  78400. effect.setFloat("distance", _this.depthOfFieldDistance);
  78401. };
  78402. // Add to pipeline
  78403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  78404. };
  78405. // Create motion blur post-process
  78406. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  78407. var _this = this;
  78408. 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);
  78409. var motionScale = 0;
  78410. var prevViewProjection = BABYLON.Matrix.Identity();
  78411. var invViewProjection = BABYLON.Matrix.Identity();
  78412. var viewProjection = BABYLON.Matrix.Identity();
  78413. var screenSize = BABYLON.Vector2.Zero();
  78414. this.motionBlurPostProcess.onApply = function (effect) {
  78415. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  78416. viewProjection.invertToRef(invViewProjection);
  78417. effect.setMatrix("inverseViewProjection", invViewProjection);
  78418. effect.setMatrix("prevViewProjection", prevViewProjection);
  78419. prevViewProjection = viewProjection;
  78420. screenSize.x = _this.motionBlurPostProcess.width;
  78421. screenSize.y = _this.motionBlurPostProcess.height;
  78422. effect.setVector2("screenSize", screenSize);
  78423. motionScale = scene.getEngine().getFps() / 60.0;
  78424. effect.setFloat("motionScale", motionScale);
  78425. effect.setFloat("motionStrength", _this.motionStrength);
  78426. effect.setTexture("depthSampler", _this._getDepthTexture());
  78427. };
  78428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  78429. };
  78430. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  78431. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  78432. var renderer = this._scene.enableGeometryBufferRenderer();
  78433. return renderer.getGBuffer().textures[0];
  78434. }
  78435. return this._scene.enableDepthRenderer().getDepthMap();
  78436. };
  78437. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  78438. for (var i = 0; i < this._cameras.length; i++) {
  78439. var camera = this._cameras[i];
  78440. if (this.originalPostProcess) {
  78441. this.originalPostProcess.dispose(camera);
  78442. }
  78443. if (this.downSampleX4PostProcess) {
  78444. this.downSampleX4PostProcess.dispose(camera);
  78445. }
  78446. if (this.brightPassPostProcess) {
  78447. this.brightPassPostProcess.dispose(camera);
  78448. }
  78449. if (this.textureAdderPostProcess) {
  78450. this.textureAdderPostProcess.dispose(camera);
  78451. }
  78452. if (this.textureAdderFinalPostProcess) {
  78453. this.textureAdderFinalPostProcess.dispose(camera);
  78454. }
  78455. if (this.volumetricLightPostProcess) {
  78456. this.volumetricLightPostProcess.dispose(camera);
  78457. }
  78458. if (this.volumetricLightSmoothXPostProcess) {
  78459. this.volumetricLightSmoothXPostProcess.dispose(camera);
  78460. }
  78461. if (this.volumetricLightSmoothYPostProcess) {
  78462. this.volumetricLightSmoothYPostProcess.dispose(camera);
  78463. }
  78464. if (this.volumetricLightMergePostProces) {
  78465. this.volumetricLightMergePostProces.dispose(camera);
  78466. }
  78467. if (this.volumetricLightFinalPostProcess) {
  78468. this.volumetricLightFinalPostProcess.dispose(camera);
  78469. }
  78470. if (this.lensFlarePostProcess) {
  78471. this.lensFlarePostProcess.dispose(camera);
  78472. }
  78473. if (this.lensFlareComposePostProcess) {
  78474. this.lensFlareComposePostProcess.dispose(camera);
  78475. }
  78476. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  78477. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  78478. }
  78479. if (this.luminancePostProcess) {
  78480. this.luminancePostProcess.dispose(camera);
  78481. }
  78482. if (this.hdrPostProcess) {
  78483. this.hdrPostProcess.dispose(camera);
  78484. }
  78485. if (this.hdrFinalPostProcess) {
  78486. this.hdrFinalPostProcess.dispose(camera);
  78487. }
  78488. if (this.depthOfFieldPostProcess) {
  78489. this.depthOfFieldPostProcess.dispose(camera);
  78490. }
  78491. if (this.motionBlurPostProcess) {
  78492. this.motionBlurPostProcess.dispose(camera);
  78493. }
  78494. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  78495. this.blurHPostProcesses[j].dispose(camera);
  78496. }
  78497. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  78498. this.blurVPostProcesses[j].dispose(camera);
  78499. }
  78500. }
  78501. this.originalPostProcess = null;
  78502. this.downSampleX4PostProcess = null;
  78503. this.brightPassPostProcess = null;
  78504. this.textureAdderPostProcess = null;
  78505. this.textureAdderFinalPostProcess = null;
  78506. this.volumetricLightPostProcess = null;
  78507. this.volumetricLightSmoothXPostProcess = null;
  78508. this.volumetricLightSmoothYPostProcess = null;
  78509. this.volumetricLightMergePostProces = null;
  78510. this.volumetricLightFinalPostProcess = null;
  78511. this.lensFlarePostProcess = null;
  78512. this.lensFlareComposePostProcess = null;
  78513. this.luminancePostProcess = null;
  78514. this.hdrPostProcess = null;
  78515. this.hdrFinalPostProcess = null;
  78516. this.depthOfFieldPostProcess = null;
  78517. this.motionBlurPostProcess = null;
  78518. this.luminanceDownSamplePostProcesses = [];
  78519. this.blurHPostProcesses = [];
  78520. this.blurVPostProcesses = [];
  78521. };
  78522. /**
  78523. * Dispose of the pipeline and stop all post processes
  78524. */
  78525. StandardRenderingPipeline.prototype.dispose = function () {
  78526. this._disposePostProcesses();
  78527. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78528. _super.prototype.dispose.call(this);
  78529. };
  78530. /**
  78531. * Serialize the rendering pipeline (Used when exporting)
  78532. * @returns the serialized object
  78533. */
  78534. StandardRenderingPipeline.prototype.serialize = function () {
  78535. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78536. if (this.sourceLight) {
  78537. serializationObject.sourceLightId = this.sourceLight.id;
  78538. }
  78539. serializationObject.customType = "StandardRenderingPipeline";
  78540. return serializationObject;
  78541. };
  78542. /**
  78543. * Parse the serialized pipeline
  78544. * @param source Source pipeline.
  78545. * @param scene The scene to load the pipeline to.
  78546. * @param rootUrl The URL of the serialized pipeline.
  78547. * @returns An instantiated pipeline from the serialized object.
  78548. */
  78549. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78550. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78551. if (source.sourceLightId) {
  78552. p.sourceLight = scene.getLightByID(source.sourceLightId);
  78553. }
  78554. return p;
  78555. };
  78556. // Luminance steps
  78557. StandardRenderingPipeline.LuminanceSteps = 6;
  78558. __decorate([
  78559. BABYLON.serialize()
  78560. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  78561. __decorate([
  78562. BABYLON.serialize()
  78563. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  78564. __decorate([
  78565. BABYLON.serialize()
  78566. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  78567. __decorate([
  78568. BABYLON.serialize()
  78569. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  78570. __decorate([
  78571. BABYLON.serializeAsTexture("lensTexture")
  78572. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  78573. __decorate([
  78574. BABYLON.serialize()
  78575. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  78576. __decorate([
  78577. BABYLON.serialize()
  78578. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  78579. __decorate([
  78580. BABYLON.serialize()
  78581. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  78582. __decorate([
  78583. BABYLON.serialize()
  78584. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  78585. __decorate([
  78586. BABYLON.serialize()
  78587. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  78588. __decorate([
  78589. BABYLON.serialize()
  78590. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  78591. __decorate([
  78592. BABYLON.serializeAsTexture("lensColorTexture")
  78593. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  78594. __decorate([
  78595. BABYLON.serialize()
  78596. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  78597. __decorate([
  78598. BABYLON.serialize()
  78599. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  78600. __decorate([
  78601. BABYLON.serialize()
  78602. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  78603. __decorate([
  78604. BABYLON.serialize()
  78605. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  78606. __decorate([
  78607. BABYLON.serializeAsTexture("lensStarTexture")
  78608. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  78609. __decorate([
  78610. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  78611. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  78612. __decorate([
  78613. BABYLON.serialize()
  78614. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  78615. __decorate([
  78616. BABYLON.serialize()
  78617. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  78618. __decorate([
  78619. BABYLON.serialize()
  78620. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  78621. __decorate([
  78622. BABYLON.serialize()
  78623. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  78624. __decorate([
  78625. BABYLON.serialize()
  78626. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  78627. __decorate([
  78628. BABYLON.serialize()
  78629. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  78630. __decorate([
  78631. BABYLON.serialize()
  78632. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  78633. __decorate([
  78634. BABYLON.serialize()
  78635. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  78636. __decorate([
  78637. BABYLON.serialize()
  78638. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  78639. __decorate([
  78640. BABYLON.serialize()
  78641. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  78642. __decorate([
  78643. BABYLON.serialize()
  78644. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  78645. __decorate([
  78646. BABYLON.serialize()
  78647. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  78648. return StandardRenderingPipeline;
  78649. }(BABYLON.PostProcessRenderPipeline));
  78650. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  78651. })(BABYLON || (BABYLON = {}));
  78652. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  78653. var BABYLON;
  78654. (function (BABYLON) {
  78655. var FxaaPostProcess = /** @class */ (function (_super) {
  78656. __extends(FxaaPostProcess, _super);
  78657. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78658. if (camera === void 0) { camera = null; }
  78659. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78660. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  78661. var defines = _this._getDefines();
  78662. _this.updateEffect(defines);
  78663. _this.onApplyObservable.add(function (effect) {
  78664. var texelSize = _this.texelSize;
  78665. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  78666. });
  78667. return _this;
  78668. }
  78669. FxaaPostProcess.prototype._getDefines = function () {
  78670. var engine = this.getEngine();
  78671. if (!engine) {
  78672. return null;
  78673. }
  78674. var glInfo = engine.getGlInfo();
  78675. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  78676. return "#define MALI 1\n";
  78677. }
  78678. return null;
  78679. };
  78680. return FxaaPostProcess;
  78681. }(BABYLON.PostProcess));
  78682. BABYLON.FxaaPostProcess = FxaaPostProcess;
  78683. })(BABYLON || (BABYLON = {}));
  78684. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  78685. var BABYLON;
  78686. (function (BABYLON) {
  78687. /**
  78688. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  78689. */
  78690. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  78691. __extends(ChromaticAberrationPostProcess, _super);
  78692. /**
  78693. * Creates a new instance ChromaticAberrationPostProcess
  78694. * @param name The name of the effect.
  78695. * @param screenWidth The width of the screen to apply the effect on.
  78696. * @param screenHeight The height of the screen to apply the effect on.
  78697. * @param options The required width/height ratio to downsize to before computing the render pass.
  78698. * @param camera The camera to apply the render pass to.
  78699. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78700. * @param engine The engine which the post process will be applied. (default: current engine)
  78701. * @param reusable If the post process can be reused on the same frame. (default: false)
  78702. * @param textureType Type of textures used when performing the post process. (default: 0)
  78703. * @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)
  78704. */
  78705. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78706. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78707. if (blockCompilation === void 0) { blockCompilation = false; }
  78708. 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;
  78709. /**
  78710. * The amount of seperation of rgb channels (default: 30)
  78711. */
  78712. _this.aberrationAmount = 30;
  78713. /**
  78714. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  78715. */
  78716. _this.radialIntensity = 0;
  78717. /**
  78718. * 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))
  78719. */
  78720. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  78721. /**
  78722. * 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))
  78723. */
  78724. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  78725. _this.onApplyObservable.add(function (effect) {
  78726. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  78727. effect.setFloat('screen_width', screenWidth);
  78728. effect.setFloat('screen_height', screenHeight);
  78729. effect.setFloat('radialIntensity', _this.radialIntensity);
  78730. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  78731. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  78732. });
  78733. return _this;
  78734. }
  78735. return ChromaticAberrationPostProcess;
  78736. }(BABYLON.PostProcess));
  78737. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  78738. })(BABYLON || (BABYLON = {}));
  78739. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  78740. var BABYLON;
  78741. (function (BABYLON) {
  78742. /**
  78743. * The GrainPostProcess adds noise to the image at mid luminance levels
  78744. */
  78745. var GrainPostProcess = /** @class */ (function (_super) {
  78746. __extends(GrainPostProcess, _super);
  78747. /**
  78748. * Creates a new instance of @see GrainPostProcess
  78749. * @param name The name of the effect.
  78750. * @param options The required width/height ratio to downsize to before computing the render pass.
  78751. * @param camera The camera to apply the render pass to.
  78752. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78753. * @param engine The engine which the post process will be applied. (default: current engine)
  78754. * @param reusable If the post process can be reused on the same frame. (default: false)
  78755. * @param textureType Type of textures used when performing the post process. (default: 0)
  78756. * @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)
  78757. */
  78758. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78759. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78760. if (blockCompilation === void 0) { blockCompilation = false; }
  78761. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78762. /**
  78763. * The intensity of the grain added (default: 30)
  78764. */
  78765. _this.intensity = 30;
  78766. /**
  78767. * If the grain should be randomized on every frame
  78768. */
  78769. _this.animated = false;
  78770. _this.onApplyObservable.add(function (effect) {
  78771. effect.setFloat('intensity', _this.intensity);
  78772. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  78773. });
  78774. return _this;
  78775. }
  78776. return GrainPostProcess;
  78777. }(BABYLON.PostProcess));
  78778. BABYLON.GrainPostProcess = GrainPostProcess;
  78779. })(BABYLON || (BABYLON = {}));
  78780. //# sourceMappingURL=babylon.grainPostProcess.js.map
  78781. var BABYLON;
  78782. (function (BABYLON) {
  78783. /**
  78784. * The SharpenPostProcess applies a sharpen kernel to every pixel
  78785. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78786. */
  78787. var SharpenPostProcess = /** @class */ (function (_super) {
  78788. __extends(SharpenPostProcess, _super);
  78789. /**
  78790. * Creates a new instance ConvolutionPostProcess
  78791. * @param name The name of the effect.
  78792. * @param options The required width/height ratio to downsize to before computing the render pass.
  78793. * @param camera The camera to apply the render pass to.
  78794. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78795. * @param engine The engine which the post process will be applied. (default: current engine)
  78796. * @param reusable If the post process can be reused on the same frame. (default: false)
  78797. * @param textureType Type of textures used when performing the post process. (default: 0)
  78798. * @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)
  78799. */
  78800. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78801. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78802. if (blockCompilation === void 0) { blockCompilation = false; }
  78803. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78804. /**
  78805. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  78806. */
  78807. _this.colorAmount = 1.0;
  78808. /**
  78809. * How much sharpness should be applied (default: 0.3)
  78810. */
  78811. _this.edgeAmount = 0.3;
  78812. _this.onApply = function (effect) {
  78813. effect.setFloat2("screenSize", _this.width, _this.height);
  78814. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  78815. };
  78816. return _this;
  78817. }
  78818. return SharpenPostProcess;
  78819. }(BABYLON.PostProcess));
  78820. BABYLON.SharpenPostProcess = SharpenPostProcess;
  78821. })(BABYLON || (BABYLON = {}));
  78822. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  78823. var BABYLON;
  78824. (function (BABYLON) {
  78825. /**
  78826. * The Blur Post Process which blurs an image based on a kernel and direction.
  78827. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  78828. */
  78829. var BlurPostProcess = /** @class */ (function (_super) {
  78830. __extends(BlurPostProcess, _super);
  78831. /**
  78832. * Creates a new instance BlurPostProcess
  78833. * @param name The name of the effect.
  78834. * @param direction The direction in which to blur the image.
  78835. * @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.
  78836. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  78837. * @param camera The camera to apply the render pass to.
  78838. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78839. * @param engine The engine which the post process will be applied. (default: current engine)
  78840. * @param reusable If the post process can be reused on the same frame. (default: false)
  78841. * @param textureType Type of textures used when performing the post process. (default: 0)
  78842. * @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)
  78843. */
  78844. function BlurPostProcess(name,
  78845. /** The direction in which to blur the image. */
  78846. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  78847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78848. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78849. if (defines === void 0) { defines = ""; }
  78850. if (blockCompilation === void 0) { blockCompilation = false; }
  78851. 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;
  78852. _this.direction = direction;
  78853. _this.blockCompilation = blockCompilation;
  78854. _this._packedFloat = false;
  78855. _this._staticDefines = "";
  78856. _this._staticDefines = defines;
  78857. _this.onApplyObservable.add(function (effect) {
  78858. if (_this._outputTexture) {
  78859. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  78860. }
  78861. else {
  78862. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  78863. }
  78864. });
  78865. _this.kernel = kernel;
  78866. return _this;
  78867. }
  78868. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  78869. /**
  78870. * Gets the length in pixels of the blur sample region
  78871. */
  78872. get: function () {
  78873. return this._idealKernel;
  78874. },
  78875. /**
  78876. * Sets the length in pixels of the blur sample region
  78877. */
  78878. set: function (v) {
  78879. if (this._idealKernel === v) {
  78880. return;
  78881. }
  78882. v = Math.max(v, 1);
  78883. this._idealKernel = v;
  78884. this._kernel = this._nearestBestKernel(v);
  78885. if (!this.blockCompilation) {
  78886. this._updateParameters();
  78887. }
  78888. },
  78889. enumerable: true,
  78890. configurable: true
  78891. });
  78892. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  78893. /**
  78894. * Gets wether or not the blur is unpacking/repacking floats
  78895. */
  78896. get: function () {
  78897. return this._packedFloat;
  78898. },
  78899. /**
  78900. * Sets wether or not the blur needs to unpack/repack floats
  78901. */
  78902. set: function (v) {
  78903. if (this._packedFloat === v) {
  78904. return;
  78905. }
  78906. this._packedFloat = v;
  78907. if (!this.blockCompilation) {
  78908. this._updateParameters();
  78909. }
  78910. },
  78911. enumerable: true,
  78912. configurable: true
  78913. });
  78914. /**
  78915. * Updates the effect with the current post process compile time values and recompiles the shader.
  78916. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78917. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78918. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78919. * @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
  78920. * @param onCompiled Called when the shader has been compiled.
  78921. * @param onError Called if there is an error when compiling a shader.
  78922. */
  78923. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78924. if (defines === void 0) { defines = null; }
  78925. if (uniforms === void 0) { uniforms = null; }
  78926. if (samplers === void 0) { samplers = null; }
  78927. this._updateParameters(onCompiled, onError);
  78928. };
  78929. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  78930. // Generate sampling offsets and weights
  78931. var N = this._kernel;
  78932. var centerIndex = (N - 1) / 2;
  78933. // Generate Gaussian sampling weights over kernel
  78934. var offsets = [];
  78935. var weights = [];
  78936. var totalWeight = 0;
  78937. for (var i = 0; i < N; i++) {
  78938. var u = i / (N - 1);
  78939. var w = this._gaussianWeight(u * 2.0 - 1);
  78940. offsets[i] = (i - centerIndex);
  78941. weights[i] = w;
  78942. totalWeight += w;
  78943. }
  78944. // Normalize weights
  78945. for (var i = 0; i < weights.length; i++) {
  78946. weights[i] /= totalWeight;
  78947. }
  78948. // Optimize: combine samples to take advantage of hardware linear sampling
  78949. // Walk from left to center, combining pairs (symmetrically)
  78950. var linearSamplingWeights = [];
  78951. var linearSamplingOffsets = [];
  78952. var linearSamplingMap = [];
  78953. for (var i = 0; i <= centerIndex; i += 2) {
  78954. var j = Math.min(i + 1, Math.floor(centerIndex));
  78955. var singleCenterSample = i === j;
  78956. if (singleCenterSample) {
  78957. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78958. }
  78959. else {
  78960. var sharedCell = j === centerIndex;
  78961. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  78962. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  78963. if (offsetLinear === 0) {
  78964. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78965. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  78966. }
  78967. else {
  78968. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  78969. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  78970. }
  78971. }
  78972. }
  78973. for (var i = 0; i < linearSamplingMap.length; i++) {
  78974. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  78975. linearSamplingWeights[i] = linearSamplingMap[i].w;
  78976. }
  78977. // Replace with optimized
  78978. offsets = linearSamplingOffsets;
  78979. weights = linearSamplingWeights;
  78980. // Generate shaders
  78981. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  78982. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  78983. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  78984. var defines = "";
  78985. defines += this._staticDefines;
  78986. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  78987. if (this._staticDefines.indexOf("DOF") != -1) {
  78988. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  78989. varyingCount--;
  78990. }
  78991. for (var i = 0; i < varyingCount; i++) {
  78992. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  78993. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  78994. }
  78995. var depCount = 0;
  78996. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  78997. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  78998. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  78999. depCount++;
  79000. }
  79001. if (this.packedFloat) {
  79002. defines += "#define PACKEDFLOAT 1";
  79003. }
  79004. this.blockCompilation = false;
  79005. _super.prototype.updateEffect.call(this, defines, null, null, {
  79006. varyingCount: varyingCount,
  79007. depCount: depCount
  79008. }, onCompiled, onError);
  79009. };
  79010. /**
  79011. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  79012. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  79013. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  79014. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  79015. * The gaps between physical kernels are compensated for in the weighting of the samples
  79016. * @param idealKernel Ideal blur kernel.
  79017. * @return Nearest best kernel.
  79018. */
  79019. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  79020. var v = Math.round(idealKernel);
  79021. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  79022. var k = _a[_i];
  79023. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  79024. return Math.max(k, 3);
  79025. }
  79026. }
  79027. return Math.max(v, 3);
  79028. };
  79029. /**
  79030. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  79031. * @param x The point on the Gaussian distribution to sample.
  79032. * @return the value of the Gaussian function at x.
  79033. */
  79034. BlurPostProcess.prototype._gaussianWeight = function (x) {
  79035. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  79036. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  79037. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  79038. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  79039. // truncated at around 1.3% of peak strength.
  79040. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  79041. var sigma = (1 / 3);
  79042. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  79043. var exponent = -((x * x) / (2.0 * sigma * sigma));
  79044. var weight = (1.0 / denominator) * Math.exp(exponent);
  79045. return weight;
  79046. };
  79047. /**
  79048. * Generates a string that can be used as a floating point number in GLSL.
  79049. * @param x Value to print.
  79050. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  79051. * @return GLSL float string.
  79052. */
  79053. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  79054. if (decimalFigures === void 0) { decimalFigures = 8; }
  79055. return x.toFixed(decimalFigures).replace(/0+$/, '');
  79056. };
  79057. return BlurPostProcess;
  79058. }(BABYLON.PostProcess));
  79059. BABYLON.BlurPostProcess = BlurPostProcess;
  79060. })(BABYLON || (BABYLON = {}));
  79061. //# sourceMappingURL=babylon.blurPostProcess.js.map
  79062. var BABYLON;
  79063. (function (BABYLON) {
  79064. /**
  79065. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  79066. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  79067. * based on samples that have a large difference in distance than the center pixel.
  79068. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79069. */
  79070. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  79071. __extends(DepthOfFieldBlurPostProcess, _super);
  79072. /**
  79073. * Creates a new instance CircleOfConfusionPostProcess
  79074. * @param name The name of the effect.
  79075. * @param scene The scene the effect belongs to.
  79076. * @param direction The direction the blur should be applied.
  79077. * @param kernel The size of the kernel used to blur.
  79078. * @param options The required width/height ratio to downsize to before computing the render pass.
  79079. * @param camera The camera to apply the render pass to.
  79080. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  79081. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  79082. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79083. * @param engine The engine which the post process will be applied. (default: current engine)
  79084. * @param reusable If the post process can be reused on the same frame. (default: false)
  79085. * @param textureType Type of textures used when performing the post process. (default: 0)
  79086. * @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)
  79087. */
  79088. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  79089. if (imageToBlur === void 0) { imageToBlur = null; }
  79090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79091. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79092. if (blockCompilation === void 0) { blockCompilation = false; }
  79093. 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;
  79094. _this.direction = direction;
  79095. _this.onApplyObservable.add(function (effect) {
  79096. if (imageToBlur != null) {
  79097. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  79098. }
  79099. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79100. if (scene.activeCamera) {
  79101. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  79102. }
  79103. });
  79104. return _this;
  79105. }
  79106. return DepthOfFieldBlurPostProcess;
  79107. }(BABYLON.BlurPostProcess));
  79108. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  79109. })(BABYLON || (BABYLON = {}));
  79110. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  79111. var BABYLON;
  79112. (function (BABYLON) {
  79113. /**
  79114. * Options to be set when merging outputs from the default pipeline.
  79115. */
  79116. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  79117. function DepthOfFieldMergePostProcessOptions() {
  79118. }
  79119. return DepthOfFieldMergePostProcessOptions;
  79120. }());
  79121. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  79122. /**
  79123. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79124. */
  79125. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  79126. __extends(DepthOfFieldMergePostProcess, _super);
  79127. /**
  79128. * Creates a new instance of DepthOfFieldMergePostProcess
  79129. * @param name The name of the effect.
  79130. * @param originalFromInput Post process which's input will be used for the merge.
  79131. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  79132. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  79133. * @param options The required width/height ratio to downsize to before computing the render pass.
  79134. * @param camera The camera to apply the render pass to.
  79135. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79136. * @param engine The engine which the post process will be applied. (default: current engine)
  79137. * @param reusable If the post process can be reused on the same frame. (default: false)
  79138. * @param textureType Type of textures used when performing the post process. (default: 0)
  79139. * @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)
  79140. */
  79141. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79143. if (blockCompilation === void 0) { blockCompilation = false; }
  79144. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79145. _this.blurSteps = blurSteps;
  79146. _this.onApplyObservable.add(function (effect) {
  79147. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79148. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79149. blurSteps.forEach(function (step, index) {
  79150. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  79151. });
  79152. });
  79153. if (!blockCompilation) {
  79154. _this.updateEffect();
  79155. }
  79156. return _this;
  79157. }
  79158. /**
  79159. * Updates the effect with the current post process compile time values and recompiles the shader.
  79160. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79161. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79162. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79163. * @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
  79164. * @param onCompiled Called when the shader has been compiled.
  79165. * @param onError Called if there is an error when compiling a shader.
  79166. */
  79167. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79168. if (defines === void 0) { defines = null; }
  79169. if (uniforms === void 0) { uniforms = null; }
  79170. if (samplers === void 0) { samplers = null; }
  79171. if (!defines) {
  79172. defines = "";
  79173. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  79174. }
  79175. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  79176. };
  79177. return DepthOfFieldMergePostProcess;
  79178. }(BABYLON.PostProcess));
  79179. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  79180. })(BABYLON || (BABYLON = {}));
  79181. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  79182. var BABYLON;
  79183. (function (BABYLON) {
  79184. /**
  79185. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  79186. */
  79187. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  79188. __extends(CircleOfConfusionPostProcess, _super);
  79189. /**
  79190. * Creates a new instance CircleOfConfusionPostProcess
  79191. * @param name The name of the effect.
  79192. * @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.
  79193. * @param options The required width/height ratio to downsize to before computing the render pass.
  79194. * @param camera The camera to apply the render pass to.
  79195. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79196. * @param engine The engine which the post process will be applied. (default: current engine)
  79197. * @param reusable If the post process can be reused on the same frame. (default: false)
  79198. * @param textureType Type of textures used when performing the post process. (default: 0)
  79199. * @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)
  79200. */
  79201. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79202. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79203. if (blockCompilation === void 0) { blockCompilation = false; }
  79204. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79205. /**
  79206. * 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.
  79207. */
  79208. _this.lensSize = 50;
  79209. /**
  79210. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79211. */
  79212. _this.fStop = 1.4;
  79213. /**
  79214. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79215. */
  79216. _this.focusDistance = 2000;
  79217. /**
  79218. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  79219. */
  79220. _this.focalLength = 50;
  79221. _this._depthTexture = null;
  79222. _this._depthTexture = depthTexture;
  79223. _this.onApplyObservable.add(function (effect) {
  79224. if (!_this._depthTexture) {
  79225. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  79226. return;
  79227. }
  79228. effect.setTexture("depthSampler", _this._depthTexture);
  79229. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  79230. var aperture = _this.lensSize / _this.fStop;
  79231. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  79232. effect.setFloat('focusDistance', _this.focusDistance);
  79233. effect.setFloat('cocPrecalculation', cocPrecalculation);
  79234. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  79235. });
  79236. return _this;
  79237. }
  79238. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  79239. /**
  79240. * 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.
  79241. */
  79242. set: function (value) {
  79243. this._depthTexture = value;
  79244. },
  79245. enumerable: true,
  79246. configurable: true
  79247. });
  79248. return CircleOfConfusionPostProcess;
  79249. }(BABYLON.PostProcess));
  79250. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  79251. })(BABYLON || (BABYLON = {}));
  79252. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  79253. var BABYLON;
  79254. (function (BABYLON) {
  79255. /**
  79256. * Specifies the level of max blur that should be applied when using the depth of field effect
  79257. */
  79258. var DepthOfFieldEffectBlurLevel;
  79259. (function (DepthOfFieldEffectBlurLevel) {
  79260. /**
  79261. * Subtle blur
  79262. */
  79263. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  79264. /**
  79265. * Medium blur
  79266. */
  79267. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  79268. /**
  79269. * Large blur
  79270. */
  79271. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  79272. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  79273. ;
  79274. /**
  79275. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  79276. */
  79277. var DepthOfFieldEffect = /** @class */ (function (_super) {
  79278. __extends(DepthOfFieldEffect, _super);
  79279. /**
  79280. * Creates a new instance DepthOfFieldEffect
  79281. * @param scene The scene the effect belongs to.
  79282. * @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.
  79283. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79284. * @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)
  79285. */
  79286. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  79287. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  79288. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79289. if (blockCompilation === void 0) { blockCompilation = false; }
  79290. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  79291. return _this._effects;
  79292. }, true) || this;
  79293. /**
  79294. * @hidden Internal post processes in depth of field effect
  79295. */
  79296. _this._effects = [];
  79297. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  79298. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79299. // 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)
  79300. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  79301. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79302. _this._depthOfFieldBlurY = [];
  79303. _this._depthOfFieldBlurX = [];
  79304. var blurCount = 1;
  79305. var kernelSize = 15;
  79306. switch (blurLevel) {
  79307. case DepthOfFieldEffectBlurLevel.High: {
  79308. blurCount = 3;
  79309. kernelSize = 51;
  79310. break;
  79311. }
  79312. case DepthOfFieldEffectBlurLevel.Medium: {
  79313. blurCount = 2;
  79314. kernelSize = 31;
  79315. break;
  79316. }
  79317. default: {
  79318. kernelSize = 15;
  79319. blurCount = 1;
  79320. break;
  79321. }
  79322. }
  79323. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  79324. var ratio = 1.0;
  79325. for (var i = 0; i < blurCount; i++) {
  79326. 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);
  79327. blurY.autoClear = false;
  79328. ratio = 0.75 / Math.pow(2, i);
  79329. 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);
  79330. blurX.autoClear = false;
  79331. _this._depthOfFieldBlurY.push(blurY);
  79332. _this._depthOfFieldBlurX.push(blurX);
  79333. }
  79334. // Set all post processes on the effect.
  79335. _this._effects = [_this._circleOfConfusion];
  79336. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  79337. _this._effects.push(_this._depthOfFieldBlurY[i]);
  79338. _this._effects.push(_this._depthOfFieldBlurX[i]);
  79339. }
  79340. // Merge blurred images with original image based on circleOfConfusion
  79341. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79342. _this._dofMerge.autoClear = false;
  79343. _this._effects.push(_this._dofMerge);
  79344. return _this;
  79345. }
  79346. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  79347. get: function () {
  79348. return this._circleOfConfusion.focalLength;
  79349. },
  79350. /**
  79351. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  79352. */
  79353. set: function (value) {
  79354. this._circleOfConfusion.focalLength = value;
  79355. },
  79356. enumerable: true,
  79357. configurable: true
  79358. });
  79359. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  79360. get: function () {
  79361. return this._circleOfConfusion.fStop;
  79362. },
  79363. /**
  79364. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79365. */
  79366. set: function (value) {
  79367. this._circleOfConfusion.fStop = value;
  79368. },
  79369. enumerable: true,
  79370. configurable: true
  79371. });
  79372. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  79373. get: function () {
  79374. return this._circleOfConfusion.focusDistance;
  79375. },
  79376. /**
  79377. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79378. */
  79379. set: function (value) {
  79380. this._circleOfConfusion.focusDistance = value;
  79381. },
  79382. enumerable: true,
  79383. configurable: true
  79384. });
  79385. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  79386. get: function () {
  79387. return this._circleOfConfusion.lensSize;
  79388. },
  79389. /**
  79390. * 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.
  79391. */
  79392. set: function (value) {
  79393. this._circleOfConfusion.lensSize = value;
  79394. },
  79395. enumerable: true,
  79396. configurable: true
  79397. });
  79398. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  79399. /**
  79400. * 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.
  79401. */
  79402. set: function (value) {
  79403. this._circleOfConfusion.depthTexture = value;
  79404. },
  79405. enumerable: true,
  79406. configurable: true
  79407. });
  79408. /**
  79409. * Disposes each of the internal effects for a given camera.
  79410. * @param camera The camera to dispose the effect on.
  79411. */
  79412. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  79413. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79414. this._effects[effectIndex].dispose(camera);
  79415. }
  79416. };
  79417. /**
  79418. * @hidden Internal
  79419. */
  79420. DepthOfFieldEffect.prototype._updateEffects = function () {
  79421. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79422. this._effects[effectIndex].updateEffect();
  79423. }
  79424. };
  79425. /**
  79426. * Internal
  79427. * @returns if all the contained post processes are ready.
  79428. * @hidden
  79429. */
  79430. DepthOfFieldEffect.prototype._isReady = function () {
  79431. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79432. if (!this._effects[effectIndex].isReady()) {
  79433. return false;
  79434. }
  79435. }
  79436. return true;
  79437. };
  79438. return DepthOfFieldEffect;
  79439. }(BABYLON.PostProcessRenderEffect));
  79440. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  79441. })(BABYLON || (BABYLON = {}));
  79442. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  79443. var BABYLON;
  79444. (function (BABYLON) {
  79445. /**
  79446. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79447. */
  79448. var BloomMergePostProcess = /** @class */ (function (_super) {
  79449. __extends(BloomMergePostProcess, _super);
  79450. /**
  79451. * Creates a new instance of @see BloomMergePostProcess
  79452. * @param name The name of the effect.
  79453. * @param originalFromInput Post process which's input will be used for the merge.
  79454. * @param blurred Blurred highlights post process which's output will be used.
  79455. * @param weight Weight of the bloom to be added to the original input.
  79456. * @param options The required width/height ratio to downsize to before computing the render pass.
  79457. * @param camera The camera to apply the render pass to.
  79458. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79459. * @param engine The engine which the post process will be applied. (default: current engine)
  79460. * @param reusable If the post process can be reused on the same frame. (default: false)
  79461. * @param textureType Type of textures used when performing the post process. (default: 0)
  79462. * @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)
  79463. */
  79464. function BloomMergePostProcess(name, originalFromInput, blurred,
  79465. /** Weight of the bloom to be added to the original input. */
  79466. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79467. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79468. if (blockCompilation === void 0) { blockCompilation = false; }
  79469. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79470. _this.weight = weight;
  79471. _this.onApplyObservable.add(function (effect) {
  79472. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79473. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  79474. effect.setFloat("bloomWeight", _this.weight);
  79475. });
  79476. if (!blockCompilation) {
  79477. _this.updateEffect();
  79478. }
  79479. return _this;
  79480. }
  79481. return BloomMergePostProcess;
  79482. }(BABYLON.PostProcess));
  79483. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  79484. })(BABYLON || (BABYLON = {}));
  79485. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  79486. var BABYLON;
  79487. (function (BABYLON) {
  79488. /**
  79489. * 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.
  79490. */
  79491. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  79492. __extends(ExtractHighlightsPostProcess, _super);
  79493. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79494. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79495. if (blockCompilation === void 0) { blockCompilation = false; }
  79496. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79497. /**
  79498. * The luminance threshold, pixels below this value will be set to black.
  79499. */
  79500. _this.threshold = 0.9;
  79501. /** @hidden */
  79502. _this._exposure = 1;
  79503. /**
  79504. * Post process which has the input texture to be used when performing highlight extraction
  79505. * @hidden
  79506. */
  79507. _this._inputPostProcess = null;
  79508. _this.onApplyObservable.add(function (effect) {
  79509. if (_this._inputPostProcess) {
  79510. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  79511. }
  79512. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  79513. effect.setFloat('exposure', _this._exposure);
  79514. });
  79515. return _this;
  79516. }
  79517. return ExtractHighlightsPostProcess;
  79518. }(BABYLON.PostProcess));
  79519. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  79520. })(BABYLON || (BABYLON = {}));
  79521. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  79522. var BABYLON;
  79523. (function (BABYLON) {
  79524. /**
  79525. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  79526. */
  79527. var BloomEffect = /** @class */ (function (_super) {
  79528. __extends(BloomEffect, _super);
  79529. /**
  79530. * Creates a new instance of @see BloomEffect
  79531. * @param scene The scene the effect belongs to.
  79532. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  79533. * @param bloomKernel The size of the kernel to be used when applying the blur.
  79534. * @param bloomWeight The the strength of bloom.
  79535. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79536. * @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)
  79537. */
  79538. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  79539. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79540. if (blockCompilation === void 0) { blockCompilation = false; }
  79541. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  79542. return _this._effects;
  79543. }, true) || this;
  79544. _this.bloomScale = bloomScale;
  79545. /**
  79546. * @hidden Internal
  79547. */
  79548. _this._effects = [];
  79549. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79550. _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);
  79551. _this._blurX.alwaysForcePOT = true;
  79552. _this._blurX.autoClear = false;
  79553. _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);
  79554. _this._blurY.alwaysForcePOT = true;
  79555. _this._blurY.autoClear = false;
  79556. _this.kernel = bloomKernel;
  79557. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  79558. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79559. _this._merge.autoClear = false;
  79560. _this._effects.push(_this._merge);
  79561. return _this;
  79562. }
  79563. Object.defineProperty(BloomEffect.prototype, "threshold", {
  79564. /**
  79565. * The luminance threshold to find bright areas of the image to bloom.
  79566. */
  79567. get: function () {
  79568. return this._downscale.threshold;
  79569. },
  79570. set: function (value) {
  79571. this._downscale.threshold = value;
  79572. },
  79573. enumerable: true,
  79574. configurable: true
  79575. });
  79576. Object.defineProperty(BloomEffect.prototype, "weight", {
  79577. /**
  79578. * The strength of the bloom.
  79579. */
  79580. get: function () {
  79581. return this._merge.weight;
  79582. },
  79583. set: function (value) {
  79584. this._merge.weight = value;
  79585. },
  79586. enumerable: true,
  79587. configurable: true
  79588. });
  79589. Object.defineProperty(BloomEffect.prototype, "kernel", {
  79590. /**
  79591. * Specifies the size of the bloom blur kernel, relative to the final output size
  79592. */
  79593. get: function () {
  79594. return this._blurX.kernel / this.bloomScale;
  79595. },
  79596. set: function (value) {
  79597. this._blurX.kernel = value * this.bloomScale;
  79598. this._blurY.kernel = value * this.bloomScale;
  79599. },
  79600. enumerable: true,
  79601. configurable: true
  79602. });
  79603. /**
  79604. * Disposes each of the internal effects for a given camera.
  79605. * @param camera The camera to dispose the effect on.
  79606. */
  79607. BloomEffect.prototype.disposeEffects = function (camera) {
  79608. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79609. this._effects[effectIndex].dispose(camera);
  79610. }
  79611. };
  79612. /**
  79613. * @hidden Internal
  79614. */
  79615. BloomEffect.prototype._updateEffects = function () {
  79616. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79617. this._effects[effectIndex].updateEffect();
  79618. }
  79619. };
  79620. /**
  79621. * Internal
  79622. * @returns if all the contained post processes are ready.
  79623. * @hidden
  79624. */
  79625. BloomEffect.prototype._isReady = function () {
  79626. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79627. if (!this._effects[effectIndex].isReady()) {
  79628. return false;
  79629. }
  79630. }
  79631. return true;
  79632. };
  79633. return BloomEffect;
  79634. }(BABYLON.PostProcessRenderEffect));
  79635. BABYLON.BloomEffect = BloomEffect;
  79636. })(BABYLON || (BABYLON = {}));
  79637. //# sourceMappingURL=babylon.bloomEffect.js.map
  79638. var BABYLON;
  79639. (function (BABYLON) {
  79640. /**
  79641. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  79642. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  79643. */
  79644. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  79645. __extends(DefaultRenderingPipeline, _super);
  79646. /**
  79647. * @constructor
  79648. * @param {string} name - The rendering pipeline name (default: "")
  79649. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  79650. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  79651. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  79652. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  79653. */
  79654. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  79655. if (name === void 0) { name = ""; }
  79656. if (hdr === void 0) { hdr = true; }
  79657. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  79658. if (automaticBuild === void 0) { automaticBuild = true; }
  79659. var _this = _super.call(this, scene.getEngine(), name) || this;
  79660. _this._camerasToBeAttached = [];
  79661. /**
  79662. * ID of the sharpen post process,
  79663. */
  79664. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  79665. /**
  79666. * ID of the image processing post process;
  79667. */
  79668. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  79669. /**
  79670. * ID of the Fast Approximate Anti-Aliasing post process;
  79671. */
  79672. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  79673. /**
  79674. * ID of the chromatic aberration post process,
  79675. */
  79676. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  79677. /**
  79678. * ID of the grain post process
  79679. */
  79680. _this.GrainPostProcessId = "GrainPostProcessEffect";
  79681. /**
  79682. * Glow post process which adds a glow to emmisive areas of the image
  79683. */
  79684. _this._glowLayer = null;
  79685. /**
  79686. * Animations which can be used to tweak settings over a period of time
  79687. */
  79688. _this.animations = [];
  79689. _this._imageProcessingConfigurationObserver = null;
  79690. // Values
  79691. _this._sharpenEnabled = false;
  79692. _this._bloomEnabled = false;
  79693. _this._depthOfFieldEnabled = false;
  79694. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  79695. _this._fxaaEnabled = false;
  79696. _this._imageProcessingEnabled = true;
  79697. _this._bloomScale = 0.5;
  79698. _this._chromaticAberrationEnabled = false;
  79699. _this._grainEnabled = false;
  79700. _this._buildAllowed = true;
  79701. _this._resizeObserver = null;
  79702. _this._hardwareScaleLevel = 1.0;
  79703. _this._bloomKernel = 64;
  79704. /**
  79705. * Specifies the weight of the bloom in the final rendering
  79706. */
  79707. _this._bloomWeight = 0.15;
  79708. /**
  79709. * Specifies the luma threshold for the area that will be blurred by the bloom
  79710. */
  79711. _this._bloomThreshold = 0.9;
  79712. _this._samples = 1;
  79713. _this._hasCleared = false;
  79714. _this._prevPostProcess = null;
  79715. _this._prevPrevPostProcess = null;
  79716. _this._cameras = cameras || scene.cameras;
  79717. _this._cameras = _this._cameras.slice();
  79718. _this._camerasToBeAttached = _this._cameras.slice();
  79719. _this._buildAllowed = automaticBuild;
  79720. // Initialize
  79721. _this._scene = scene;
  79722. var caps = _this._scene.getEngine().getCaps();
  79723. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  79724. // Misc
  79725. if (_this._hdr) {
  79726. if (caps.textureHalfFloatRender) {
  79727. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79728. }
  79729. else if (caps.textureFloatRender) {
  79730. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79731. }
  79732. }
  79733. else {
  79734. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79735. }
  79736. // Attach
  79737. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79738. var engine = _this._scene.getEngine();
  79739. // Create post processes before hand so they can be modified before enabled.
  79740. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  79741. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79742. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  79743. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  79744. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  79745. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79746. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  79747. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79748. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  79749. _this._resizeObserver = engine.onResizeObservable.add(function () {
  79750. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  79751. _this.bloomKernel = _this.bloomKernel;
  79752. });
  79753. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  79754. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  79755. });
  79756. _this._buildPipeline();
  79757. return _this;
  79758. }
  79759. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  79760. get: function () {
  79761. return this._sharpenEnabled;
  79762. },
  79763. /**
  79764. * Enable or disable the sharpen process from the pipeline
  79765. */
  79766. set: function (enabled) {
  79767. if (this._sharpenEnabled === enabled) {
  79768. return;
  79769. }
  79770. this._sharpenEnabled = enabled;
  79771. this._buildPipeline();
  79772. },
  79773. enumerable: true,
  79774. configurable: true
  79775. });
  79776. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  79777. /**
  79778. * Specifies the size of the bloom blur kernel, relative to the final output size
  79779. */
  79780. get: function () {
  79781. return this._bloomKernel;
  79782. },
  79783. set: function (value) {
  79784. this._bloomKernel = value;
  79785. this.bloom.kernel = value / this._hardwareScaleLevel;
  79786. },
  79787. enumerable: true,
  79788. configurable: true
  79789. });
  79790. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  79791. get: function () {
  79792. return this._bloomWeight;
  79793. },
  79794. /**
  79795. * The strength of the bloom.
  79796. */
  79797. set: function (value) {
  79798. if (this._bloomWeight === value) {
  79799. return;
  79800. }
  79801. this.bloom.weight = value;
  79802. this._bloomWeight = value;
  79803. },
  79804. enumerable: true,
  79805. configurable: true
  79806. });
  79807. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  79808. get: function () {
  79809. return this._bloomThreshold;
  79810. },
  79811. /**
  79812. * The strength of the bloom.
  79813. */
  79814. set: function (value) {
  79815. if (this._bloomThreshold === value) {
  79816. return;
  79817. }
  79818. this.bloom.threshold = value;
  79819. this._bloomThreshold = value;
  79820. },
  79821. enumerable: true,
  79822. configurable: true
  79823. });
  79824. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  79825. get: function () {
  79826. return this._bloomScale;
  79827. },
  79828. /**
  79829. * The scale of the bloom, lower value will provide better performance.
  79830. */
  79831. set: function (value) {
  79832. if (this._bloomScale === value) {
  79833. return;
  79834. }
  79835. this._bloomScale = value;
  79836. // recreate bloom and dispose old as this setting is not dynamic
  79837. this._rebuildBloom();
  79838. this._buildPipeline();
  79839. },
  79840. enumerable: true,
  79841. configurable: true
  79842. });
  79843. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  79844. get: function () {
  79845. return this._bloomEnabled;
  79846. },
  79847. /**
  79848. * Enable or disable the bloom from the pipeline
  79849. */
  79850. set: function (enabled) {
  79851. if (this._bloomEnabled === enabled) {
  79852. return;
  79853. }
  79854. this._bloomEnabled = enabled;
  79855. this._buildPipeline();
  79856. },
  79857. enumerable: true,
  79858. configurable: true
  79859. });
  79860. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  79861. // recreate bloom and dispose old as this setting is not dynamic
  79862. var oldBloom = this.bloom;
  79863. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  79864. this.bloom.threshold = oldBloom.threshold;
  79865. for (var i = 0; i < this._cameras.length; i++) {
  79866. oldBloom.disposeEffects(this._cameras[i]);
  79867. }
  79868. };
  79869. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  79870. /**
  79871. * If the depth of field is enabled.
  79872. */
  79873. get: function () {
  79874. return this._depthOfFieldEnabled;
  79875. },
  79876. set: function (enabled) {
  79877. if (this._depthOfFieldEnabled === enabled) {
  79878. return;
  79879. }
  79880. this._depthOfFieldEnabled = enabled;
  79881. this._buildPipeline();
  79882. },
  79883. enumerable: true,
  79884. configurable: true
  79885. });
  79886. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  79887. /**
  79888. * Blur level of the depth of field effect. (Higher blur will effect performance)
  79889. */
  79890. get: function () {
  79891. return this._depthOfFieldBlurLevel;
  79892. },
  79893. set: function (value) {
  79894. if (this._depthOfFieldBlurLevel === value) {
  79895. return;
  79896. }
  79897. this._depthOfFieldBlurLevel = value;
  79898. // recreate dof and dispose old as this setting is not dynamic
  79899. var oldDof = this.depthOfField;
  79900. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  79901. this.depthOfField.focalLength = oldDof.focalLength;
  79902. this.depthOfField.focusDistance = oldDof.focusDistance;
  79903. this.depthOfField.fStop = oldDof.fStop;
  79904. this.depthOfField.lensSize = oldDof.lensSize;
  79905. for (var i = 0; i < this._cameras.length; i++) {
  79906. oldDof.disposeEffects(this._cameras[i]);
  79907. }
  79908. this._buildPipeline();
  79909. },
  79910. enumerable: true,
  79911. configurable: true
  79912. });
  79913. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  79914. get: function () {
  79915. return this._fxaaEnabled;
  79916. },
  79917. /**
  79918. * If the anti aliasing is enabled.
  79919. */
  79920. set: function (enabled) {
  79921. if (this._fxaaEnabled === enabled) {
  79922. return;
  79923. }
  79924. this._fxaaEnabled = enabled;
  79925. this._buildPipeline();
  79926. },
  79927. enumerable: true,
  79928. configurable: true
  79929. });
  79930. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  79931. get: function () {
  79932. return this._samples;
  79933. },
  79934. /**
  79935. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79936. */
  79937. set: function (sampleCount) {
  79938. if (this._samples === sampleCount) {
  79939. return;
  79940. }
  79941. this._samples = sampleCount;
  79942. this._buildPipeline();
  79943. },
  79944. enumerable: true,
  79945. configurable: true
  79946. });
  79947. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  79948. get: function () {
  79949. return this._imageProcessingEnabled;
  79950. },
  79951. /**
  79952. * If image processing is enabled.
  79953. */
  79954. set: function (enabled) {
  79955. if (this._imageProcessingEnabled === enabled) {
  79956. return;
  79957. }
  79958. this._imageProcessingEnabled = enabled;
  79959. this._buildPipeline();
  79960. },
  79961. enumerable: true,
  79962. configurable: true
  79963. });
  79964. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  79965. get: function () {
  79966. return this._glowLayer == null;
  79967. },
  79968. /**
  79969. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  79970. */
  79971. set: function (enabled) {
  79972. if (enabled && !this._glowLayer) {
  79973. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  79974. }
  79975. else if (!enabled && this._glowLayer) {
  79976. this._glowLayer.dispose();
  79977. this._glowLayer = null;
  79978. }
  79979. },
  79980. enumerable: true,
  79981. configurable: true
  79982. });
  79983. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  79984. get: function () {
  79985. return this._chromaticAberrationEnabled;
  79986. },
  79987. /**
  79988. * Enable or disable the chromaticAberration process from the pipeline
  79989. */
  79990. set: function (enabled) {
  79991. if (this._chromaticAberrationEnabled === enabled) {
  79992. return;
  79993. }
  79994. this._chromaticAberrationEnabled = enabled;
  79995. this._buildPipeline();
  79996. },
  79997. enumerable: true,
  79998. configurable: true
  79999. });
  80000. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  80001. get: function () {
  80002. return this._grainEnabled;
  80003. },
  80004. /**
  80005. * Enable or disable the grain process from the pipeline
  80006. */
  80007. set: function (enabled) {
  80008. if (this._grainEnabled === enabled) {
  80009. return;
  80010. }
  80011. this._grainEnabled = enabled;
  80012. this._buildPipeline();
  80013. },
  80014. enumerable: true,
  80015. configurable: true
  80016. });
  80017. /**
  80018. * Force the compilation of the entire pipeline.
  80019. */
  80020. DefaultRenderingPipeline.prototype.prepare = function () {
  80021. var previousState = this._buildAllowed;
  80022. this._buildAllowed = true;
  80023. this._buildPipeline();
  80024. this._buildAllowed = previousState;
  80025. };
  80026. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  80027. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  80028. if (this._hasCleared) {
  80029. postProcess.autoClear = false;
  80030. }
  80031. else {
  80032. postProcess.autoClear = true;
  80033. this._scene.autoClear = false;
  80034. this._hasCleared = true;
  80035. }
  80036. if (!skipTextureSharing) {
  80037. if (this._prevPrevPostProcess) {
  80038. postProcess.shareOutputWith(this._prevPrevPostProcess);
  80039. }
  80040. else {
  80041. postProcess.useOwnOutput();
  80042. }
  80043. if (this._prevPostProcess) {
  80044. this._prevPrevPostProcess = this._prevPostProcess;
  80045. }
  80046. this._prevPostProcess = postProcess;
  80047. }
  80048. };
  80049. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  80050. var _this = this;
  80051. if (!this._buildAllowed) {
  80052. return;
  80053. }
  80054. this._scene.autoClear = true;
  80055. var engine = this._scene.getEngine();
  80056. this._disposePostProcesses();
  80057. if (this._cameras !== null) {
  80058. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80059. // get back cameras to be used to reattach pipeline
  80060. this._cameras = this._camerasToBeAttached.slice();
  80061. }
  80062. this._reset();
  80063. this._prevPostProcess = null;
  80064. this._prevPrevPostProcess = null;
  80065. this._hasCleared = false;
  80066. if (this.depthOfFieldEnabled) {
  80067. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  80068. this.depthOfField.depthTexture = depthTexture;
  80069. if (!this.depthOfField._isReady()) {
  80070. this.depthOfField._updateEffects();
  80071. }
  80072. this.addEffect(this.depthOfField);
  80073. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  80074. }
  80075. if (this.bloomEnabled) {
  80076. if (!this.bloom._isReady()) {
  80077. this.bloom._updateEffects();
  80078. }
  80079. this.addEffect(this.bloom);
  80080. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  80081. }
  80082. if (this._imageProcessingEnabled) {
  80083. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80084. if (this._hdr) {
  80085. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  80086. this._setAutoClearAndTextureSharing(this.imageProcessing);
  80087. }
  80088. else {
  80089. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  80090. }
  80091. }
  80092. if (this.sharpenEnabled) {
  80093. if (!this.sharpen.isReady()) {
  80094. this.sharpen.updateEffect();
  80095. }
  80096. this.addEffect(this._sharpenEffect);
  80097. this._setAutoClearAndTextureSharing(this.sharpen);
  80098. }
  80099. if (this.grainEnabled) {
  80100. if (!this.grain.isReady()) {
  80101. this.grain.updateEffect();
  80102. }
  80103. this.addEffect(this._grainEffect);
  80104. this._setAutoClearAndTextureSharing(this.grain);
  80105. }
  80106. if (this.chromaticAberrationEnabled) {
  80107. if (!this.chromaticAberration.isReady()) {
  80108. this.chromaticAberration.updateEffect();
  80109. }
  80110. this.addEffect(this._chromaticAberrationEffect);
  80111. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  80112. }
  80113. if (this.fxaaEnabled) {
  80114. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80115. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  80116. this._setAutoClearAndTextureSharing(this.fxaa, true);
  80117. }
  80118. if (this._cameras !== null) {
  80119. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80120. }
  80121. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  80122. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80123. }
  80124. };
  80125. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  80126. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  80127. for (var i = 0; i < this._cameras.length; i++) {
  80128. var camera = this._cameras[i];
  80129. if (this.imageProcessing) {
  80130. this.imageProcessing.dispose(camera);
  80131. }
  80132. if (this.fxaa) {
  80133. this.fxaa.dispose(camera);
  80134. }
  80135. // These are created in the constructor and should not be disposed on every pipeline change
  80136. if (disposeNonRecreated) {
  80137. if (this.sharpen) {
  80138. this.sharpen.dispose(camera);
  80139. }
  80140. if (this.depthOfField) {
  80141. this.depthOfField.disposeEffects(camera);
  80142. }
  80143. if (this.bloom) {
  80144. this.bloom.disposeEffects(camera);
  80145. }
  80146. if (this.chromaticAberration) {
  80147. this.chromaticAberration.dispose(camera);
  80148. }
  80149. if (this.grain) {
  80150. this.grain.dispose(camera);
  80151. }
  80152. if (this._glowLayer) {
  80153. this._glowLayer.dispose();
  80154. }
  80155. }
  80156. }
  80157. this.imageProcessing = null;
  80158. this.fxaa = null;
  80159. if (disposeNonRecreated) {
  80160. this.sharpen = null;
  80161. this._sharpenEffect = null;
  80162. this.depthOfField = null;
  80163. this.bloom = null;
  80164. this.chromaticAberration = null;
  80165. this._chromaticAberrationEffect = null;
  80166. this.grain = null;
  80167. this._grainEffect = null;
  80168. this._glowLayer = null;
  80169. }
  80170. };
  80171. /**
  80172. * Adds a camera to the pipeline
  80173. * @param camera the camera to be added
  80174. */
  80175. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  80176. this._camerasToBeAttached.push(camera);
  80177. this._buildPipeline();
  80178. };
  80179. /**
  80180. * Removes a camera from the pipeline
  80181. * @param camera the camera to remove
  80182. */
  80183. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  80184. var index = this._camerasToBeAttached.indexOf(camera);
  80185. this._camerasToBeAttached.splice(index, 1);
  80186. this._buildPipeline();
  80187. };
  80188. /**
  80189. * Dispose of the pipeline and stop all post processes
  80190. */
  80191. DefaultRenderingPipeline.prototype.dispose = function () {
  80192. this._disposePostProcesses(true);
  80193. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80194. this._scene.autoClear = true;
  80195. if (this._resizeObserver) {
  80196. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  80197. this._resizeObserver = null;
  80198. }
  80199. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  80200. _super.prototype.dispose.call(this);
  80201. };
  80202. /**
  80203. * Serialize the rendering pipeline (Used when exporting)
  80204. * @returns the serialized object
  80205. */
  80206. DefaultRenderingPipeline.prototype.serialize = function () {
  80207. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80208. serializationObject.customType = "DefaultRenderingPipeline";
  80209. return serializationObject;
  80210. };
  80211. /**
  80212. * Parse the serialized pipeline
  80213. * @param source Source pipeline.
  80214. * @param scene The scene to load the pipeline to.
  80215. * @param rootUrl The URL of the serialized pipeline.
  80216. * @returns An instantiated pipeline from the serialized object.
  80217. */
  80218. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80219. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  80220. };
  80221. __decorate([
  80222. BABYLON.serialize()
  80223. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  80224. __decorate([
  80225. BABYLON.serialize()
  80226. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  80227. __decorate([
  80228. BABYLON.serialize()
  80229. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  80230. __decorate([
  80231. BABYLON.serialize()
  80232. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  80233. __decorate([
  80234. BABYLON.serialize()
  80235. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  80236. __decorate([
  80237. BABYLON.serialize()
  80238. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  80239. __decorate([
  80240. BABYLON.serialize()
  80241. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  80242. __decorate([
  80243. BABYLON.serialize()
  80244. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  80245. __decorate([
  80246. BABYLON.serialize()
  80247. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  80248. __decorate([
  80249. BABYLON.serialize()
  80250. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  80251. __decorate([
  80252. BABYLON.serialize()
  80253. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  80254. __decorate([
  80255. BABYLON.serialize()
  80256. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  80257. __decorate([
  80258. BABYLON.serialize()
  80259. ], DefaultRenderingPipeline.prototype, "samples", null);
  80260. __decorate([
  80261. BABYLON.serialize()
  80262. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  80263. __decorate([
  80264. BABYLON.serialize()
  80265. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  80266. __decorate([
  80267. BABYLON.serialize()
  80268. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  80269. __decorate([
  80270. BABYLON.serialize()
  80271. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  80272. return DefaultRenderingPipeline;
  80273. }(BABYLON.PostProcessRenderPipeline));
  80274. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  80275. })(BABYLON || (BABYLON = {}));
  80276. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  80277. var BABYLON;
  80278. (function (BABYLON) {
  80279. /**
  80280. * @hidden
  80281. */
  80282. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  80283. __extends(ImageProcessingConfigurationDefines, _super);
  80284. function ImageProcessingConfigurationDefines() {
  80285. var _this = _super.call(this) || this;
  80286. _this.IMAGEPROCESSING = false;
  80287. _this.VIGNETTE = false;
  80288. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80289. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80290. _this.TONEMAPPING = false;
  80291. _this.TONEMAPPING_ACES = false;
  80292. _this.CONTRAST = false;
  80293. _this.COLORCURVES = false;
  80294. _this.COLORGRADING = false;
  80295. _this.COLORGRADING3D = false;
  80296. _this.SAMPLER3DGREENDEPTH = false;
  80297. _this.SAMPLER3DBGRMAP = false;
  80298. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80299. _this.EXPOSURE = false;
  80300. _this.rebuild();
  80301. return _this;
  80302. }
  80303. return ImageProcessingConfigurationDefines;
  80304. }(BABYLON.MaterialDefines));
  80305. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  80306. /**
  80307. * This groups together the common properties used for image processing either in direct forward pass
  80308. * or through post processing effect depending on the use of the image processing pipeline in your scene
  80309. * or not.
  80310. */
  80311. var ImageProcessingConfiguration = /** @class */ (function () {
  80312. function ImageProcessingConfiguration() {
  80313. /**
  80314. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  80315. */
  80316. this.colorCurves = new BABYLON.ColorCurves();
  80317. this._colorCurvesEnabled = false;
  80318. this._colorGradingEnabled = false;
  80319. this._colorGradingWithGreenDepth = true;
  80320. this._colorGradingBGR = true;
  80321. /** @hidden */
  80322. this._exposure = 1.0;
  80323. this._toneMappingEnabled = false;
  80324. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  80325. this._contrast = 1.0;
  80326. /**
  80327. * Vignette stretch size.
  80328. */
  80329. this.vignetteStretch = 0;
  80330. /**
  80331. * Vignette centre X Offset.
  80332. */
  80333. this.vignetteCentreX = 0;
  80334. /**
  80335. * Vignette centre Y Offset.
  80336. */
  80337. this.vignetteCentreY = 0;
  80338. /**
  80339. * Vignette weight or intensity of the vignette effect.
  80340. */
  80341. this.vignetteWeight = 1.5;
  80342. /**
  80343. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80344. * if vignetteEnabled is set to true.
  80345. */
  80346. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80347. /**
  80348. * Camera field of view used by the Vignette effect.
  80349. */
  80350. this.vignetteCameraFov = 0.5;
  80351. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  80352. this._vignetteEnabled = false;
  80353. this._applyByPostProcess = false;
  80354. this._isEnabled = true;
  80355. /**
  80356. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  80357. */
  80358. this.onUpdateParameters = new BABYLON.Observable();
  80359. }
  80360. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  80361. /**
  80362. * Gets wether the color curves effect is enabled.
  80363. */
  80364. get: function () {
  80365. return this._colorCurvesEnabled;
  80366. },
  80367. /**
  80368. * Sets wether the color curves effect is enabled.
  80369. */
  80370. set: function (value) {
  80371. if (this._colorCurvesEnabled === value) {
  80372. return;
  80373. }
  80374. this._colorCurvesEnabled = value;
  80375. this._updateParameters();
  80376. },
  80377. enumerable: true,
  80378. configurable: true
  80379. });
  80380. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  80381. /**
  80382. * Gets wether the color grading effect is enabled.
  80383. */
  80384. get: function () {
  80385. return this._colorGradingEnabled;
  80386. },
  80387. /**
  80388. * Sets wether the color grading effect is enabled.
  80389. */
  80390. set: function (value) {
  80391. if (this._colorGradingEnabled === value) {
  80392. return;
  80393. }
  80394. this._colorGradingEnabled = value;
  80395. this._updateParameters();
  80396. },
  80397. enumerable: true,
  80398. configurable: true
  80399. });
  80400. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  80401. /**
  80402. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  80403. */
  80404. get: function () {
  80405. return this._colorGradingWithGreenDepth;
  80406. },
  80407. /**
  80408. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  80409. */
  80410. set: function (value) {
  80411. if (this._colorGradingWithGreenDepth === value) {
  80412. return;
  80413. }
  80414. this._colorGradingWithGreenDepth = value;
  80415. this._updateParameters();
  80416. },
  80417. enumerable: true,
  80418. configurable: true
  80419. });
  80420. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  80421. /**
  80422. * Gets wether the color grading texture contains BGR values.
  80423. */
  80424. get: function () {
  80425. return this._colorGradingBGR;
  80426. },
  80427. /**
  80428. * Sets wether the color grading texture contains BGR values.
  80429. */
  80430. set: function (value) {
  80431. if (this._colorGradingBGR === value) {
  80432. return;
  80433. }
  80434. this._colorGradingBGR = value;
  80435. this._updateParameters();
  80436. },
  80437. enumerable: true,
  80438. configurable: true
  80439. });
  80440. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  80441. /**
  80442. * Gets the Exposure used in the effect.
  80443. */
  80444. get: function () {
  80445. return this._exposure;
  80446. },
  80447. /**
  80448. * Sets the Exposure used in the effect.
  80449. */
  80450. set: function (value) {
  80451. if (this._exposure === value) {
  80452. return;
  80453. }
  80454. this._exposure = value;
  80455. this._updateParameters();
  80456. },
  80457. enumerable: true,
  80458. configurable: true
  80459. });
  80460. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  80461. /**
  80462. * Gets wether the tone mapping effect is enabled.
  80463. */
  80464. get: function () {
  80465. return this._toneMappingEnabled;
  80466. },
  80467. /**
  80468. * Sets wether the tone mapping effect is enabled.
  80469. */
  80470. set: function (value) {
  80471. if (this._toneMappingEnabled === value) {
  80472. return;
  80473. }
  80474. this._toneMappingEnabled = value;
  80475. this._updateParameters();
  80476. },
  80477. enumerable: true,
  80478. configurable: true
  80479. });
  80480. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  80481. /**
  80482. * Gets the type of tone mapping effect.
  80483. */
  80484. get: function () {
  80485. return this._toneMappingType;
  80486. },
  80487. /**
  80488. * Sets the type of tone mapping effect used in BabylonJS.
  80489. */
  80490. set: function (value) {
  80491. if (this._toneMappingType === value) {
  80492. return;
  80493. }
  80494. this._toneMappingType = value;
  80495. this._updateParameters();
  80496. },
  80497. enumerable: true,
  80498. configurable: true
  80499. });
  80500. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  80501. /**
  80502. * Gets the contrast used in the effect.
  80503. */
  80504. get: function () {
  80505. return this._contrast;
  80506. },
  80507. /**
  80508. * Sets the contrast used in the effect.
  80509. */
  80510. set: function (value) {
  80511. if (this._contrast === value) {
  80512. return;
  80513. }
  80514. this._contrast = value;
  80515. this._updateParameters();
  80516. },
  80517. enumerable: true,
  80518. configurable: true
  80519. });
  80520. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  80521. /**
  80522. * Gets the vignette blend mode allowing different kind of effect.
  80523. */
  80524. get: function () {
  80525. return this._vignetteBlendMode;
  80526. },
  80527. /**
  80528. * Sets the vignette blend mode allowing different kind of effect.
  80529. */
  80530. set: function (value) {
  80531. if (this._vignetteBlendMode === value) {
  80532. return;
  80533. }
  80534. this._vignetteBlendMode = value;
  80535. this._updateParameters();
  80536. },
  80537. enumerable: true,
  80538. configurable: true
  80539. });
  80540. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  80541. /**
  80542. * Gets wether the vignette effect is enabled.
  80543. */
  80544. get: function () {
  80545. return this._vignetteEnabled;
  80546. },
  80547. /**
  80548. * Sets wether the vignette effect is enabled.
  80549. */
  80550. set: function (value) {
  80551. if (this._vignetteEnabled === value) {
  80552. return;
  80553. }
  80554. this._vignetteEnabled = value;
  80555. this._updateParameters();
  80556. },
  80557. enumerable: true,
  80558. configurable: true
  80559. });
  80560. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  80561. /**
  80562. * Gets wether the image processing is applied through a post process or not.
  80563. */
  80564. get: function () {
  80565. return this._applyByPostProcess;
  80566. },
  80567. /**
  80568. * Sets wether the image processing is applied through a post process or not.
  80569. */
  80570. set: function (value) {
  80571. if (this._applyByPostProcess === value) {
  80572. return;
  80573. }
  80574. this._applyByPostProcess = value;
  80575. this._updateParameters();
  80576. },
  80577. enumerable: true,
  80578. configurable: true
  80579. });
  80580. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  80581. /**
  80582. * Gets wether the image processing is enabled or not.
  80583. */
  80584. get: function () {
  80585. return this._isEnabled;
  80586. },
  80587. /**
  80588. * Sets wether the image processing is enabled or not.
  80589. */
  80590. set: function (value) {
  80591. if (this._isEnabled === value) {
  80592. return;
  80593. }
  80594. this._isEnabled = value;
  80595. this._updateParameters();
  80596. },
  80597. enumerable: true,
  80598. configurable: true
  80599. });
  80600. /**
  80601. * Method called each time the image processing information changes requires to recompile the effect.
  80602. */
  80603. ImageProcessingConfiguration.prototype._updateParameters = function () {
  80604. this.onUpdateParameters.notifyObservers(this);
  80605. };
  80606. ImageProcessingConfiguration.prototype.getClassName = function () {
  80607. return "ImageProcessingConfiguration";
  80608. };
  80609. /**
  80610. * Prepare the list of uniforms associated with the Image Processing effects.
  80611. * @param uniformsList The list of uniforms used in the effect
  80612. * @param defines the list of defines currently in use
  80613. */
  80614. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  80615. if (defines.EXPOSURE) {
  80616. uniforms.push("exposureLinear");
  80617. }
  80618. if (defines.CONTRAST) {
  80619. uniforms.push("contrast");
  80620. }
  80621. if (defines.COLORGRADING) {
  80622. uniforms.push("colorTransformSettings");
  80623. }
  80624. if (defines.VIGNETTE) {
  80625. uniforms.push("vInverseScreenSize");
  80626. uniforms.push("vignetteSettings1");
  80627. uniforms.push("vignetteSettings2");
  80628. }
  80629. if (defines.COLORCURVES) {
  80630. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  80631. }
  80632. };
  80633. /**
  80634. * Prepare the list of samplers associated with the Image Processing effects.
  80635. * @param uniformsList The list of uniforms used in the effect
  80636. * @param defines the list of defines currently in use
  80637. */
  80638. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  80639. if (defines.COLORGRADING) {
  80640. samplersList.push("txColorTransform");
  80641. }
  80642. };
  80643. /**
  80644. * Prepare the list of defines associated to the shader.
  80645. * @param defines the list of defines to complete
  80646. */
  80647. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  80648. if (forPostProcess === void 0) { forPostProcess = false; }
  80649. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  80650. defines.VIGNETTE = false;
  80651. defines.TONEMAPPING = false;
  80652. defines.TONEMAPPING_ACES = false;
  80653. defines.CONTRAST = false;
  80654. defines.EXPOSURE = false;
  80655. defines.COLORCURVES = false;
  80656. defines.COLORGRADING = false;
  80657. defines.COLORGRADING3D = false;
  80658. defines.IMAGEPROCESSING = false;
  80659. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  80660. return;
  80661. }
  80662. defines.VIGNETTE = this.vignetteEnabled;
  80663. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  80664. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  80665. defines.TONEMAPPING = this.toneMappingEnabled;
  80666. switch (this._toneMappingType) {
  80667. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  80668. defines.TONEMAPPING_ACES = true;
  80669. break;
  80670. }
  80671. defines.CONTRAST = (this.contrast !== 1.0);
  80672. defines.EXPOSURE = (this.exposure !== 1.0);
  80673. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  80674. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  80675. if (defines.COLORGRADING) {
  80676. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  80677. }
  80678. else {
  80679. defines.COLORGRADING3D = false;
  80680. }
  80681. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  80682. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  80683. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  80684. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  80685. };
  80686. /**
  80687. * Returns true if all the image processing information are ready.
  80688. */
  80689. ImageProcessingConfiguration.prototype.isReady = function () {
  80690. // Color Grading texure can not be none blocking.
  80691. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  80692. };
  80693. /**
  80694. * Binds the image processing to the shader.
  80695. * @param effect The effect to bind to
  80696. */
  80697. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  80698. if (aspectRatio === void 0) { aspectRatio = 1; }
  80699. // Color Curves
  80700. if (this._colorCurvesEnabled && this.colorCurves) {
  80701. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  80702. }
  80703. // Vignette
  80704. if (this._vignetteEnabled) {
  80705. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  80706. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  80707. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  80708. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  80709. var vignetteScaleX = vignetteScaleY * aspectRatio;
  80710. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  80711. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  80712. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  80713. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  80714. var vignettePower = -2.0 * this.vignetteWeight;
  80715. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  80716. }
  80717. // Exposure
  80718. effect.setFloat("exposureLinear", this.exposure);
  80719. // Contrast
  80720. effect.setFloat("contrast", this.contrast);
  80721. // Color transform settings
  80722. if (this.colorGradingTexture) {
  80723. effect.setTexture("txColorTransform", this.colorGradingTexture);
  80724. var textureSize = this.colorGradingTexture.getSize().height;
  80725. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  80726. 0.5 / textureSize, // textureOffset
  80727. textureSize, // textureSize
  80728. this.colorGradingTexture.level // weight
  80729. );
  80730. }
  80731. };
  80732. /**
  80733. * Clones the current image processing instance.
  80734. * @return The cloned image processing
  80735. */
  80736. ImageProcessingConfiguration.prototype.clone = function () {
  80737. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  80738. };
  80739. /**
  80740. * Serializes the current image processing instance to a json representation.
  80741. * @return a JSON representation
  80742. */
  80743. ImageProcessingConfiguration.prototype.serialize = function () {
  80744. return BABYLON.SerializationHelper.Serialize(this);
  80745. };
  80746. /**
  80747. * Parses the image processing from a json representation.
  80748. * @param source the JSON source to parse
  80749. * @return The parsed image processing
  80750. */
  80751. ImageProcessingConfiguration.Parse = function (source) {
  80752. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  80753. };
  80754. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  80755. /**
  80756. * Used to apply the vignette as a mix with the pixel color.
  80757. */
  80758. get: function () {
  80759. return this._VIGNETTEMODE_MULTIPLY;
  80760. },
  80761. enumerable: true,
  80762. configurable: true
  80763. });
  80764. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  80765. /**
  80766. * Used to apply the vignette as a replacement of the pixel color.
  80767. */
  80768. get: function () {
  80769. return this._VIGNETTEMODE_OPAQUE;
  80770. },
  80771. enumerable: true,
  80772. configurable: true
  80773. });
  80774. /**
  80775. * Default tone mapping applied in BabylonJS.
  80776. */
  80777. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  80778. /**
  80779. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  80780. * to other engines rendering to increase portability.
  80781. */
  80782. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  80783. // Static constants associated to the image processing.
  80784. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  80785. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  80786. __decorate([
  80787. BABYLON.serializeAsColorCurves()
  80788. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  80789. __decorate([
  80790. BABYLON.serialize()
  80791. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  80792. __decorate([
  80793. BABYLON.serializeAsTexture()
  80794. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  80795. __decorate([
  80796. BABYLON.serialize()
  80797. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  80798. __decorate([
  80799. BABYLON.serialize()
  80800. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  80801. __decorate([
  80802. BABYLON.serialize()
  80803. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  80804. __decorate([
  80805. BABYLON.serialize()
  80806. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  80807. __decorate([
  80808. BABYLON.serialize()
  80809. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  80810. __decorate([
  80811. BABYLON.serialize()
  80812. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  80813. __decorate([
  80814. BABYLON.serialize()
  80815. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  80816. __decorate([
  80817. BABYLON.serialize()
  80818. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  80819. __decorate([
  80820. BABYLON.serialize()
  80821. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  80822. __decorate([
  80823. BABYLON.serialize()
  80824. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  80825. __decorate([
  80826. BABYLON.serialize()
  80827. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  80828. __decorate([
  80829. BABYLON.serializeAsColor4()
  80830. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  80831. __decorate([
  80832. BABYLON.serialize()
  80833. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  80834. __decorate([
  80835. BABYLON.serialize()
  80836. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  80837. __decorate([
  80838. BABYLON.serialize()
  80839. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  80840. __decorate([
  80841. BABYLON.serialize()
  80842. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  80843. __decorate([
  80844. BABYLON.serialize()
  80845. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  80846. return ImageProcessingConfiguration;
  80847. }());
  80848. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  80849. })(BABYLON || (BABYLON = {}));
  80850. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  80851. var BABYLON;
  80852. (function (BABYLON) {
  80853. /**
  80854. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  80855. * It can help converting any input color in a desired output one. This can then be used to create effects
  80856. * from sepia, black and white to sixties or futuristic rendering...
  80857. *
  80858. * The only supported format is currently 3dl.
  80859. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  80860. */
  80861. var ColorGradingTexture = /** @class */ (function (_super) {
  80862. __extends(ColorGradingTexture, _super);
  80863. /**
  80864. * Instantiates a ColorGradingTexture from the following parameters.
  80865. *
  80866. * @param url The location of the color gradind data (currently only supporting 3dl)
  80867. * @param scene The scene the texture will be used in
  80868. */
  80869. function ColorGradingTexture(url, scene) {
  80870. var _this = _super.call(this, scene) || this;
  80871. if (!url) {
  80872. return _this;
  80873. }
  80874. _this._engine = scene.getEngine();
  80875. _this._textureMatrix = BABYLON.Matrix.Identity();
  80876. _this.name = url;
  80877. _this.url = url;
  80878. _this.hasAlpha = false;
  80879. _this.isCube = false;
  80880. _this.is3D = _this._engine.webGLVersion > 1;
  80881. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80882. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80883. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80884. _this.anisotropicFilteringLevel = 1;
  80885. _this._texture = _this._getFromCache(url, true);
  80886. if (!_this._texture) {
  80887. if (!scene.useDelayedTextureLoading) {
  80888. _this.loadTexture();
  80889. }
  80890. else {
  80891. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80892. }
  80893. }
  80894. return _this;
  80895. }
  80896. /**
  80897. * Returns the texture matrix used in most of the material.
  80898. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  80899. */
  80900. ColorGradingTexture.prototype.getTextureMatrix = function () {
  80901. return this._textureMatrix;
  80902. };
  80903. /**
  80904. * Occurs when the file being loaded is a .3dl LUT file.
  80905. */
  80906. ColorGradingTexture.prototype.load3dlTexture = function () {
  80907. var engine = this._engine;
  80908. var texture;
  80909. if (engine.webGLVersion === 1) {
  80910. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80911. }
  80912. else {
  80913. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80914. }
  80915. this._texture = texture;
  80916. var callback = function (text) {
  80917. if (typeof text !== "string") {
  80918. return;
  80919. }
  80920. var data = null;
  80921. var tempData = null;
  80922. var line;
  80923. var lines = text.split('\n');
  80924. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  80925. var maxColor = 0;
  80926. for (var i = 0; i < lines.length; i++) {
  80927. line = lines[i];
  80928. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  80929. continue;
  80930. if (line.indexOf('#') === 0)
  80931. continue;
  80932. var words = line.split(" ");
  80933. if (size === 0) {
  80934. // Number of space + one
  80935. size = words.length;
  80936. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  80937. tempData = new Float32Array(size * size * size * 4);
  80938. continue;
  80939. }
  80940. if (size != 0) {
  80941. var r = Math.max(parseInt(words[0]), 0);
  80942. var g = Math.max(parseInt(words[1]), 0);
  80943. var b = Math.max(parseInt(words[2]), 0);
  80944. maxColor = Math.max(r, maxColor);
  80945. maxColor = Math.max(g, maxColor);
  80946. maxColor = Math.max(b, maxColor);
  80947. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  80948. if (tempData) {
  80949. tempData[pixelStorageIndex + 0] = r;
  80950. tempData[pixelStorageIndex + 1] = g;
  80951. tempData[pixelStorageIndex + 2] = b;
  80952. }
  80953. pixelIndexSlice++;
  80954. if (pixelIndexSlice % size == 0) {
  80955. pixelIndexH++;
  80956. pixelIndexSlice = 0;
  80957. if (pixelIndexH % size == 0) {
  80958. pixelIndexW++;
  80959. pixelIndexH = 0;
  80960. }
  80961. }
  80962. }
  80963. }
  80964. if (tempData && data) {
  80965. for (var i = 0; i < tempData.length; i++) {
  80966. if (i > 0 && (i + 1) % 4 === 0) {
  80967. data[i] = 255;
  80968. }
  80969. else {
  80970. var value = tempData[i];
  80971. data[i] = (value / maxColor * 255);
  80972. }
  80973. }
  80974. }
  80975. if (texture.is3D) {
  80976. texture.updateSize(size, size, size);
  80977. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80978. }
  80979. else {
  80980. texture.updateSize(size * size, size);
  80981. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80982. }
  80983. };
  80984. var scene = this.getScene();
  80985. if (scene) {
  80986. scene._loadFile(this.url, callback);
  80987. }
  80988. else {
  80989. this._engine._loadFile(this.url, callback);
  80990. }
  80991. return this._texture;
  80992. };
  80993. /**
  80994. * Starts the loading process of the texture.
  80995. */
  80996. ColorGradingTexture.prototype.loadTexture = function () {
  80997. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  80998. this.load3dlTexture();
  80999. }
  81000. };
  81001. /**
  81002. * Clones the color gradind texture.
  81003. */
  81004. ColorGradingTexture.prototype.clone = function () {
  81005. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  81006. // Base texture
  81007. newTexture.level = this.level;
  81008. return newTexture;
  81009. };
  81010. /**
  81011. * Called during delayed load for textures.
  81012. */
  81013. ColorGradingTexture.prototype.delayLoad = function () {
  81014. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81015. return;
  81016. }
  81017. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81018. this._texture = this._getFromCache(this.url, true);
  81019. if (!this._texture) {
  81020. this.loadTexture();
  81021. }
  81022. };
  81023. /**
  81024. * Parses a color grading texture serialized by Babylon.
  81025. * @param parsedTexture The texture information being parsedTexture
  81026. * @param scene The scene to load the texture in
  81027. * @param rootUrl The root url of the data assets to load
  81028. * @return A color gradind texture
  81029. */
  81030. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81031. var texture = null;
  81032. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81033. texture = new ColorGradingTexture(parsedTexture.name, scene);
  81034. texture.name = parsedTexture.name;
  81035. texture.level = parsedTexture.level;
  81036. }
  81037. return texture;
  81038. };
  81039. /**
  81040. * Serializes the LUT texture to json format.
  81041. */
  81042. ColorGradingTexture.prototype.serialize = function () {
  81043. if (!this.name) {
  81044. return null;
  81045. }
  81046. var serializationObject = {};
  81047. serializationObject.name = this.name;
  81048. serializationObject.level = this.level;
  81049. serializationObject.customType = "BABYLON.ColorGradingTexture";
  81050. return serializationObject;
  81051. };
  81052. /**
  81053. * Empty line regex stored for GC.
  81054. */
  81055. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  81056. return ColorGradingTexture;
  81057. }(BABYLON.BaseTexture));
  81058. BABYLON.ColorGradingTexture = ColorGradingTexture;
  81059. })(BABYLON || (BABYLON = {}));
  81060. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  81061. var BABYLON;
  81062. (function (BABYLON) {
  81063. /**
  81064. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81065. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81066. * 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;
  81067. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81068. */
  81069. var ColorCurves = /** @class */ (function () {
  81070. function ColorCurves() {
  81071. this._dirty = true;
  81072. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  81073. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  81074. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81075. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  81076. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81077. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  81078. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  81079. this._globalHue = 30;
  81080. this._globalDensity = 0;
  81081. this._globalSaturation = 0;
  81082. this._globalExposure = 0;
  81083. this._highlightsHue = 30;
  81084. this._highlightsDensity = 0;
  81085. this._highlightsSaturation = 0;
  81086. this._highlightsExposure = 0;
  81087. this._midtonesHue = 30;
  81088. this._midtonesDensity = 0;
  81089. this._midtonesSaturation = 0;
  81090. this._midtonesExposure = 0;
  81091. this._shadowsHue = 30;
  81092. this._shadowsDensity = 0;
  81093. this._shadowsSaturation = 0;
  81094. this._shadowsExposure = 0;
  81095. }
  81096. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  81097. /**
  81098. * Gets the global Hue value.
  81099. * 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).
  81100. */
  81101. get: function () {
  81102. return this._globalHue;
  81103. },
  81104. /**
  81105. * Sets the global Hue value.
  81106. * 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).
  81107. */
  81108. set: function (value) {
  81109. this._globalHue = value;
  81110. this._dirty = true;
  81111. },
  81112. enumerable: true,
  81113. configurable: true
  81114. });
  81115. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  81116. /**
  81117. * Gets the global Density value.
  81118. * 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.
  81119. * Values less than zero provide a filter of opposite hue.
  81120. */
  81121. get: function () {
  81122. return this._globalDensity;
  81123. },
  81124. /**
  81125. * Sets the global Density value.
  81126. * 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.
  81127. * Values less than zero provide a filter of opposite hue.
  81128. */
  81129. set: function (value) {
  81130. this._globalDensity = value;
  81131. this._dirty = true;
  81132. },
  81133. enumerable: true,
  81134. configurable: true
  81135. });
  81136. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  81137. /**
  81138. * Gets the global Saturation value.
  81139. * 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.
  81140. */
  81141. get: function () {
  81142. return this._globalSaturation;
  81143. },
  81144. /**
  81145. * Sets the global Saturation value.
  81146. * 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.
  81147. */
  81148. set: function (value) {
  81149. this._globalSaturation = value;
  81150. this._dirty = true;
  81151. },
  81152. enumerable: true,
  81153. configurable: true
  81154. });
  81155. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  81156. /**
  81157. * Gets the global Exposure value.
  81158. * 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.
  81159. */
  81160. get: function () {
  81161. return this._globalExposure;
  81162. },
  81163. /**
  81164. * Sets the global Exposure value.
  81165. * 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.
  81166. */
  81167. set: function (value) {
  81168. this._globalExposure = value;
  81169. this._dirty = true;
  81170. },
  81171. enumerable: true,
  81172. configurable: true
  81173. });
  81174. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  81175. /**
  81176. * Gets the highlights Hue value.
  81177. * 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).
  81178. */
  81179. get: function () {
  81180. return this._highlightsHue;
  81181. },
  81182. /**
  81183. * Sets the highlights Hue value.
  81184. * 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).
  81185. */
  81186. set: function (value) {
  81187. this._highlightsHue = value;
  81188. this._dirty = true;
  81189. },
  81190. enumerable: true,
  81191. configurable: true
  81192. });
  81193. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  81194. /**
  81195. * Gets the highlights Density value.
  81196. * 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.
  81197. * Values less than zero provide a filter of opposite hue.
  81198. */
  81199. get: function () {
  81200. return this._highlightsDensity;
  81201. },
  81202. /**
  81203. * Sets the highlights Density value.
  81204. * 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.
  81205. * Values less than zero provide a filter of opposite hue.
  81206. */
  81207. set: function (value) {
  81208. this._highlightsDensity = value;
  81209. this._dirty = true;
  81210. },
  81211. enumerable: true,
  81212. configurable: true
  81213. });
  81214. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  81215. /**
  81216. * Gets the highlights Saturation value.
  81217. * 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.
  81218. */
  81219. get: function () {
  81220. return this._highlightsSaturation;
  81221. },
  81222. /**
  81223. * Sets the highlights Saturation value.
  81224. * 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.
  81225. */
  81226. set: function (value) {
  81227. this._highlightsSaturation = value;
  81228. this._dirty = true;
  81229. },
  81230. enumerable: true,
  81231. configurable: true
  81232. });
  81233. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  81234. /**
  81235. * Gets the highlights Exposure value.
  81236. * 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.
  81237. */
  81238. get: function () {
  81239. return this._highlightsExposure;
  81240. },
  81241. /**
  81242. * Sets the highlights Exposure value.
  81243. * 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.
  81244. */
  81245. set: function (value) {
  81246. this._highlightsExposure = value;
  81247. this._dirty = true;
  81248. },
  81249. enumerable: true,
  81250. configurable: true
  81251. });
  81252. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  81253. /**
  81254. * Gets the midtones Hue value.
  81255. * 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).
  81256. */
  81257. get: function () {
  81258. return this._midtonesHue;
  81259. },
  81260. /**
  81261. * Sets the midtones Hue value.
  81262. * 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).
  81263. */
  81264. set: function (value) {
  81265. this._midtonesHue = value;
  81266. this._dirty = true;
  81267. },
  81268. enumerable: true,
  81269. configurable: true
  81270. });
  81271. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  81272. /**
  81273. * Gets the midtones Density value.
  81274. * 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.
  81275. * Values less than zero provide a filter of opposite hue.
  81276. */
  81277. get: function () {
  81278. return this._midtonesDensity;
  81279. },
  81280. /**
  81281. * Sets the midtones Density value.
  81282. * 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.
  81283. * Values less than zero provide a filter of opposite hue.
  81284. */
  81285. set: function (value) {
  81286. this._midtonesDensity = value;
  81287. this._dirty = true;
  81288. },
  81289. enumerable: true,
  81290. configurable: true
  81291. });
  81292. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  81293. /**
  81294. * Gets the midtones Saturation value.
  81295. * 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.
  81296. */
  81297. get: function () {
  81298. return this._midtonesSaturation;
  81299. },
  81300. /**
  81301. * Sets the midtones Saturation value.
  81302. * 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.
  81303. */
  81304. set: function (value) {
  81305. this._midtonesSaturation = value;
  81306. this._dirty = true;
  81307. },
  81308. enumerable: true,
  81309. configurable: true
  81310. });
  81311. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  81312. /**
  81313. * Gets the midtones Exposure value.
  81314. * 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.
  81315. */
  81316. get: function () {
  81317. return this._midtonesExposure;
  81318. },
  81319. /**
  81320. * Sets the midtones Exposure value.
  81321. * 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.
  81322. */
  81323. set: function (value) {
  81324. this._midtonesExposure = value;
  81325. this._dirty = true;
  81326. },
  81327. enumerable: true,
  81328. configurable: true
  81329. });
  81330. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  81331. /**
  81332. * Gets the shadows Hue value.
  81333. * 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).
  81334. */
  81335. get: function () {
  81336. return this._shadowsHue;
  81337. },
  81338. /**
  81339. * Sets the shadows Hue value.
  81340. * 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).
  81341. */
  81342. set: function (value) {
  81343. this._shadowsHue = value;
  81344. this._dirty = true;
  81345. },
  81346. enumerable: true,
  81347. configurable: true
  81348. });
  81349. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  81350. /**
  81351. * Gets the shadows Density value.
  81352. * 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.
  81353. * Values less than zero provide a filter of opposite hue.
  81354. */
  81355. get: function () {
  81356. return this._shadowsDensity;
  81357. },
  81358. /**
  81359. * Sets the shadows Density value.
  81360. * 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.
  81361. * Values less than zero provide a filter of opposite hue.
  81362. */
  81363. set: function (value) {
  81364. this._shadowsDensity = value;
  81365. this._dirty = true;
  81366. },
  81367. enumerable: true,
  81368. configurable: true
  81369. });
  81370. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  81371. /**
  81372. * Gets the shadows Saturation value.
  81373. * 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.
  81374. */
  81375. get: function () {
  81376. return this._shadowsSaturation;
  81377. },
  81378. /**
  81379. * Sets the shadows Saturation value.
  81380. * 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.
  81381. */
  81382. set: function (value) {
  81383. this._shadowsSaturation = value;
  81384. this._dirty = true;
  81385. },
  81386. enumerable: true,
  81387. configurable: true
  81388. });
  81389. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  81390. /**
  81391. * Gets the shadows Exposure value.
  81392. * 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.
  81393. */
  81394. get: function () {
  81395. return this._shadowsExposure;
  81396. },
  81397. /**
  81398. * Sets the shadows Exposure value.
  81399. * 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.
  81400. */
  81401. set: function (value) {
  81402. this._shadowsExposure = value;
  81403. this._dirty = true;
  81404. },
  81405. enumerable: true,
  81406. configurable: true
  81407. });
  81408. ColorCurves.prototype.getClassName = function () {
  81409. return "ColorCurves";
  81410. };
  81411. /**
  81412. * Binds the color curves to the shader.
  81413. * @param colorCurves The color curve to bind
  81414. * @param effect The effect to bind to
  81415. */
  81416. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  81417. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  81418. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  81419. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  81420. if (colorCurves._dirty) {
  81421. colorCurves._dirty = false;
  81422. // Fill in global info.
  81423. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  81424. // Compute highlights info.
  81425. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  81426. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  81427. // Compute midtones info.
  81428. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  81429. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  81430. // Compute shadows info.
  81431. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  81432. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  81433. // Compute deltas (neutral is midtones).
  81434. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  81435. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  81436. }
  81437. if (effect) {
  81438. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  81439. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  81440. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  81441. }
  81442. };
  81443. /**
  81444. * Prepare the list of uniforms associated with the ColorCurves effects.
  81445. * @param uniformsList The list of uniforms used in the effect
  81446. */
  81447. ColorCurves.PrepareUniforms = function (uniformsList) {
  81448. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  81449. };
  81450. /**
  81451. * Returns color grading data based on a hue, density, saturation and exposure value.
  81452. * @param filterHue The hue of the color filter.
  81453. * @param filterDensity The density of the color filter.
  81454. * @param saturation The saturation.
  81455. * @param exposure The exposure.
  81456. * @param result The result data container.
  81457. */
  81458. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  81459. if (hue == null) {
  81460. return;
  81461. }
  81462. hue = ColorCurves.clamp(hue, 0, 360);
  81463. density = ColorCurves.clamp(density, -100, 100);
  81464. saturation = ColorCurves.clamp(saturation, -100, 100);
  81465. exposure = ColorCurves.clamp(exposure, -100, 100);
  81466. // Remap the slider/config filter density with non-linear mapping and also scale by half
  81467. // so that the maximum filter density is only 50% control. This provides fine control
  81468. // for small values and reasonable range.
  81469. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  81470. density *= 0.5;
  81471. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  81472. if (density < 0) {
  81473. density *= -1;
  81474. hue = (hue + 180) % 360;
  81475. }
  81476. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  81477. result.scaleToRef(2, result);
  81478. result.a = 1 + 0.01 * saturation;
  81479. };
  81480. /**
  81481. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  81482. * @param value The input slider value in range [-100,100].
  81483. * @returns Adjusted value.
  81484. */
  81485. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  81486. value /= 100;
  81487. var x = Math.abs(value);
  81488. x = Math.pow(x, 2);
  81489. if (value < 0) {
  81490. x *= -1;
  81491. }
  81492. x *= 100;
  81493. return x;
  81494. };
  81495. /**
  81496. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  81497. * @param hue The hue (H) input.
  81498. * @param saturation The saturation (S) input.
  81499. * @param brightness The brightness (B) input.
  81500. * @result An RGBA color represented as Vector4.
  81501. */
  81502. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  81503. var h = ColorCurves.clamp(hue, 0, 360);
  81504. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  81505. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  81506. if (s === 0) {
  81507. result.r = v;
  81508. result.g = v;
  81509. result.b = v;
  81510. }
  81511. else {
  81512. // sector 0 to 5
  81513. h /= 60;
  81514. var i = Math.floor(h);
  81515. // fractional part of h
  81516. var f = h - i;
  81517. var p = v * (1 - s);
  81518. var q = v * (1 - s * f);
  81519. var t = v * (1 - s * (1 - f));
  81520. switch (i) {
  81521. case 0:
  81522. result.r = v;
  81523. result.g = t;
  81524. result.b = p;
  81525. break;
  81526. case 1:
  81527. result.r = q;
  81528. result.g = v;
  81529. result.b = p;
  81530. break;
  81531. case 2:
  81532. result.r = p;
  81533. result.g = v;
  81534. result.b = t;
  81535. break;
  81536. case 3:
  81537. result.r = p;
  81538. result.g = q;
  81539. result.b = v;
  81540. break;
  81541. case 4:
  81542. result.r = t;
  81543. result.g = p;
  81544. result.b = v;
  81545. break;
  81546. default: // case 5:
  81547. result.r = v;
  81548. result.g = p;
  81549. result.b = q;
  81550. break;
  81551. }
  81552. }
  81553. result.a = 1;
  81554. };
  81555. /**
  81556. * Returns a value clamped between min and max
  81557. * @param value The value to clamp
  81558. * @param min The minimum of value
  81559. * @param max The maximum of value
  81560. * @returns The clamped value.
  81561. */
  81562. ColorCurves.clamp = function (value, min, max) {
  81563. return Math.min(Math.max(value, min), max);
  81564. };
  81565. /**
  81566. * Clones the current color curve instance.
  81567. * @return The cloned curves
  81568. */
  81569. ColorCurves.prototype.clone = function () {
  81570. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  81571. };
  81572. /**
  81573. * Serializes the current color curve instance to a json representation.
  81574. * @return a JSON representation
  81575. */
  81576. ColorCurves.prototype.serialize = function () {
  81577. return BABYLON.SerializationHelper.Serialize(this);
  81578. };
  81579. /**
  81580. * Parses the color curve from a json representation.
  81581. * @param source the JSON source to parse
  81582. * @return The parsed curves
  81583. */
  81584. ColorCurves.Parse = function (source) {
  81585. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  81586. };
  81587. __decorate([
  81588. BABYLON.serialize()
  81589. ], ColorCurves.prototype, "_globalHue", void 0);
  81590. __decorate([
  81591. BABYLON.serialize()
  81592. ], ColorCurves.prototype, "_globalDensity", void 0);
  81593. __decorate([
  81594. BABYLON.serialize()
  81595. ], ColorCurves.prototype, "_globalSaturation", void 0);
  81596. __decorate([
  81597. BABYLON.serialize()
  81598. ], ColorCurves.prototype, "_globalExposure", void 0);
  81599. __decorate([
  81600. BABYLON.serialize()
  81601. ], ColorCurves.prototype, "_highlightsHue", void 0);
  81602. __decorate([
  81603. BABYLON.serialize()
  81604. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  81605. __decorate([
  81606. BABYLON.serialize()
  81607. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  81608. __decorate([
  81609. BABYLON.serialize()
  81610. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  81611. __decorate([
  81612. BABYLON.serialize()
  81613. ], ColorCurves.prototype, "_midtonesHue", void 0);
  81614. __decorate([
  81615. BABYLON.serialize()
  81616. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  81617. __decorate([
  81618. BABYLON.serialize()
  81619. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  81620. __decorate([
  81621. BABYLON.serialize()
  81622. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  81623. return ColorCurves;
  81624. }());
  81625. BABYLON.ColorCurves = ColorCurves;
  81626. })(BABYLON || (BABYLON = {}));
  81627. //# sourceMappingURL=babylon.colorCurves.js.map
  81628. var BABYLON;
  81629. (function (BABYLON) {
  81630. var RefractionPostProcess = /** @class */ (function (_super) {
  81631. __extends(RefractionPostProcess, _super);
  81632. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  81633. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  81634. _this.color = color;
  81635. _this.depth = depth;
  81636. _this.colorLevel = colorLevel;
  81637. _this._ownRefractionTexture = true;
  81638. _this.onActivateObservable.add(function (cam) {
  81639. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  81640. });
  81641. _this.onApplyObservable.add(function (effect) {
  81642. effect.setColor3("baseColor", _this.color);
  81643. effect.setFloat("depth", _this.depth);
  81644. effect.setFloat("colorLevel", _this.colorLevel);
  81645. effect.setTexture("refractionSampler", _this._refTexture);
  81646. });
  81647. return _this;
  81648. }
  81649. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  81650. /**
  81651. * Gets or sets the refraction texture
  81652. * Please note that you are responsible for disposing the texture if you set it manually
  81653. */
  81654. get: function () {
  81655. return this._refTexture;
  81656. },
  81657. set: function (value) {
  81658. if (this._refTexture && this._ownRefractionTexture) {
  81659. this._refTexture.dispose();
  81660. }
  81661. this._refTexture = value;
  81662. this._ownRefractionTexture = false;
  81663. },
  81664. enumerable: true,
  81665. configurable: true
  81666. });
  81667. // Methods
  81668. RefractionPostProcess.prototype.dispose = function (camera) {
  81669. if (this._refTexture && this._ownRefractionTexture) {
  81670. this._refTexture.dispose();
  81671. this._refTexture = null;
  81672. }
  81673. _super.prototype.dispose.call(this, camera);
  81674. };
  81675. return RefractionPostProcess;
  81676. }(BABYLON.PostProcess));
  81677. BABYLON.RefractionPostProcess = RefractionPostProcess;
  81678. })(BABYLON || (BABYLON = {}));
  81679. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  81680. var BABYLON;
  81681. (function (BABYLON) {
  81682. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  81683. __extends(BlackAndWhitePostProcess, _super);
  81684. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  81685. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  81686. _this.degree = 1;
  81687. _this.onApplyObservable.add(function (effect) {
  81688. effect.setFloat("degree", _this.degree);
  81689. });
  81690. return _this;
  81691. }
  81692. return BlackAndWhitePostProcess;
  81693. }(BABYLON.PostProcess));
  81694. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  81695. })(BABYLON || (BABYLON = {}));
  81696. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  81697. var BABYLON;
  81698. (function (BABYLON) {
  81699. /**
  81700. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  81701. * input texture to perform effects such as edge detection or sharpening
  81702. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  81703. */
  81704. var ConvolutionPostProcess = /** @class */ (function (_super) {
  81705. __extends(ConvolutionPostProcess, _super);
  81706. /**
  81707. * Creates a new instance ConvolutionPostProcess
  81708. * @param name The name of the effect.
  81709. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  81710. * @param options The required width/height ratio to downsize to before computing the render pass.
  81711. * @param camera The camera to apply the render pass to.
  81712. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81713. * @param engine The engine which the post process will be applied. (default: current engine)
  81714. * @param reusable If the post process can be reused on the same frame. (default: false)
  81715. * @param textureType Type of textures used when performing the post process. (default: 0)
  81716. */
  81717. function ConvolutionPostProcess(name,
  81718. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  81719. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  81720. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81721. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81722. _this.kernel = kernel;
  81723. _this.onApply = function (effect) {
  81724. effect.setFloat2("screenSize", _this.width, _this.height);
  81725. effect.setArray("kernel", _this.kernel);
  81726. };
  81727. return _this;
  81728. }
  81729. // Statics
  81730. /**
  81731. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81732. */
  81733. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  81734. /**
  81735. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81736. */
  81737. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  81738. /**
  81739. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81740. */
  81741. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  81742. /**
  81743. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81744. */
  81745. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  81746. /**
  81747. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81748. */
  81749. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  81750. /**
  81751. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81752. */
  81753. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  81754. return ConvolutionPostProcess;
  81755. }(BABYLON.PostProcess));
  81756. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  81757. })(BABYLON || (BABYLON = {}));
  81758. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  81759. var BABYLON;
  81760. (function (BABYLON) {
  81761. var FilterPostProcess = /** @class */ (function (_super) {
  81762. __extends(FilterPostProcess, _super);
  81763. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  81764. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  81765. _this.kernelMatrix = kernelMatrix;
  81766. _this.onApply = function (effect) {
  81767. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  81768. };
  81769. return _this;
  81770. }
  81771. return FilterPostProcess;
  81772. }(BABYLON.PostProcess));
  81773. BABYLON.FilterPostProcess = FilterPostProcess;
  81774. })(BABYLON || (BABYLON = {}));
  81775. //# sourceMappingURL=babylon.filterPostProcess.js.map
  81776. var BABYLON;
  81777. (function (BABYLON) {
  81778. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  81779. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  81780. __extends(VolumetricLightScatteringPostProcess, _super);
  81781. /**
  81782. * @constructor
  81783. * @param {string} name - The post-process name
  81784. * @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)
  81785. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  81786. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  81787. * @param {number} samples - The post-process quality, default 100
  81788. * @param {number} samplingMode - The post-process filtering mode
  81789. * @param {BABYLON.Engine} engine - The babylon engine
  81790. * @param {boolean} reusable - If the post-process is reusable
  81791. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  81792. */
  81793. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  81794. if (samples === void 0) { samples = 100; }
  81795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81796. 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;
  81797. _this._screenCoordinates = BABYLON.Vector2.Zero();
  81798. /**
  81799. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  81800. */
  81801. _this.customMeshPosition = BABYLON.Vector3.Zero();
  81802. /**
  81803. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  81804. */
  81805. _this.useCustomMeshPosition = false;
  81806. /**
  81807. * If the post-process should inverse the light scattering direction
  81808. */
  81809. _this.invert = true;
  81810. /**
  81811. * Array containing the excluded meshes not rendered in the internal pass
  81812. */
  81813. _this.excludedMeshes = new Array();
  81814. /**
  81815. * Controls the overall intensity of the post-process
  81816. */
  81817. _this.exposure = 0.3;
  81818. /**
  81819. * Dissipates each sample's contribution in range [0, 1]
  81820. */
  81821. _this.decay = 0.96815;
  81822. /**
  81823. * Controls the overall intensity of each sample
  81824. */
  81825. _this.weight = 0.58767;
  81826. /**
  81827. * Controls the density of each sample
  81828. */
  81829. _this.density = 0.926;
  81830. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  81831. engine = scene.getEngine();
  81832. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  81833. // Configure mesh
  81834. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  81835. // Configure
  81836. _this._createPass(scene, ratio.passRatio || ratio);
  81837. _this.onActivate = function (camera) {
  81838. if (!_this.isSupported) {
  81839. _this.dispose(camera);
  81840. }
  81841. _this.onActivate = null;
  81842. };
  81843. _this.onApplyObservable.add(function (effect) {
  81844. _this._updateMeshScreenCoordinates(scene);
  81845. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  81846. effect.setFloat("exposure", _this.exposure);
  81847. effect.setFloat("decay", _this.decay);
  81848. effect.setFloat("weight", _this.weight);
  81849. effect.setFloat("density", _this.density);
  81850. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  81851. });
  81852. return _this;
  81853. }
  81854. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  81855. get: function () {
  81856. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81857. return false;
  81858. },
  81859. set: function (useDiffuseColor) {
  81860. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81861. },
  81862. enumerable: true,
  81863. configurable: true
  81864. });
  81865. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  81866. return "VolumetricLightScatteringPostProcess";
  81867. };
  81868. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  81869. var mesh = subMesh.getMesh();
  81870. // Render this.mesh as default
  81871. if (mesh === this.mesh && mesh.material) {
  81872. return mesh.material.isReady(mesh);
  81873. }
  81874. var defines = [];
  81875. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81876. var material = subMesh.getMaterial();
  81877. // Alpha test
  81878. if (material) {
  81879. if (material.needAlphaTesting()) {
  81880. defines.push("#define ALPHATEST");
  81881. }
  81882. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81883. attribs.push(BABYLON.VertexBuffer.UVKind);
  81884. defines.push("#define UV1");
  81885. }
  81886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81887. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81888. defines.push("#define UV2");
  81889. }
  81890. }
  81891. // Bones
  81892. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81895. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81896. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81897. }
  81898. else {
  81899. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81900. }
  81901. // Instances
  81902. if (useInstances) {
  81903. defines.push("#define INSTANCES");
  81904. attribs.push("world0");
  81905. attribs.push("world1");
  81906. attribs.push("world2");
  81907. attribs.push("world3");
  81908. }
  81909. // Get correct effect
  81910. var join = defines.join("\n");
  81911. if (this._cachedDefines !== join) {
  81912. this._cachedDefines = join;
  81913. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  81914. }
  81915. return this._volumetricLightScatteringPass.isReady();
  81916. };
  81917. /**
  81918. * Sets the new light position for light scattering effect
  81919. * @param {BABYLON.Vector3} The new custom light position
  81920. */
  81921. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  81922. this.customMeshPosition = position;
  81923. };
  81924. /**
  81925. * Returns the light position for light scattering effect
  81926. * @return {BABYLON.Vector3} The custom light position
  81927. */
  81928. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  81929. return this.customMeshPosition;
  81930. };
  81931. /**
  81932. * Disposes the internal assets and detaches the post-process from the camera
  81933. */
  81934. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  81935. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  81936. if (rttIndex !== -1) {
  81937. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  81938. }
  81939. this._volumetricLightScatteringRTT.dispose();
  81940. _super.prototype.dispose.call(this, camera);
  81941. };
  81942. /**
  81943. * Returns the render target texture used by the post-process
  81944. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  81945. */
  81946. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  81947. return this._volumetricLightScatteringRTT;
  81948. };
  81949. // Private methods
  81950. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  81951. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  81952. return true;
  81953. }
  81954. return false;
  81955. };
  81956. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  81957. var _this = this;
  81958. var engine = scene.getEngine();
  81959. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81960. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81961. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81962. this._volumetricLightScatteringRTT.renderList = null;
  81963. this._volumetricLightScatteringRTT.renderParticles = false;
  81964. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  81965. var camera = this.getCamera();
  81966. if (camera) {
  81967. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81968. }
  81969. else {
  81970. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81971. }
  81972. // Custom render function for submeshes
  81973. var renderSubMesh = function (subMesh) {
  81974. var mesh = subMesh.getRenderingMesh();
  81975. if (_this._meshExcluded(mesh)) {
  81976. return;
  81977. }
  81978. var material = subMesh.getMaterial();
  81979. if (!material) {
  81980. return;
  81981. }
  81982. var scene = mesh.getScene();
  81983. var engine = scene.getEngine();
  81984. // Culling
  81985. engine.setState(material.backFaceCulling);
  81986. // Managing instances
  81987. var batch = mesh._getInstancesRenderList(subMesh._id);
  81988. if (batch.mustReturn) {
  81989. return;
  81990. }
  81991. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81992. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  81993. var effect = _this._volumetricLightScatteringPass;
  81994. if (mesh === _this.mesh) {
  81995. if (subMesh.effect) {
  81996. effect = subMesh.effect;
  81997. }
  81998. else {
  81999. effect = material.getEffect();
  82000. }
  82001. }
  82002. engine.enableEffect(effect);
  82003. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  82004. if (mesh === _this.mesh) {
  82005. material.bind(mesh.getWorldMatrix(), mesh);
  82006. }
  82007. else {
  82008. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  82009. // Alpha test
  82010. if (material && material.needAlphaTesting()) {
  82011. var alphaTexture = material.getAlphaTestTexture();
  82012. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  82013. if (alphaTexture) {
  82014. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82015. }
  82016. }
  82017. // Bones
  82018. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82019. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82020. }
  82021. }
  82022. // Draw
  82023. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  82024. }
  82025. };
  82026. // Render target texture callbacks
  82027. var savedSceneClearColor;
  82028. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  82029. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  82030. savedSceneClearColor = scene.clearColor;
  82031. scene.clearColor = sceneClearColor;
  82032. });
  82033. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  82034. scene.clearColor = savedSceneClearColor;
  82035. });
  82036. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82037. var engine = scene.getEngine();
  82038. var index;
  82039. if (depthOnlySubMeshes.length) {
  82040. engine.setColorWrite(false);
  82041. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82042. renderSubMesh(depthOnlySubMeshes.data[index]);
  82043. }
  82044. engine.setColorWrite(true);
  82045. }
  82046. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82047. renderSubMesh(opaqueSubMeshes.data[index]);
  82048. }
  82049. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82050. renderSubMesh(alphaTestSubMeshes.data[index]);
  82051. }
  82052. if (transparentSubMeshes.length) {
  82053. // Sort sub meshes
  82054. for (index = 0; index < transparentSubMeshes.length; index++) {
  82055. var submesh = transparentSubMeshes.data[index];
  82056. var boundingInfo = submesh.getBoundingInfo();
  82057. if (boundingInfo && scene.activeCamera) {
  82058. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  82059. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  82060. }
  82061. }
  82062. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  82063. sortedArray.sort(function (a, b) {
  82064. // Alpha index first
  82065. if (a._alphaIndex > b._alphaIndex) {
  82066. return 1;
  82067. }
  82068. if (a._alphaIndex < b._alphaIndex) {
  82069. return -1;
  82070. }
  82071. // Then distance to camera
  82072. if (a._distanceToCamera < b._distanceToCamera) {
  82073. return 1;
  82074. }
  82075. if (a._distanceToCamera > b._distanceToCamera) {
  82076. return -1;
  82077. }
  82078. return 0;
  82079. });
  82080. // Render sub meshes
  82081. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  82082. for (index = 0; index < sortedArray.length; index++) {
  82083. renderSubMesh(sortedArray[index]);
  82084. }
  82085. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82086. }
  82087. };
  82088. };
  82089. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  82090. var transform = scene.getTransformMatrix();
  82091. var meshPosition;
  82092. if (this.useCustomMeshPosition) {
  82093. meshPosition = this.customMeshPosition;
  82094. }
  82095. else if (this.attachedNode) {
  82096. meshPosition = this.attachedNode.position;
  82097. }
  82098. else {
  82099. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  82100. }
  82101. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  82102. this._screenCoordinates.x = pos.x / this._viewPort.width;
  82103. this._screenCoordinates.y = pos.y / this._viewPort.height;
  82104. if (this.invert)
  82105. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  82106. };
  82107. // Static methods
  82108. /**
  82109. * Creates a default mesh for the Volumeric Light Scattering post-process
  82110. * @param {string} The mesh name
  82111. * @param {BABYLON.Scene} The scene where to create the mesh
  82112. * @return {BABYLON.Mesh} the default mesh
  82113. */
  82114. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  82115. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  82116. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  82117. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  82118. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  82119. mesh.material = material;
  82120. return mesh;
  82121. };
  82122. __decorate([
  82123. BABYLON.serializeAsVector3()
  82124. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  82125. __decorate([
  82126. BABYLON.serialize()
  82127. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  82128. __decorate([
  82129. BABYLON.serialize()
  82130. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  82131. __decorate([
  82132. BABYLON.serializeAsMeshReference()
  82133. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  82134. __decorate([
  82135. BABYLON.serialize()
  82136. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  82137. __decorate([
  82138. BABYLON.serialize()
  82139. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  82140. __decorate([
  82141. BABYLON.serialize()
  82142. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  82143. __decorate([
  82144. BABYLON.serialize()
  82145. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  82146. __decorate([
  82147. BABYLON.serialize()
  82148. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  82149. return VolumetricLightScatteringPostProcess;
  82150. }(BABYLON.PostProcess));
  82151. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  82152. })(BABYLON || (BABYLON = {}));
  82153. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  82154. //
  82155. // This post-process allows the modification of rendered colors by using
  82156. // a 'look-up table' (LUT). This effect is also called Color Grading.
  82157. //
  82158. // The object needs to be provided an url to a texture containing the color
  82159. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  82160. // Use an image editing software to tweak the LUT to match your needs.
  82161. //
  82162. // For an example of a color LUT, see here:
  82163. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  82164. // For explanations on color grading, see here:
  82165. // http://udn.epicgames.com/Three/ColorGrading.html
  82166. //
  82167. var BABYLON;
  82168. (function (BABYLON) {
  82169. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  82170. __extends(ColorCorrectionPostProcess, _super);
  82171. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  82172. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  82173. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82174. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  82175. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82176. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82177. _this.onApply = function (effect) {
  82178. effect.setTexture("colorTable", _this._colorTableTexture);
  82179. };
  82180. return _this;
  82181. }
  82182. return ColorCorrectionPostProcess;
  82183. }(BABYLON.PostProcess));
  82184. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  82185. })(BABYLON || (BABYLON = {}));
  82186. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  82187. var BABYLON;
  82188. (function (BABYLON) {
  82189. /** Defines operator used for tonemapping */
  82190. var TonemappingOperator;
  82191. (function (TonemappingOperator) {
  82192. /** Hable */
  82193. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  82194. /** Reinhard */
  82195. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  82196. /** HejiDawson */
  82197. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  82198. /** Photographic */
  82199. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  82200. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  82201. ;
  82202. /**
  82203. * Defines a post process to apply tone mapping
  82204. */
  82205. var TonemapPostProcess = /** @class */ (function (_super) {
  82206. __extends(TonemapPostProcess, _super);
  82207. /**
  82208. * Creates a new TonemapPostProcess
  82209. * @param name defines the name of the postprocess
  82210. * @param _operator defines the operator to use
  82211. * @param exposureAdjustment defines the required exposure adjustement
  82212. * @param camera defines the camera to use (can be null)
  82213. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  82214. * @param engine defines the hosting engine (can be ignore if camera is set)
  82215. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  82216. */
  82217. function TonemapPostProcess(name, _operator,
  82218. /** Defines the required exposure adjustement */
  82219. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  82220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82221. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82222. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  82223. _this._operator = _operator;
  82224. _this.exposureAdjustment = exposureAdjustment;
  82225. var defines = "#define ";
  82226. if (_this._operator === TonemappingOperator.Hable)
  82227. defines += "HABLE_TONEMAPPING";
  82228. else if (_this._operator === TonemappingOperator.Reinhard)
  82229. defines += "REINHARD_TONEMAPPING";
  82230. else if (_this._operator === TonemappingOperator.HejiDawson)
  82231. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  82232. else if (_this._operator === TonemappingOperator.Photographic)
  82233. defines += "PHOTOGRAPHIC_TONEMAPPING";
  82234. //sadly a second call to create the effect.
  82235. _this.updateEffect(defines);
  82236. _this.onApply = function (effect) {
  82237. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  82238. };
  82239. return _this;
  82240. }
  82241. return TonemapPostProcess;
  82242. }(BABYLON.PostProcess));
  82243. BABYLON.TonemapPostProcess = TonemapPostProcess;
  82244. })(BABYLON || (BABYLON = {}));
  82245. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  82246. var BABYLON;
  82247. (function (BABYLON) {
  82248. var DisplayPassPostProcess = /** @class */ (function (_super) {
  82249. __extends(DisplayPassPostProcess, _super);
  82250. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  82251. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  82252. }
  82253. return DisplayPassPostProcess;
  82254. }(BABYLON.PostProcess));
  82255. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  82256. })(BABYLON || (BABYLON = {}));
  82257. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  82258. var BABYLON;
  82259. (function (BABYLON) {
  82260. var HighlightsPostProcess = /** @class */ (function (_super) {
  82261. __extends(HighlightsPostProcess, _super);
  82262. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82264. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82265. }
  82266. return HighlightsPostProcess;
  82267. }(BABYLON.PostProcess));
  82268. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  82269. })(BABYLON || (BABYLON = {}));
  82270. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  82271. var BABYLON;
  82272. (function (BABYLON) {
  82273. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  82274. __extends(ImageProcessingPostProcess, _super);
  82275. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  82276. if (camera === void 0) { camera = null; }
  82277. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82278. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  82279. _this._fromLinearSpace = true;
  82280. /**
  82281. * Defines cache preventing GC.
  82282. */
  82283. _this._defines = {
  82284. IMAGEPROCESSING: false,
  82285. VIGNETTE: false,
  82286. VIGNETTEBLENDMODEMULTIPLY: false,
  82287. VIGNETTEBLENDMODEOPAQUE: false,
  82288. TONEMAPPING: false,
  82289. TONEMAPPING_ACES: false,
  82290. CONTRAST: false,
  82291. COLORCURVES: false,
  82292. COLORGRADING: false,
  82293. COLORGRADING3D: false,
  82294. FROMLINEARSPACE: false,
  82295. SAMPLER3DGREENDEPTH: false,
  82296. SAMPLER3DBGRMAP: false,
  82297. IMAGEPROCESSINGPOSTPROCESS: false,
  82298. EXPOSURE: false,
  82299. };
  82300. // Setup the configuration as forced by the constructor. This would then not force the
  82301. // scene materials output in linear space and let untouched the default forward pass.
  82302. if (imageProcessingConfiguration) {
  82303. imageProcessingConfiguration.applyByPostProcess = true;
  82304. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  82305. // This will cause the shader to be compiled
  82306. _this.fromLinearSpace = false;
  82307. }
  82308. // Setup the default processing configuration to the scene.
  82309. else {
  82310. _this._attachImageProcessingConfiguration(null, true);
  82311. _this.imageProcessingConfiguration.applyByPostProcess = true;
  82312. }
  82313. _this.onApply = function (effect) {
  82314. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  82315. };
  82316. return _this;
  82317. }
  82318. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  82319. /**
  82320. * Gets the image processing configuration used either in this material.
  82321. */
  82322. get: function () {
  82323. return this._imageProcessingConfiguration;
  82324. },
  82325. /**
  82326. * Sets the Default image processing configuration used either in the this material.
  82327. *
  82328. * If sets to null, the scene one is in use.
  82329. */
  82330. set: function (value) {
  82331. this._attachImageProcessingConfiguration(value);
  82332. },
  82333. enumerable: true,
  82334. configurable: true
  82335. });
  82336. /**
  82337. * Attaches a new image processing configuration to the PBR Material.
  82338. * @param configuration
  82339. */
  82340. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  82341. var _this = this;
  82342. if (doNotBuild === void 0) { doNotBuild = false; }
  82343. if (configuration === this._imageProcessingConfiguration) {
  82344. return;
  82345. }
  82346. // Detaches observer.
  82347. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82348. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82349. }
  82350. // Pick the scene configuration if needed.
  82351. if (!configuration) {
  82352. var scene = null;
  82353. var engine = this.getEngine();
  82354. var camera = this.getCamera();
  82355. if (camera) {
  82356. scene = camera.getScene();
  82357. }
  82358. else if (engine && engine.scenes) {
  82359. var scenes = engine.scenes;
  82360. scene = scenes[scenes.length - 1];
  82361. }
  82362. else {
  82363. scene = BABYLON.Engine.LastCreatedScene;
  82364. }
  82365. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  82366. }
  82367. else {
  82368. this._imageProcessingConfiguration = configuration;
  82369. }
  82370. // Attaches observer.
  82371. if (this._imageProcessingConfiguration) {
  82372. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82373. _this._updateParameters();
  82374. });
  82375. }
  82376. // Ensure the effect will be rebuilt.
  82377. if (!doNotBuild) {
  82378. this._updateParameters();
  82379. }
  82380. };
  82381. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  82382. /**
  82383. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82384. */
  82385. get: function () {
  82386. return this.imageProcessingConfiguration.colorCurves;
  82387. },
  82388. /**
  82389. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82390. */
  82391. set: function (value) {
  82392. this.imageProcessingConfiguration.colorCurves = value;
  82393. },
  82394. enumerable: true,
  82395. configurable: true
  82396. });
  82397. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  82398. /**
  82399. * Gets wether the color curves effect is enabled.
  82400. */
  82401. get: function () {
  82402. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82403. },
  82404. /**
  82405. * Sets wether the color curves effect is enabled.
  82406. */
  82407. set: function (value) {
  82408. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82409. },
  82410. enumerable: true,
  82411. configurable: true
  82412. });
  82413. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  82414. /**
  82415. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82416. */
  82417. get: function () {
  82418. return this.imageProcessingConfiguration.colorGradingTexture;
  82419. },
  82420. /**
  82421. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82422. */
  82423. set: function (value) {
  82424. this.imageProcessingConfiguration.colorGradingTexture = value;
  82425. },
  82426. enumerable: true,
  82427. configurable: true
  82428. });
  82429. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  82430. /**
  82431. * Gets wether the color grading effect is enabled.
  82432. */
  82433. get: function () {
  82434. return this.imageProcessingConfiguration.colorGradingEnabled;
  82435. },
  82436. /**
  82437. * Gets wether the color grading effect is enabled.
  82438. */
  82439. set: function (value) {
  82440. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82441. },
  82442. enumerable: true,
  82443. configurable: true
  82444. });
  82445. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  82446. /**
  82447. * Gets exposure used in the effect.
  82448. */
  82449. get: function () {
  82450. return this.imageProcessingConfiguration.exposure;
  82451. },
  82452. /**
  82453. * Sets exposure used in the effect.
  82454. */
  82455. set: function (value) {
  82456. this.imageProcessingConfiguration.exposure = value;
  82457. },
  82458. enumerable: true,
  82459. configurable: true
  82460. });
  82461. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  82462. /**
  82463. * Gets wether tonemapping is enabled or not.
  82464. */
  82465. get: function () {
  82466. return this._imageProcessingConfiguration.toneMappingEnabled;
  82467. },
  82468. /**
  82469. * Sets wether tonemapping is enabled or not
  82470. */
  82471. set: function (value) {
  82472. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82473. },
  82474. enumerable: true,
  82475. configurable: true
  82476. });
  82477. ;
  82478. ;
  82479. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  82480. /**
  82481. * Gets contrast used in the effect.
  82482. */
  82483. get: function () {
  82484. return this.imageProcessingConfiguration.contrast;
  82485. },
  82486. /**
  82487. * Sets contrast used in the effect.
  82488. */
  82489. set: function (value) {
  82490. this.imageProcessingConfiguration.contrast = value;
  82491. },
  82492. enumerable: true,
  82493. configurable: true
  82494. });
  82495. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  82496. /**
  82497. * Gets Vignette stretch size.
  82498. */
  82499. get: function () {
  82500. return this.imageProcessingConfiguration.vignetteStretch;
  82501. },
  82502. /**
  82503. * Sets Vignette stretch size.
  82504. */
  82505. set: function (value) {
  82506. this.imageProcessingConfiguration.vignetteStretch = value;
  82507. },
  82508. enumerable: true,
  82509. configurable: true
  82510. });
  82511. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  82512. /**
  82513. * Gets Vignette centre X Offset.
  82514. */
  82515. get: function () {
  82516. return this.imageProcessingConfiguration.vignetteCentreX;
  82517. },
  82518. /**
  82519. * Sets Vignette centre X Offset.
  82520. */
  82521. set: function (value) {
  82522. this.imageProcessingConfiguration.vignetteCentreX = value;
  82523. },
  82524. enumerable: true,
  82525. configurable: true
  82526. });
  82527. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  82528. /**
  82529. * Gets Vignette centre Y Offset.
  82530. */
  82531. get: function () {
  82532. return this.imageProcessingConfiguration.vignetteCentreY;
  82533. },
  82534. /**
  82535. * Sets Vignette centre Y Offset.
  82536. */
  82537. set: function (value) {
  82538. this.imageProcessingConfiguration.vignetteCentreY = value;
  82539. },
  82540. enumerable: true,
  82541. configurable: true
  82542. });
  82543. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  82544. /**
  82545. * Gets Vignette weight or intensity of the vignette effect.
  82546. */
  82547. get: function () {
  82548. return this.imageProcessingConfiguration.vignetteWeight;
  82549. },
  82550. /**
  82551. * Sets Vignette weight or intensity of the vignette effect.
  82552. */
  82553. set: function (value) {
  82554. this.imageProcessingConfiguration.vignetteWeight = value;
  82555. },
  82556. enumerable: true,
  82557. configurable: true
  82558. });
  82559. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  82560. /**
  82561. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82562. * if vignetteEnabled is set to true.
  82563. */
  82564. get: function () {
  82565. return this.imageProcessingConfiguration.vignetteColor;
  82566. },
  82567. /**
  82568. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82569. * if vignetteEnabled is set to true.
  82570. */
  82571. set: function (value) {
  82572. this.imageProcessingConfiguration.vignetteColor = value;
  82573. },
  82574. enumerable: true,
  82575. configurable: true
  82576. });
  82577. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  82578. /**
  82579. * Gets Camera field of view used by the Vignette effect.
  82580. */
  82581. get: function () {
  82582. return this.imageProcessingConfiguration.vignetteCameraFov;
  82583. },
  82584. /**
  82585. * Sets Camera field of view used by the Vignette effect.
  82586. */
  82587. set: function (value) {
  82588. this.imageProcessingConfiguration.vignetteCameraFov = value;
  82589. },
  82590. enumerable: true,
  82591. configurable: true
  82592. });
  82593. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  82594. /**
  82595. * Gets the vignette blend mode allowing different kind of effect.
  82596. */
  82597. get: function () {
  82598. return this.imageProcessingConfiguration.vignetteBlendMode;
  82599. },
  82600. /**
  82601. * Sets the vignette blend mode allowing different kind of effect.
  82602. */
  82603. set: function (value) {
  82604. this.imageProcessingConfiguration.vignetteBlendMode = value;
  82605. },
  82606. enumerable: true,
  82607. configurable: true
  82608. });
  82609. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  82610. /**
  82611. * Gets wether the vignette effect is enabled.
  82612. */
  82613. get: function () {
  82614. return this.imageProcessingConfiguration.vignetteEnabled;
  82615. },
  82616. /**
  82617. * Sets wether the vignette effect is enabled.
  82618. */
  82619. set: function (value) {
  82620. this.imageProcessingConfiguration.vignetteEnabled = value;
  82621. },
  82622. enumerable: true,
  82623. configurable: true
  82624. });
  82625. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  82626. /**
  82627. * Gets wether the input of the processing is in Gamma or Linear Space.
  82628. */
  82629. get: function () {
  82630. return this._fromLinearSpace;
  82631. },
  82632. /**
  82633. * Sets wether the input of the processing is in Gamma or Linear Space.
  82634. */
  82635. set: function (value) {
  82636. if (this._fromLinearSpace === value) {
  82637. return;
  82638. }
  82639. this._fromLinearSpace = value;
  82640. this._updateParameters();
  82641. },
  82642. enumerable: true,
  82643. configurable: true
  82644. });
  82645. ImageProcessingPostProcess.prototype.getClassName = function () {
  82646. return "ImageProcessingPostProcess";
  82647. };
  82648. ImageProcessingPostProcess.prototype._updateParameters = function () {
  82649. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  82650. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  82651. var defines = "";
  82652. for (var define in this._defines) {
  82653. if (this._defines[define]) {
  82654. defines += "#define " + define + ";\r\n";
  82655. }
  82656. }
  82657. var samplers = ["textureSampler"];
  82658. var uniforms = ["scale"];
  82659. if (BABYLON.ImageProcessingConfiguration) {
  82660. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  82661. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  82662. }
  82663. this.updateEffect(defines, uniforms, samplers);
  82664. };
  82665. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  82666. _super.prototype.dispose.call(this, camera);
  82667. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82668. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82669. }
  82670. if (this._imageProcessingConfiguration) {
  82671. this.imageProcessingConfiguration.applyByPostProcess = false;
  82672. }
  82673. };
  82674. __decorate([
  82675. BABYLON.serialize()
  82676. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  82677. return ImageProcessingPostProcess;
  82678. }(BABYLON.PostProcess));
  82679. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  82680. })(BABYLON || (BABYLON = {}));
  82681. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  82682. var BABYLON;
  82683. (function (BABYLON) {
  82684. /**
  82685. * Class used to store bone information
  82686. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82687. */
  82688. var Bone = /** @class */ (function (_super) {
  82689. __extends(Bone, _super);
  82690. /**
  82691. * Create a new bone
  82692. * @param name defines the bone name
  82693. * @param skeleton defines the parent skeleton
  82694. * @param parentBone defines the parent (can be null if the bone is the root)
  82695. * @param localMatrix defines the local matrix
  82696. * @param restPose defines the rest pose matrix
  82697. * @param baseMatrix defines the base matrix
  82698. * @param index defines index of the bone in the hiearchy
  82699. */
  82700. function Bone(
  82701. /**
  82702. * defines the bone name
  82703. */
  82704. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  82705. if (parentBone === void 0) { parentBone = null; }
  82706. if (localMatrix === void 0) { localMatrix = null; }
  82707. if (restPose === void 0) { restPose = null; }
  82708. if (baseMatrix === void 0) { baseMatrix = null; }
  82709. if (index === void 0) { index = null; }
  82710. var _this = _super.call(this, name, skeleton.getScene()) || this;
  82711. _this.name = name;
  82712. /**
  82713. * Gets the list of child bones
  82714. */
  82715. _this.children = new Array();
  82716. /** Gets the animations associated with this bone */
  82717. _this.animations = new Array();
  82718. /**
  82719. * @hidden Internal only
  82720. * Set this value to map this bone to a different index in the transform matrices
  82721. * Set this value to -1 to exclude the bone from the transform matrices
  82722. */
  82723. _this._index = null;
  82724. _this._absoluteTransform = new BABYLON.Matrix();
  82725. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  82726. _this._scalingDeterminant = 1;
  82727. _this._worldTransform = new BABYLON.Matrix();
  82728. _this._needToDecompose = true;
  82729. _this._needToCompose = false;
  82730. _this._skeleton = skeleton;
  82731. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  82732. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  82733. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  82734. _this._index = index;
  82735. skeleton.bones.push(_this);
  82736. _this.setParent(parentBone, false);
  82737. if (baseMatrix || localMatrix) {
  82738. _this._updateDifferenceMatrix();
  82739. }
  82740. return _this;
  82741. }
  82742. Object.defineProperty(Bone.prototype, "_matrix", {
  82743. /** @hidden */
  82744. get: function () {
  82745. this._compose();
  82746. return this._localMatrix;
  82747. },
  82748. /** @hidden */
  82749. set: function (value) {
  82750. this._localMatrix.copyFrom(value);
  82751. this._needToDecompose = true;
  82752. },
  82753. enumerable: true,
  82754. configurable: true
  82755. });
  82756. // Members
  82757. /**
  82758. * Gets the parent skeleton
  82759. * @returns a skeleton
  82760. */
  82761. Bone.prototype.getSkeleton = function () {
  82762. return this._skeleton;
  82763. };
  82764. /**
  82765. * Gets parent bone
  82766. * @returns a bone or null if the bone is the root of the bone hierarchy
  82767. */
  82768. Bone.prototype.getParent = function () {
  82769. return this._parent;
  82770. };
  82771. /**
  82772. * Sets the parent bone
  82773. * @param parent defines the parent (can be null if the bone is the root)
  82774. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82775. */
  82776. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  82777. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82778. if (this._parent === parent) {
  82779. return;
  82780. }
  82781. if (this._parent) {
  82782. var index = this._parent.children.indexOf(this);
  82783. if (index !== -1) {
  82784. this._parent.children.splice(index, 1);
  82785. }
  82786. }
  82787. this._parent = parent;
  82788. if (this._parent) {
  82789. this._parent.children.push(this);
  82790. }
  82791. if (updateDifferenceMatrix) {
  82792. this._updateDifferenceMatrix();
  82793. }
  82794. this.markAsDirty();
  82795. };
  82796. /**
  82797. * Gets the local matrix
  82798. * @returns a matrix
  82799. */
  82800. Bone.prototype.getLocalMatrix = function () {
  82801. this._compose();
  82802. return this._localMatrix;
  82803. };
  82804. /**
  82805. * Gets the base matrix (initial matrix which remains unchanged)
  82806. * @returns a matrix
  82807. */
  82808. Bone.prototype.getBaseMatrix = function () {
  82809. return this._baseMatrix;
  82810. };
  82811. /**
  82812. * Gets the rest pose matrix
  82813. * @returns a matrix
  82814. */
  82815. Bone.prototype.getRestPose = function () {
  82816. return this._restPose;
  82817. };
  82818. /**
  82819. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  82820. */
  82821. Bone.prototype.getWorldMatrix = function () {
  82822. return this._worldTransform;
  82823. };
  82824. /**
  82825. * Sets the local matrix to rest pose matrix
  82826. */
  82827. Bone.prototype.returnToRest = function () {
  82828. this.updateMatrix(this._restPose.clone());
  82829. };
  82830. /**
  82831. * Gets the inverse of the absolute transform matrix.
  82832. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  82833. * @returns a matrix
  82834. */
  82835. Bone.prototype.getInvertedAbsoluteTransform = function () {
  82836. return this._invertedAbsoluteTransform;
  82837. };
  82838. /**
  82839. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  82840. * @returns a matrix
  82841. */
  82842. Bone.prototype.getAbsoluteTransform = function () {
  82843. return this._absoluteTransform;
  82844. };
  82845. Object.defineProperty(Bone.prototype, "position", {
  82846. // Properties (matches AbstractMesh properties)
  82847. /** Gets or sets current position (in local space) */
  82848. get: function () {
  82849. this._decompose();
  82850. return this._localPosition;
  82851. },
  82852. set: function (newPosition) {
  82853. this._decompose();
  82854. this._localPosition.copyFrom(newPosition);
  82855. this._markAsDirtyAndCompose();
  82856. },
  82857. enumerable: true,
  82858. configurable: true
  82859. });
  82860. Object.defineProperty(Bone.prototype, "rotation", {
  82861. /** Gets or sets current rotation (in local space) */
  82862. get: function () {
  82863. return this.getRotation();
  82864. },
  82865. set: function (newRotation) {
  82866. this.setRotation(newRotation);
  82867. },
  82868. enumerable: true,
  82869. configurable: true
  82870. });
  82871. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  82872. /** Gets or sets current rotation quaternion (in local space) */
  82873. get: function () {
  82874. this._decompose();
  82875. return this._localRotation;
  82876. },
  82877. set: function (newRotation) {
  82878. this.setRotationQuaternion(newRotation);
  82879. },
  82880. enumerable: true,
  82881. configurable: true
  82882. });
  82883. Object.defineProperty(Bone.prototype, "scaling", {
  82884. /** Gets or sets current scaling (in local space) */
  82885. get: function () {
  82886. return this.getScale();
  82887. },
  82888. set: function (newScaling) {
  82889. this.setScale(newScaling);
  82890. },
  82891. enumerable: true,
  82892. configurable: true
  82893. });
  82894. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  82895. /**
  82896. * Gets the animation properties override
  82897. */
  82898. get: function () {
  82899. return this._skeleton.animationPropertiesOverride;
  82900. },
  82901. enumerable: true,
  82902. configurable: true
  82903. });
  82904. // Methods
  82905. Bone.prototype._decompose = function () {
  82906. if (!this._needToDecompose) {
  82907. return;
  82908. }
  82909. this._needToDecompose = false;
  82910. if (!this._localScaling) {
  82911. this._localScaling = BABYLON.Vector3.Zero();
  82912. this._localRotation = BABYLON.Quaternion.Zero();
  82913. this._localPosition = BABYLON.Vector3.Zero();
  82914. }
  82915. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  82916. };
  82917. Bone.prototype._compose = function () {
  82918. if (!this._needToCompose) {
  82919. return;
  82920. }
  82921. this._needToCompose = false;
  82922. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  82923. };
  82924. /**
  82925. * Update the base and local matrices
  82926. * @param matrix defines the new base or local matrix
  82927. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82928. * @param updateLocalMatrix defines if the local matrix should be updated
  82929. */
  82930. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  82931. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82932. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  82933. this._baseMatrix.copyFrom(matrix);
  82934. if (updateDifferenceMatrix) {
  82935. this._updateDifferenceMatrix();
  82936. }
  82937. if (updateLocalMatrix) {
  82938. this._localMatrix.copyFrom(matrix);
  82939. this._markAsDirtyAndDecompose();
  82940. }
  82941. else {
  82942. this.markAsDirty();
  82943. }
  82944. };
  82945. /** @hidden */
  82946. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  82947. if (updateChildren === void 0) { updateChildren = true; }
  82948. if (!rootMatrix) {
  82949. rootMatrix = this._baseMatrix;
  82950. }
  82951. if (this._parent) {
  82952. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82953. }
  82954. else {
  82955. this._absoluteTransform.copyFrom(rootMatrix);
  82956. }
  82957. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  82958. if (updateChildren) {
  82959. for (var index = 0; index < this.children.length; index++) {
  82960. this.children[index]._updateDifferenceMatrix();
  82961. }
  82962. }
  82963. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  82964. };
  82965. /**
  82966. * Flag the bone as dirty (Forcing it to update everything)
  82967. */
  82968. Bone.prototype.markAsDirty = function () {
  82969. this._currentRenderId++;
  82970. this._childRenderId++;
  82971. this._skeleton._markAsDirty();
  82972. };
  82973. Bone.prototype._markAsDirtyAndCompose = function () {
  82974. this.markAsDirty();
  82975. this._needToCompose = true;
  82976. };
  82977. Bone.prototype._markAsDirtyAndDecompose = function () {
  82978. this.markAsDirty();
  82979. this._needToDecompose = true;
  82980. };
  82981. /**
  82982. * Copy an animation range from another bone
  82983. * @param source defines the source bone
  82984. * @param rangeName defines the range name to copy
  82985. * @param frameOffset defines the frame offset
  82986. * @param rescaleAsRequired defines if rescaling must be applied if required
  82987. * @param skelDimensionsRatio defines the scaling ratio
  82988. * @returns true if operation was successful
  82989. */
  82990. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  82991. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82992. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  82993. // all animation may be coming from a library skeleton, so may need to create animation
  82994. if (this.animations.length === 0) {
  82995. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  82996. this.animations[0].setKeys([]);
  82997. }
  82998. // get animation info / verify there is such a range from the source bone
  82999. var sourceRange = source.animations[0].getRange(rangeName);
  83000. if (!sourceRange) {
  83001. return false;
  83002. }
  83003. var from = sourceRange.from;
  83004. var to = sourceRange.to;
  83005. var sourceKeys = source.animations[0].getKeys();
  83006. // rescaling prep
  83007. var sourceBoneLength = source.length;
  83008. var sourceParent = source.getParent();
  83009. var parent = this.getParent();
  83010. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  83011. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  83012. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  83013. var destKeys = this.animations[0].getKeys();
  83014. // loop vars declaration
  83015. var orig;
  83016. var origTranslation;
  83017. var mat;
  83018. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  83019. orig = sourceKeys[key];
  83020. if (orig.frame >= from && orig.frame <= to) {
  83021. if (rescaleAsRequired) {
  83022. mat = orig.value.clone();
  83023. // scale based on parent ratio, when bone has parent
  83024. if (parentScalingReqd) {
  83025. origTranslation = mat.getTranslation();
  83026. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  83027. // scale based on skeleton dimension ratio when root bone, and value is passed
  83028. }
  83029. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  83030. origTranslation = mat.getTranslation();
  83031. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  83032. // use original when root bone, and no data for skelDimensionsRatio
  83033. }
  83034. else {
  83035. mat = orig.value;
  83036. }
  83037. }
  83038. else {
  83039. mat = orig.value;
  83040. }
  83041. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  83042. }
  83043. }
  83044. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  83045. return true;
  83046. };
  83047. /**
  83048. * Translate the bone in local or world space
  83049. * @param vec The amount to translate the bone
  83050. * @param space The space that the translation is in
  83051. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83052. */
  83053. Bone.prototype.translate = function (vec, space, mesh) {
  83054. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83055. var lm = this.getLocalMatrix();
  83056. if (space == BABYLON.Space.LOCAL) {
  83057. lm.m[12] += vec.x;
  83058. lm.m[13] += vec.y;
  83059. lm.m[14] += vec.z;
  83060. }
  83061. else {
  83062. var wm = null;
  83063. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83064. if (mesh) {
  83065. wm = mesh.getWorldMatrix();
  83066. }
  83067. this._skeleton.computeAbsoluteTransforms();
  83068. var tmat = Bone._tmpMats[0];
  83069. var tvec = Bone._tmpVecs[0];
  83070. if (this._parent) {
  83071. if (mesh && wm) {
  83072. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83073. tmat.multiplyToRef(wm, tmat);
  83074. }
  83075. else {
  83076. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83077. }
  83078. }
  83079. tmat.m[12] = 0;
  83080. tmat.m[13] = 0;
  83081. tmat.m[14] = 0;
  83082. tmat.invert();
  83083. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  83084. lm.m[12] += tvec.x;
  83085. lm.m[13] += tvec.y;
  83086. lm.m[14] += tvec.z;
  83087. }
  83088. this._markAsDirtyAndDecompose();
  83089. };
  83090. /**
  83091. * Set the postion of the bone in local or world space
  83092. * @param position The position to set the bone
  83093. * @param space The space that the position is in
  83094. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83095. */
  83096. Bone.prototype.setPosition = function (position, space, mesh) {
  83097. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83098. var lm = this.getLocalMatrix();
  83099. if (space == BABYLON.Space.LOCAL) {
  83100. lm.m[12] = position.x;
  83101. lm.m[13] = position.y;
  83102. lm.m[14] = position.z;
  83103. }
  83104. else {
  83105. var wm = null;
  83106. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83107. if (mesh) {
  83108. wm = mesh.getWorldMatrix();
  83109. }
  83110. this._skeleton.computeAbsoluteTransforms();
  83111. var tmat = Bone._tmpMats[0];
  83112. var vec = Bone._tmpVecs[0];
  83113. if (this._parent) {
  83114. if (mesh && wm) {
  83115. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83116. tmat.multiplyToRef(wm, tmat);
  83117. }
  83118. else {
  83119. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83120. }
  83121. }
  83122. tmat.invert();
  83123. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  83124. lm.m[12] = vec.x;
  83125. lm.m[13] = vec.y;
  83126. lm.m[14] = vec.z;
  83127. }
  83128. this._markAsDirtyAndDecompose();
  83129. };
  83130. /**
  83131. * Set the absolute position of the bone (world space)
  83132. * @param position The position to set the bone
  83133. * @param mesh The mesh that this bone is attached to
  83134. */
  83135. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  83136. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  83137. };
  83138. /**
  83139. * Scale the bone on the x, y and z axes (in local space)
  83140. * @param x The amount to scale the bone on the x axis
  83141. * @param y The amount to scale the bone on the y axis
  83142. * @param z The amount to scale the bone on the z axis
  83143. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  83144. */
  83145. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  83146. if (scaleChildren === void 0) { scaleChildren = false; }
  83147. var locMat = this.getLocalMatrix();
  83148. // Apply new scaling on top of current local matrix
  83149. var scaleMat = Bone._tmpMats[0];
  83150. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  83151. scaleMat.multiplyToRef(locMat, locMat);
  83152. // Invert scaling matrix and apply the inverse to all children
  83153. scaleMat.invert();
  83154. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  83155. var child = _a[_i];
  83156. var cm = child.getLocalMatrix();
  83157. cm.multiplyToRef(scaleMat, cm);
  83158. cm.m[12] *= x;
  83159. cm.m[13] *= y;
  83160. cm.m[14] *= z;
  83161. child._markAsDirtyAndDecompose();
  83162. }
  83163. this._markAsDirtyAndDecompose();
  83164. if (scaleChildren) {
  83165. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  83166. var child = _c[_b];
  83167. child.scale(x, y, z, scaleChildren);
  83168. }
  83169. }
  83170. };
  83171. /**
  83172. * Set the bone scaling in local space
  83173. * @param scale defines the scaling vector
  83174. */
  83175. Bone.prototype.setScale = function (scale) {
  83176. this._decompose();
  83177. this._localScaling.copyFrom(scale);
  83178. this._markAsDirtyAndCompose();
  83179. };
  83180. /**
  83181. * Gets the current scaling in local space
  83182. * @returns the current scaling vector
  83183. */
  83184. Bone.prototype.getScale = function () {
  83185. this._decompose();
  83186. return this._localScaling;
  83187. };
  83188. /**
  83189. * Gets the current scaling in local space and stores it in a target vector
  83190. * @param result defines the target vector
  83191. */
  83192. Bone.prototype.getScaleToRef = function (result) {
  83193. this._decompose();
  83194. result.copyFrom(this._localScaling);
  83195. };
  83196. /**
  83197. * Set the yaw, pitch, and roll of the bone in local or world space
  83198. * @param yaw The rotation of the bone on the y axis
  83199. * @param pitch The rotation of the bone on the x axis
  83200. * @param roll The rotation of the bone on the z axis
  83201. * @param space The space that the axes of rotation are in
  83202. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83203. */
  83204. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  83205. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83206. if (space === BABYLON.Space.LOCAL) {
  83207. var quat = Bone._tmpQuat;
  83208. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  83209. this.setRotationQuaternion(quat, space, mesh);
  83210. return;
  83211. }
  83212. var rotMatInv = Bone._tmpMats[0];
  83213. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83214. return;
  83215. }
  83216. var rotMat = Bone._tmpMats[1];
  83217. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  83218. rotMatInv.multiplyToRef(rotMat, rotMat);
  83219. this._rotateWithMatrix(rotMat, space, mesh);
  83220. };
  83221. /**
  83222. * Add a rotation to the bone on an axis in local or world space
  83223. * @param axis The axis to rotate the bone on
  83224. * @param amount The amount to rotate the bone
  83225. * @param space The space that the axis is in
  83226. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83227. */
  83228. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  83229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83230. var rmat = Bone._tmpMats[0];
  83231. rmat.m[12] = 0;
  83232. rmat.m[13] = 0;
  83233. rmat.m[14] = 0;
  83234. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  83235. this._rotateWithMatrix(rmat, space, mesh);
  83236. };
  83237. /**
  83238. * Set the rotation of the bone to a particular axis angle in local or world space
  83239. * @param axis The axis to rotate the bone on
  83240. * @param angle The angle that the bone should be rotated to
  83241. * @param space The space that the axis is in
  83242. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83243. */
  83244. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  83245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83246. if (space === BABYLON.Space.LOCAL) {
  83247. var quat = Bone._tmpQuat;
  83248. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  83249. this.setRotationQuaternion(quat, space, mesh);
  83250. return;
  83251. }
  83252. var rotMatInv = Bone._tmpMats[0];
  83253. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83254. return;
  83255. }
  83256. var rotMat = Bone._tmpMats[1];
  83257. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  83258. rotMatInv.multiplyToRef(rotMat, rotMat);
  83259. this._rotateWithMatrix(rotMat, space, mesh);
  83260. };
  83261. /**
  83262. * Set the euler rotation of the bone in local of world space
  83263. * @param rotation The euler rotation that the bone should be set to
  83264. * @param space The space that the rotation is in
  83265. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83266. */
  83267. Bone.prototype.setRotation = function (rotation, space, mesh) {
  83268. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83269. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  83270. };
  83271. /**
  83272. * Set the quaternion rotation of the bone in local of world space
  83273. * @param quat The quaternion rotation that the bone should be set to
  83274. * @param space The space that the rotation is in
  83275. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83276. */
  83277. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  83278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83279. if (space === BABYLON.Space.LOCAL) {
  83280. this._decompose();
  83281. this._localRotation.copyFrom(quat);
  83282. this._markAsDirtyAndCompose();
  83283. return;
  83284. }
  83285. var rotMatInv = Bone._tmpMats[0];
  83286. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83287. return;
  83288. }
  83289. var rotMat = Bone._tmpMats[1];
  83290. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  83291. rotMatInv.multiplyToRef(rotMat, rotMat);
  83292. this._rotateWithMatrix(rotMat, space, mesh);
  83293. };
  83294. /**
  83295. * Set the rotation matrix of the bone in local of world space
  83296. * @param rotMat The rotation matrix that the bone should be set to
  83297. * @param space The space that the rotation is in
  83298. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83299. */
  83300. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  83301. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83302. if (space === BABYLON.Space.LOCAL) {
  83303. var quat = Bone._tmpQuat;
  83304. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  83305. this.setRotationQuaternion(quat, space, mesh);
  83306. return;
  83307. }
  83308. var rotMatInv = Bone._tmpMats[0];
  83309. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83310. return;
  83311. }
  83312. var rotMat2 = Bone._tmpMats[1];
  83313. rotMat2.copyFrom(rotMat);
  83314. rotMatInv.multiplyToRef(rotMat, rotMat2);
  83315. this._rotateWithMatrix(rotMat2, space, mesh);
  83316. };
  83317. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  83318. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83319. var lmat = this.getLocalMatrix();
  83320. var lx = lmat.m[12];
  83321. var ly = lmat.m[13];
  83322. var lz = lmat.m[14];
  83323. var parent = this.getParent();
  83324. var parentScale = Bone._tmpMats[3];
  83325. var parentScaleInv = Bone._tmpMats[4];
  83326. if (parent && space == BABYLON.Space.WORLD) {
  83327. if (mesh) {
  83328. parentScale.copyFrom(mesh.getWorldMatrix());
  83329. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  83330. }
  83331. else {
  83332. parentScale.copyFrom(parent.getAbsoluteTransform());
  83333. }
  83334. parentScaleInv.copyFrom(parentScale);
  83335. parentScaleInv.invert();
  83336. lmat.multiplyToRef(parentScale, lmat);
  83337. lmat.multiplyToRef(rmat, lmat);
  83338. lmat.multiplyToRef(parentScaleInv, lmat);
  83339. }
  83340. else {
  83341. if (space == BABYLON.Space.WORLD && mesh) {
  83342. parentScale.copyFrom(mesh.getWorldMatrix());
  83343. parentScaleInv.copyFrom(parentScale);
  83344. parentScaleInv.invert();
  83345. lmat.multiplyToRef(parentScale, lmat);
  83346. lmat.multiplyToRef(rmat, lmat);
  83347. lmat.multiplyToRef(parentScaleInv, lmat);
  83348. }
  83349. else {
  83350. lmat.multiplyToRef(rmat, lmat);
  83351. }
  83352. }
  83353. lmat.m[12] = lx;
  83354. lmat.m[13] = ly;
  83355. lmat.m[14] = lz;
  83356. this.computeAbsoluteTransforms();
  83357. this._markAsDirtyAndDecompose();
  83358. };
  83359. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  83360. var scaleMatrix = Bone._tmpMats[2];
  83361. rotMatInv.copyFrom(this.getAbsoluteTransform());
  83362. if (mesh) {
  83363. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  83364. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  83365. }
  83366. rotMatInv.invert();
  83367. if (isNaN(rotMatInv.m[0])) {
  83368. // Matrix failed to invert.
  83369. // This can happen if scale is zero for example.
  83370. return false;
  83371. }
  83372. scaleMatrix.m[0] *= this._scalingDeterminant;
  83373. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  83374. return true;
  83375. };
  83376. /**
  83377. * Get the position of the bone in local or world space
  83378. * @param space The space that the returned position is in
  83379. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83380. * @returns The position of the bone
  83381. */
  83382. Bone.prototype.getPosition = function (space, mesh) {
  83383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83384. if (mesh === void 0) { mesh = null; }
  83385. var pos = BABYLON.Vector3.Zero();
  83386. this.getPositionToRef(space, mesh, pos);
  83387. return pos;
  83388. };
  83389. /**
  83390. * Copy the position of the bone to a vector3 in local or world space
  83391. * @param space The space that the returned position is in
  83392. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83393. * @param result The vector3 to copy the position to
  83394. */
  83395. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  83396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83397. if (space == BABYLON.Space.LOCAL) {
  83398. var lm = this.getLocalMatrix();
  83399. result.x = lm.m[12];
  83400. result.y = lm.m[13];
  83401. result.z = lm.m[14];
  83402. }
  83403. else {
  83404. var wm = null;
  83405. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83406. if (mesh) {
  83407. wm = mesh.getWorldMatrix();
  83408. }
  83409. this._skeleton.computeAbsoluteTransforms();
  83410. var tmat = Bone._tmpMats[0];
  83411. if (mesh && wm) {
  83412. tmat.copyFrom(this.getAbsoluteTransform());
  83413. tmat.multiplyToRef(wm, tmat);
  83414. }
  83415. else {
  83416. tmat = this.getAbsoluteTransform();
  83417. }
  83418. result.x = tmat.m[12];
  83419. result.y = tmat.m[13];
  83420. result.z = tmat.m[14];
  83421. }
  83422. };
  83423. /**
  83424. * Get the absolute position of the bone (world space)
  83425. * @param mesh The mesh that this bone is attached to
  83426. * @returns The absolute position of the bone
  83427. */
  83428. Bone.prototype.getAbsolutePosition = function (mesh) {
  83429. if (mesh === void 0) { mesh = null; }
  83430. var pos = BABYLON.Vector3.Zero();
  83431. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  83432. return pos;
  83433. };
  83434. /**
  83435. * Copy the absolute position of the bone (world space) to the result param
  83436. * @param mesh The mesh that this bone is attached to
  83437. * @param result The vector3 to copy the absolute position to
  83438. */
  83439. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  83440. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  83441. };
  83442. /**
  83443. * Compute the absolute transforms of this bone and its children
  83444. */
  83445. Bone.prototype.computeAbsoluteTransforms = function () {
  83446. this._compose();
  83447. if (this._parent) {
  83448. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83449. }
  83450. else {
  83451. this._absoluteTransform.copyFrom(this._localMatrix);
  83452. var poseMatrix = this._skeleton.getPoseMatrix();
  83453. if (poseMatrix) {
  83454. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  83455. }
  83456. }
  83457. var children = this.children;
  83458. var len = children.length;
  83459. for (var i = 0; i < len; i++) {
  83460. children[i].computeAbsoluteTransforms();
  83461. }
  83462. };
  83463. /**
  83464. * Get the world direction from an axis that is in the local space of the bone
  83465. * @param localAxis The local direction that is used to compute the world direction
  83466. * @param mesh The mesh that this bone is attached to
  83467. * @returns The world direction
  83468. */
  83469. Bone.prototype.getDirection = function (localAxis, mesh) {
  83470. if (mesh === void 0) { mesh = null; }
  83471. var result = BABYLON.Vector3.Zero();
  83472. this.getDirectionToRef(localAxis, mesh, result);
  83473. return result;
  83474. };
  83475. /**
  83476. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  83477. * @param localAxis The local direction that is used to compute the world direction
  83478. * @param mesh The mesh that this bone is attached to
  83479. * @param result The vector3 that the world direction will be copied to
  83480. */
  83481. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  83482. if (mesh === void 0) { mesh = null; }
  83483. var wm = null;
  83484. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83485. if (mesh) {
  83486. wm = mesh.getWorldMatrix();
  83487. }
  83488. this._skeleton.computeAbsoluteTransforms();
  83489. var mat = Bone._tmpMats[0];
  83490. mat.copyFrom(this.getAbsoluteTransform());
  83491. if (mesh && wm) {
  83492. mat.multiplyToRef(wm, mat);
  83493. }
  83494. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  83495. result.normalize();
  83496. };
  83497. /**
  83498. * Get the euler rotation of the bone in local or world space
  83499. * @param space The space that the rotation should be in
  83500. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83501. * @returns The euler rotation
  83502. */
  83503. Bone.prototype.getRotation = function (space, mesh) {
  83504. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83505. if (mesh === void 0) { mesh = null; }
  83506. var result = BABYLON.Vector3.Zero();
  83507. this.getRotationToRef(space, mesh, result);
  83508. return result;
  83509. };
  83510. /**
  83511. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  83512. * @param space The space that the rotation should be in
  83513. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83514. * @param result The vector3 that the rotation should be copied to
  83515. */
  83516. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  83517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83518. if (mesh === void 0) { mesh = null; }
  83519. var quat = Bone._tmpQuat;
  83520. this.getRotationQuaternionToRef(space, mesh, quat);
  83521. quat.toEulerAnglesToRef(result);
  83522. };
  83523. /**
  83524. * Get the quaternion rotation of the bone in either local or world space
  83525. * @param space The space that the rotation should be in
  83526. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83527. * @returns The quaternion rotation
  83528. */
  83529. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  83530. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83531. if (mesh === void 0) { mesh = null; }
  83532. var result = BABYLON.Quaternion.Identity();
  83533. this.getRotationQuaternionToRef(space, mesh, result);
  83534. return result;
  83535. };
  83536. /**
  83537. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  83538. * @param space The space that the rotation should be in
  83539. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83540. * @param result The quaternion that the rotation should be copied to
  83541. */
  83542. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  83543. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83544. if (mesh === void 0) { mesh = null; }
  83545. if (space == BABYLON.Space.LOCAL) {
  83546. this._decompose();
  83547. result.copyFrom(this._localRotation);
  83548. }
  83549. else {
  83550. var mat = Bone._tmpMats[0];
  83551. var amat = this.getAbsoluteTransform();
  83552. if (mesh) {
  83553. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83554. }
  83555. else {
  83556. mat.copyFrom(amat);
  83557. }
  83558. mat.m[0] *= this._scalingDeterminant;
  83559. mat.m[1] *= this._scalingDeterminant;
  83560. mat.m[2] *= this._scalingDeterminant;
  83561. mat.decompose(undefined, result, undefined);
  83562. }
  83563. };
  83564. /**
  83565. * Get the rotation matrix of the bone in local or world space
  83566. * @param space The space that the rotation should be in
  83567. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83568. * @returns The rotation matrix
  83569. */
  83570. Bone.prototype.getRotationMatrix = function (space, mesh) {
  83571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83572. var result = BABYLON.Matrix.Identity();
  83573. this.getRotationMatrixToRef(space, mesh, result);
  83574. return result;
  83575. };
  83576. /**
  83577. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  83578. * @param space The space that the rotation should be in
  83579. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83580. * @param result The quaternion that the rotation should be copied to
  83581. */
  83582. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  83583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83584. if (space == BABYLON.Space.LOCAL) {
  83585. this.getLocalMatrix().getRotationMatrixToRef(result);
  83586. }
  83587. else {
  83588. var mat = Bone._tmpMats[0];
  83589. var amat = this.getAbsoluteTransform();
  83590. if (mesh) {
  83591. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83592. }
  83593. else {
  83594. mat.copyFrom(amat);
  83595. }
  83596. mat.m[0] *= this._scalingDeterminant;
  83597. mat.m[1] *= this._scalingDeterminant;
  83598. mat.m[2] *= this._scalingDeterminant;
  83599. mat.getRotationMatrixToRef(result);
  83600. }
  83601. };
  83602. /**
  83603. * Get the world position of a point that is in the local space of the bone
  83604. * @param position The local position
  83605. * @param mesh The mesh that this bone is attached to
  83606. * @returns The world position
  83607. */
  83608. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  83609. if (mesh === void 0) { mesh = null; }
  83610. var result = BABYLON.Vector3.Zero();
  83611. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  83612. return result;
  83613. };
  83614. /**
  83615. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  83616. * @param position The local position
  83617. * @param mesh The mesh that this bone is attached to
  83618. * @param result The vector3 that the world position should be copied to
  83619. */
  83620. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  83621. if (mesh === void 0) { mesh = null; }
  83622. var wm = null;
  83623. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83624. if (mesh) {
  83625. wm = mesh.getWorldMatrix();
  83626. }
  83627. this._skeleton.computeAbsoluteTransforms();
  83628. var tmat = Bone._tmpMats[0];
  83629. if (mesh && wm) {
  83630. tmat.copyFrom(this.getAbsoluteTransform());
  83631. tmat.multiplyToRef(wm, tmat);
  83632. }
  83633. else {
  83634. tmat = this.getAbsoluteTransform();
  83635. }
  83636. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83637. };
  83638. /**
  83639. * Get the local position of a point that is in world space
  83640. * @param position The world position
  83641. * @param mesh The mesh that this bone is attached to
  83642. * @returns The local position
  83643. */
  83644. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  83645. if (mesh === void 0) { mesh = null; }
  83646. var result = BABYLON.Vector3.Zero();
  83647. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  83648. return result;
  83649. };
  83650. /**
  83651. * Get the local position of a point that is in world space and copy it to the result param
  83652. * @param position The world position
  83653. * @param mesh The mesh that this bone is attached to
  83654. * @param result The vector3 that the local position should be copied to
  83655. */
  83656. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  83657. if (mesh === void 0) { mesh = null; }
  83658. var wm = null;
  83659. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83660. if (mesh) {
  83661. wm = mesh.getWorldMatrix();
  83662. }
  83663. this._skeleton.computeAbsoluteTransforms();
  83664. var tmat = Bone._tmpMats[0];
  83665. tmat.copyFrom(this.getAbsoluteTransform());
  83666. if (mesh && wm) {
  83667. tmat.multiplyToRef(wm, tmat);
  83668. }
  83669. tmat.invert();
  83670. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83671. };
  83672. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83673. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  83674. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83675. return Bone;
  83676. }(BABYLON.Node));
  83677. BABYLON.Bone = Bone;
  83678. })(BABYLON || (BABYLON = {}));
  83679. //# sourceMappingURL=babylon.bone.js.map
  83680. var BABYLON;
  83681. (function (BABYLON) {
  83682. /**
  83683. * Class used to apply inverse kinematics to bones
  83684. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  83685. */
  83686. var BoneIKController = /** @class */ (function () {
  83687. /**
  83688. * Creates a new BoneIKController
  83689. * @param mesh defines the mesh to control
  83690. * @param bone defines the bone to control
  83691. * @param options defines options to set up the controller
  83692. */
  83693. function BoneIKController(mesh, bone, options) {
  83694. /**
  83695. * Gets or sets the target position
  83696. */
  83697. this.targetPosition = BABYLON.Vector3.Zero();
  83698. /**
  83699. * Gets or sets the pole target position
  83700. */
  83701. this.poleTargetPosition = BABYLON.Vector3.Zero();
  83702. /**
  83703. * Gets or sets the pole target local offset
  83704. */
  83705. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  83706. /**
  83707. * Gets or sets the pole angle
  83708. */
  83709. this.poleAngle = 0;
  83710. /**
  83711. * 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)
  83712. */
  83713. this.slerpAmount = 1;
  83714. this._bone1Quat = BABYLON.Quaternion.Identity();
  83715. this._bone1Mat = BABYLON.Matrix.Identity();
  83716. this._bone2Ang = Math.PI;
  83717. this._maxAngle = Math.PI;
  83718. this._rightHandedSystem = false;
  83719. this._bendAxis = BABYLON.Vector3.Right();
  83720. this._slerping = false;
  83721. this._adjustRoll = 0;
  83722. this._bone2 = bone;
  83723. this._bone1 = bone.getParent();
  83724. if (!this._bone1) {
  83725. return;
  83726. }
  83727. this.mesh = mesh;
  83728. var bonePos = bone.getPosition();
  83729. if (bone.getAbsoluteTransform().determinant() > 0) {
  83730. this._rightHandedSystem = true;
  83731. this._bendAxis.x = 0;
  83732. this._bendAxis.y = 0;
  83733. this._bendAxis.z = -1;
  83734. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  83735. this._adjustRoll = Math.PI * .5;
  83736. this._bendAxis.z = 1;
  83737. }
  83738. }
  83739. if (this._bone1.length) {
  83740. var boneScale1 = this._bone1.getScale();
  83741. var boneScale2 = this._bone2.getScale();
  83742. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  83743. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  83744. }
  83745. else if (this._bone1.children[0]) {
  83746. mesh.computeWorldMatrix(true);
  83747. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  83748. var pos2 = this._bone2.getAbsolutePosition(mesh);
  83749. var pos3 = this._bone1.getAbsolutePosition(mesh);
  83750. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  83751. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  83752. }
  83753. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  83754. this.maxAngle = Math.PI;
  83755. if (options) {
  83756. if (options.targetMesh) {
  83757. this.targetMesh = options.targetMesh;
  83758. this.targetMesh.computeWorldMatrix(true);
  83759. }
  83760. if (options.poleTargetMesh) {
  83761. this.poleTargetMesh = options.poleTargetMesh;
  83762. this.poleTargetMesh.computeWorldMatrix(true);
  83763. }
  83764. else if (options.poleTargetBone) {
  83765. this.poleTargetBone = options.poleTargetBone;
  83766. }
  83767. else if (this._bone1.getParent()) {
  83768. this.poleTargetBone = this._bone1.getParent();
  83769. }
  83770. if (options.poleTargetLocalOffset) {
  83771. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  83772. }
  83773. if (options.poleAngle) {
  83774. this.poleAngle = options.poleAngle;
  83775. }
  83776. if (options.bendAxis) {
  83777. this._bendAxis.copyFrom(options.bendAxis);
  83778. }
  83779. if (options.maxAngle) {
  83780. this.maxAngle = options.maxAngle;
  83781. }
  83782. if (options.slerpAmount) {
  83783. this.slerpAmount = options.slerpAmount;
  83784. }
  83785. }
  83786. }
  83787. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  83788. /**
  83789. * Gets or sets maximum allowed angle
  83790. */
  83791. get: function () {
  83792. return this._maxAngle;
  83793. },
  83794. set: function (value) {
  83795. this._setMaxAngle(value);
  83796. },
  83797. enumerable: true,
  83798. configurable: true
  83799. });
  83800. BoneIKController.prototype._setMaxAngle = function (ang) {
  83801. if (ang < 0) {
  83802. ang = 0;
  83803. }
  83804. if (ang > Math.PI || ang == undefined) {
  83805. ang = Math.PI;
  83806. }
  83807. this._maxAngle = ang;
  83808. var a = this._bone1Length;
  83809. var b = this._bone2Length;
  83810. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  83811. };
  83812. /**
  83813. * Force the controller to update the bones
  83814. */
  83815. BoneIKController.prototype.update = function () {
  83816. var bone1 = this._bone1;
  83817. if (!bone1) {
  83818. return;
  83819. }
  83820. var target = this.targetPosition;
  83821. var poleTarget = this.poleTargetPosition;
  83822. var mat1 = BoneIKController._tmpMats[0];
  83823. var mat2 = BoneIKController._tmpMats[1];
  83824. if (this.targetMesh) {
  83825. target.copyFrom(this.targetMesh.getAbsolutePosition());
  83826. }
  83827. if (this.poleTargetBone) {
  83828. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  83829. }
  83830. else if (this.poleTargetMesh) {
  83831. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  83832. }
  83833. var bonePos = BoneIKController._tmpVecs[0];
  83834. var zaxis = BoneIKController._tmpVecs[1];
  83835. var xaxis = BoneIKController._tmpVecs[2];
  83836. var yaxis = BoneIKController._tmpVecs[3];
  83837. var upAxis = BoneIKController._tmpVecs[4];
  83838. var _tmpQuat = BoneIKController._tmpQuat;
  83839. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  83840. poleTarget.subtractToRef(bonePos, upAxis);
  83841. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  83842. upAxis.y = 1;
  83843. }
  83844. else {
  83845. upAxis.normalize();
  83846. }
  83847. target.subtractToRef(bonePos, yaxis);
  83848. yaxis.normalize();
  83849. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  83850. zaxis.normalize();
  83851. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  83852. xaxis.normalize();
  83853. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  83854. var a = this._bone1Length;
  83855. var b = this._bone2Length;
  83856. var c = BABYLON.Vector3.Distance(bonePos, target);
  83857. if (this._maxReach > 0) {
  83858. c = Math.min(this._maxReach, c);
  83859. }
  83860. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  83861. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  83862. if (acosa > 1) {
  83863. acosa = 1;
  83864. }
  83865. if (acosb > 1) {
  83866. acosb = 1;
  83867. }
  83868. if (acosa < -1) {
  83869. acosa = -1;
  83870. }
  83871. if (acosb < -1) {
  83872. acosb = -1;
  83873. }
  83874. var angA = Math.acos(acosa);
  83875. var angB = Math.acos(acosb);
  83876. var angC = -angA - angB;
  83877. if (this._rightHandedSystem) {
  83878. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  83879. mat2.multiplyToRef(mat1, mat1);
  83880. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  83881. mat2.multiplyToRef(mat1, mat1);
  83882. }
  83883. else {
  83884. var _tmpVec = BoneIKController._tmpVecs[5];
  83885. _tmpVec.copyFrom(this._bendAxis);
  83886. _tmpVec.x *= -1;
  83887. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  83888. mat2.multiplyToRef(mat1, mat1);
  83889. }
  83890. if (this.poleAngle) {
  83891. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  83892. mat1.multiplyToRef(mat2, mat1);
  83893. }
  83894. if (this._bone1) {
  83895. if (this.slerpAmount < 1) {
  83896. if (!this._slerping) {
  83897. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  83898. }
  83899. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  83900. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  83901. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  83902. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  83903. this._slerping = true;
  83904. }
  83905. else {
  83906. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  83907. this._bone1Mat.copyFrom(mat1);
  83908. this._slerping = false;
  83909. }
  83910. }
  83911. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  83912. this._bone2Ang = angC;
  83913. };
  83914. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83915. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  83916. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83917. return BoneIKController;
  83918. }());
  83919. BABYLON.BoneIKController = BoneIKController;
  83920. })(BABYLON || (BABYLON = {}));
  83921. //# sourceMappingURL=babylon.boneIKController.js.map
  83922. var BABYLON;
  83923. (function (BABYLON) {
  83924. /**
  83925. * Class used to make a bone look toward a point in space
  83926. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  83927. */
  83928. var BoneLookController = /** @class */ (function () {
  83929. /**
  83930. * Create a BoneLookController
  83931. * @param mesh the mesh that the bone belongs to
  83932. * @param bone the bone that will be looking to the target
  83933. * @param target the target Vector3 to look at
  83934. * @param settings optional settings:
  83935. * * maxYaw: the maximum angle the bone will yaw to
  83936. * * minYaw: the minimum angle the bone will yaw to
  83937. * * maxPitch: the maximum angle the bone will pitch to
  83938. * * minPitch: the minimum angle the bone will yaw to
  83939. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  83940. * * upAxis: the up axis of the coordinate system
  83941. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  83942. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  83943. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  83944. * * adjustYaw: used to make an adjustment to the yaw of the bone
  83945. * * adjustPitch: used to make an adjustment to the pitch of the bone
  83946. * * adjustRoll: used to make an adjustment to the roll of the bone
  83947. **/
  83948. function BoneLookController(mesh, bone, target, options) {
  83949. /**
  83950. * The up axis of the coordinate system that is used when the bone is rotated
  83951. */
  83952. this.upAxis = BABYLON.Vector3.Up();
  83953. /**
  83954. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  83955. */
  83956. this.upAxisSpace = BABYLON.Space.LOCAL;
  83957. /**
  83958. * Used to make an adjustment to the yaw of the bone
  83959. */
  83960. this.adjustYaw = 0;
  83961. /**
  83962. * Used to make an adjustment to the pitch of the bone
  83963. */
  83964. this.adjustPitch = 0;
  83965. /**
  83966. * Used to make an adjustment to the roll of the bone
  83967. */
  83968. this.adjustRoll = 0;
  83969. /**
  83970. * 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)
  83971. */
  83972. this.slerpAmount = 1;
  83973. this._boneQuat = BABYLON.Quaternion.Identity();
  83974. this._slerping = false;
  83975. this._firstFrameSkipped = false;
  83976. this._fowardAxis = BABYLON.Vector3.Forward();
  83977. this.mesh = mesh;
  83978. this.bone = bone;
  83979. this.target = target;
  83980. if (options) {
  83981. if (options.adjustYaw) {
  83982. this.adjustYaw = options.adjustYaw;
  83983. }
  83984. if (options.adjustPitch) {
  83985. this.adjustPitch = options.adjustPitch;
  83986. }
  83987. if (options.adjustRoll) {
  83988. this.adjustRoll = options.adjustRoll;
  83989. }
  83990. if (options.maxYaw != null) {
  83991. this.maxYaw = options.maxYaw;
  83992. }
  83993. else {
  83994. this.maxYaw = Math.PI;
  83995. }
  83996. if (options.minYaw != null) {
  83997. this.minYaw = options.minYaw;
  83998. }
  83999. else {
  84000. this.minYaw = -Math.PI;
  84001. }
  84002. if (options.maxPitch != null) {
  84003. this.maxPitch = options.maxPitch;
  84004. }
  84005. else {
  84006. this.maxPitch = Math.PI;
  84007. }
  84008. if (options.minPitch != null) {
  84009. this.minPitch = options.minPitch;
  84010. }
  84011. else {
  84012. this.minPitch = -Math.PI;
  84013. }
  84014. if (options.slerpAmount != null) {
  84015. this.slerpAmount = options.slerpAmount;
  84016. }
  84017. if (options.upAxis != null) {
  84018. this.upAxis = options.upAxis;
  84019. }
  84020. if (options.upAxisSpace != null) {
  84021. this.upAxisSpace = options.upAxisSpace;
  84022. }
  84023. if (options.yawAxis != null || options.pitchAxis != null) {
  84024. var newYawAxis = BABYLON.Axis.Y;
  84025. var newPitchAxis = BABYLON.Axis.X;
  84026. if (options.yawAxis != null) {
  84027. newYawAxis = options.yawAxis.clone();
  84028. newYawAxis.normalize();
  84029. }
  84030. if (options.pitchAxis != null) {
  84031. newPitchAxis = options.pitchAxis.clone();
  84032. newPitchAxis.normalize();
  84033. }
  84034. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  84035. this._transformYawPitch = BABYLON.Matrix.Identity();
  84036. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  84037. this._transformYawPitchInv = this._transformYawPitch.clone();
  84038. this._transformYawPitch.invert();
  84039. }
  84040. }
  84041. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  84042. this.upAxisSpace = BABYLON.Space.LOCAL;
  84043. }
  84044. }
  84045. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  84046. /**
  84047. * Gets or sets the minimum yaw angle that the bone can look to
  84048. */
  84049. get: function () {
  84050. return this._minYaw;
  84051. },
  84052. set: function (value) {
  84053. this._minYaw = value;
  84054. this._minYawSin = Math.sin(value);
  84055. this._minYawCos = Math.cos(value);
  84056. if (this._maxYaw != null) {
  84057. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84058. this._yawRange = this._maxYaw - this._minYaw;
  84059. }
  84060. },
  84061. enumerable: true,
  84062. configurable: true
  84063. });
  84064. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  84065. /**
  84066. * Gets or sets the maximum yaw angle that the bone can look to
  84067. */
  84068. get: function () {
  84069. return this._maxYaw;
  84070. },
  84071. set: function (value) {
  84072. this._maxYaw = value;
  84073. this._maxYawSin = Math.sin(value);
  84074. this._maxYawCos = Math.cos(value);
  84075. if (this._minYaw != null) {
  84076. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84077. this._yawRange = this._maxYaw - this._minYaw;
  84078. }
  84079. },
  84080. enumerable: true,
  84081. configurable: true
  84082. });
  84083. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  84084. /**
  84085. * Gets or sets the minimum pitch angle that the bone can look to
  84086. */
  84087. get: function () {
  84088. return this._minPitch;
  84089. },
  84090. set: function (value) {
  84091. this._minPitch = value;
  84092. this._minPitchTan = Math.tan(value);
  84093. },
  84094. enumerable: true,
  84095. configurable: true
  84096. });
  84097. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  84098. /**
  84099. * Gets or sets the maximum pitch angle that the bone can look to
  84100. */
  84101. get: function () {
  84102. return this._maxPitch;
  84103. },
  84104. set: function (value) {
  84105. this._maxPitch = value;
  84106. this._maxPitchTan = Math.tan(value);
  84107. },
  84108. enumerable: true,
  84109. configurable: true
  84110. });
  84111. /**
  84112. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  84113. */
  84114. BoneLookController.prototype.update = function () {
  84115. //skip the first frame when slerping so that the mesh rotation is correct
  84116. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  84117. this._firstFrameSkipped = true;
  84118. return;
  84119. }
  84120. var bone = this.bone;
  84121. var bonePos = BoneLookController._tmpVecs[0];
  84122. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  84123. var target = this.target;
  84124. var _tmpMat1 = BoneLookController._tmpMats[0];
  84125. var _tmpMat2 = BoneLookController._tmpMats[1];
  84126. var mesh = this.mesh;
  84127. var parentBone = bone.getParent();
  84128. var upAxis = BoneLookController._tmpVecs[1];
  84129. upAxis.copyFrom(this.upAxis);
  84130. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  84131. if (this._transformYawPitch) {
  84132. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  84133. }
  84134. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  84135. }
  84136. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  84137. mesh.getDirectionToRef(upAxis, upAxis);
  84138. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  84139. upAxis.normalize();
  84140. }
  84141. }
  84142. var checkYaw = false;
  84143. var checkPitch = false;
  84144. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  84145. checkYaw = true;
  84146. }
  84147. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  84148. checkPitch = true;
  84149. }
  84150. if (checkYaw || checkPitch) {
  84151. var spaceMat = BoneLookController._tmpMats[2];
  84152. var spaceMatInv = BoneLookController._tmpMats[3];
  84153. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  84154. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  84155. }
  84156. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  84157. spaceMat.copyFrom(mesh.getWorldMatrix());
  84158. }
  84159. else {
  84160. var forwardAxis = BoneLookController._tmpVecs[2];
  84161. forwardAxis.copyFrom(this._fowardAxis);
  84162. if (this._transformYawPitch) {
  84163. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  84164. }
  84165. if (parentBone) {
  84166. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  84167. }
  84168. else {
  84169. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  84170. }
  84171. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  84172. rightAxis.normalize();
  84173. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  84174. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  84175. }
  84176. spaceMat.invertToRef(spaceMatInv);
  84177. var xzlen = null;
  84178. if (checkPitch) {
  84179. var localTarget = BoneLookController._tmpVecs[3];
  84180. target.subtractToRef(bonePos, localTarget);
  84181. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84182. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84183. var pitch = Math.atan2(localTarget.y, xzlen);
  84184. var newPitch = pitch;
  84185. if (pitch > this._maxPitch) {
  84186. localTarget.y = this._maxPitchTan * xzlen;
  84187. newPitch = this._maxPitch;
  84188. }
  84189. else if (pitch < this._minPitch) {
  84190. localTarget.y = this._minPitchTan * xzlen;
  84191. newPitch = this._minPitch;
  84192. }
  84193. if (pitch != newPitch) {
  84194. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84195. localTarget.addInPlace(bonePos);
  84196. target = localTarget;
  84197. }
  84198. }
  84199. if (checkYaw) {
  84200. var localTarget = BoneLookController._tmpVecs[4];
  84201. target.subtractToRef(bonePos, localTarget);
  84202. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84203. var yaw = Math.atan2(localTarget.x, localTarget.z);
  84204. var newYaw = yaw;
  84205. if (yaw > this._maxYaw || yaw < this._minYaw) {
  84206. if (xzlen == null) {
  84207. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84208. }
  84209. if (this._yawRange > Math.PI) {
  84210. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  84211. localTarget.z = this._maxYawCos * xzlen;
  84212. localTarget.x = this._maxYawSin * xzlen;
  84213. newYaw = this._maxYaw;
  84214. }
  84215. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  84216. localTarget.z = this._minYawCos * xzlen;
  84217. localTarget.x = this._minYawSin * xzlen;
  84218. newYaw = this._minYaw;
  84219. }
  84220. }
  84221. else {
  84222. if (yaw > this._maxYaw) {
  84223. localTarget.z = this._maxYawCos * xzlen;
  84224. localTarget.x = this._maxYawSin * xzlen;
  84225. newYaw = this._maxYaw;
  84226. }
  84227. else if (yaw < this._minYaw) {
  84228. localTarget.z = this._minYawCos * xzlen;
  84229. localTarget.x = this._minYawSin * xzlen;
  84230. newYaw = this._minYaw;
  84231. }
  84232. }
  84233. }
  84234. if (this._slerping && this._yawRange > Math.PI) {
  84235. //are we going to be crossing into the min/max region?
  84236. var boneFwd = BoneLookController._tmpVecs[8];
  84237. boneFwd.copyFrom(BABYLON.Axis.Z);
  84238. if (this._transformYawPitch) {
  84239. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  84240. }
  84241. var boneRotMat = BoneLookController._tmpMats[4];
  84242. this._boneQuat.toRotationMatrix(boneRotMat);
  84243. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  84244. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  84245. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  84246. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  84247. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  84248. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  84249. if (angBtwTar > angBtwMidYaw) {
  84250. if (xzlen == null) {
  84251. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84252. }
  84253. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  84254. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  84255. if (angBtwMin < angBtwMax) {
  84256. newYaw = boneYaw + Math.PI * .75;
  84257. localTarget.z = Math.cos(newYaw) * xzlen;
  84258. localTarget.x = Math.sin(newYaw) * xzlen;
  84259. }
  84260. else {
  84261. newYaw = boneYaw - Math.PI * .75;
  84262. localTarget.z = Math.cos(newYaw) * xzlen;
  84263. localTarget.x = Math.sin(newYaw) * xzlen;
  84264. }
  84265. }
  84266. }
  84267. if (yaw != newYaw) {
  84268. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84269. localTarget.addInPlace(bonePos);
  84270. target = localTarget;
  84271. }
  84272. }
  84273. }
  84274. var zaxis = BoneLookController._tmpVecs[5];
  84275. var xaxis = BoneLookController._tmpVecs[6];
  84276. var yaxis = BoneLookController._tmpVecs[7];
  84277. var _tmpQuat = BoneLookController._tmpQuat;
  84278. target.subtractToRef(bonePos, zaxis);
  84279. zaxis.normalize();
  84280. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  84281. xaxis.normalize();
  84282. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  84283. yaxis.normalize();
  84284. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  84285. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  84286. return;
  84287. }
  84288. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  84289. return;
  84290. }
  84291. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  84292. return;
  84293. }
  84294. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  84295. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  84296. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  84297. }
  84298. if (this.slerpAmount < 1) {
  84299. if (!this._slerping) {
  84300. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  84301. }
  84302. if (this._transformYawPitch) {
  84303. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84304. }
  84305. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  84306. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  84307. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  84308. this._slerping = true;
  84309. }
  84310. else {
  84311. if (this._transformYawPitch) {
  84312. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84313. }
  84314. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  84315. this._slerping = false;
  84316. }
  84317. };
  84318. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  84319. var angDiff = ang2 - ang1;
  84320. angDiff %= Math.PI * 2;
  84321. if (angDiff > Math.PI) {
  84322. angDiff -= Math.PI * 2;
  84323. }
  84324. else if (angDiff < -Math.PI) {
  84325. angDiff += Math.PI * 2;
  84326. }
  84327. return angDiff;
  84328. };
  84329. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  84330. ang1 %= (2 * Math.PI);
  84331. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84332. ang2 %= (2 * Math.PI);
  84333. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84334. var ab = 0;
  84335. if (ang1 < ang2) {
  84336. ab = ang2 - ang1;
  84337. }
  84338. else {
  84339. ab = ang1 - ang2;
  84340. }
  84341. if (ab > Math.PI) {
  84342. ab = Math.PI * 2 - ab;
  84343. }
  84344. return ab;
  84345. };
  84346. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  84347. ang %= (2 * Math.PI);
  84348. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  84349. ang1 %= (2 * Math.PI);
  84350. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84351. ang2 %= (2 * Math.PI);
  84352. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84353. if (ang1 < ang2) {
  84354. if (ang > ang1 && ang < ang2) {
  84355. return true;
  84356. }
  84357. }
  84358. else {
  84359. if (ang > ang2 && ang < ang1) {
  84360. return true;
  84361. }
  84362. }
  84363. return false;
  84364. };
  84365. 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()];
  84366. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  84367. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84368. return BoneLookController;
  84369. }());
  84370. BABYLON.BoneLookController = BoneLookController;
  84371. })(BABYLON || (BABYLON = {}));
  84372. //# sourceMappingURL=babylon.boneLookController.js.map
  84373. var BABYLON;
  84374. (function (BABYLON) {
  84375. /**
  84376. * Class used to handle skinning animations
  84377. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84378. */
  84379. var Skeleton = /** @class */ (function () {
  84380. /**
  84381. * Creates a new skeleton
  84382. * @param name defines the skeleton name
  84383. * @param id defines the skeleton Id
  84384. * @param scene defines the hosting scene
  84385. */
  84386. function Skeleton(
  84387. /** defines the skeleton name */
  84388. name,
  84389. /** defines the skeleton Id */
  84390. id, scene) {
  84391. this.name = name;
  84392. this.id = id;
  84393. /**
  84394. * Gets the list of child bones
  84395. */
  84396. this.bones = new Array();
  84397. /**
  84398. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  84399. */
  84400. this.needInitialSkinMatrix = false;
  84401. this._isDirty = true;
  84402. this._meshesWithPoseMatrix = new Array();
  84403. this._identity = BABYLON.Matrix.Identity();
  84404. this._ranges = {};
  84405. this._lastAbsoluteTransformsUpdateId = -1;
  84406. /**
  84407. * Specifies if the skeleton should be serialized
  84408. */
  84409. this.doNotSerialize = false;
  84410. this._animationPropertiesOverride = null;
  84411. // Events
  84412. /**
  84413. * An observable triggered before computing the skeleton's matrices
  84414. */
  84415. this.onBeforeComputeObservable = new BABYLON.Observable();
  84416. this.bones = [];
  84417. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84418. scene.skeletons.push(this);
  84419. //make sure it will recalculate the matrix next time prepare is called.
  84420. this._isDirty = true;
  84421. }
  84422. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  84423. /**
  84424. * Gets or sets the animation properties override
  84425. */
  84426. get: function () {
  84427. if (!this._animationPropertiesOverride) {
  84428. return this._scene.animationPropertiesOverride;
  84429. }
  84430. return this._animationPropertiesOverride;
  84431. },
  84432. set: function (value) {
  84433. this._animationPropertiesOverride = value;
  84434. },
  84435. enumerable: true,
  84436. configurable: true
  84437. });
  84438. // Members
  84439. /**
  84440. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  84441. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  84442. * @returns a Float32Array containing matrices data
  84443. */
  84444. Skeleton.prototype.getTransformMatrices = function (mesh) {
  84445. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  84446. return mesh._bonesTransformMatrices;
  84447. }
  84448. if (!this._transformMatrices) {
  84449. this.prepare();
  84450. }
  84451. return this._transformMatrices;
  84452. };
  84453. /**
  84454. * Gets the current hosting scene
  84455. * @returns a scene object
  84456. */
  84457. Skeleton.prototype.getScene = function () {
  84458. return this._scene;
  84459. };
  84460. // Methods
  84461. /**
  84462. * Gets a string representing the current skeleton data
  84463. * @param fullDetails defines a boolean indicating if we want a verbose version
  84464. * @returns a string representing the current skeleton data
  84465. */
  84466. Skeleton.prototype.toString = function (fullDetails) {
  84467. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  84468. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  84469. if (fullDetails) {
  84470. ret += ", Ranges: {";
  84471. var first = true;
  84472. for (var name_1 in this._ranges) {
  84473. if (first) {
  84474. ret += ", ";
  84475. first = false;
  84476. }
  84477. ret += name_1;
  84478. }
  84479. ret += "}";
  84480. }
  84481. return ret;
  84482. };
  84483. /**
  84484. * Get bone's index searching by name
  84485. * @param name defines bone's name to search for
  84486. * @return the indice of the bone. Returns -1 if not found
  84487. */
  84488. Skeleton.prototype.getBoneIndexByName = function (name) {
  84489. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  84490. if (this.bones[boneIndex].name === name) {
  84491. return boneIndex;
  84492. }
  84493. }
  84494. return -1;
  84495. };
  84496. /**
  84497. * Creater a new animation range
  84498. * @param name defines the name of the range
  84499. * @param from defines the start key
  84500. * @param to defines the end key
  84501. */
  84502. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  84503. // check name not already in use
  84504. if (!this._ranges[name]) {
  84505. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  84506. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84507. if (this.bones[i].animations[0]) {
  84508. this.bones[i].animations[0].createRange(name, from, to);
  84509. }
  84510. }
  84511. }
  84512. };
  84513. /**
  84514. * Delete a specific animation range
  84515. * @param name defines the name of the range
  84516. * @param deleteFrames defines if frames must be removed as well
  84517. */
  84518. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  84519. if (deleteFrames === void 0) { deleteFrames = true; }
  84520. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84521. if (this.bones[i].animations[0]) {
  84522. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  84523. }
  84524. }
  84525. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  84526. };
  84527. /**
  84528. * Gets a specific animation range
  84529. * @param name defines the name of the range to look for
  84530. * @returns the requested animation range or null if not found
  84531. */
  84532. Skeleton.prototype.getAnimationRange = function (name) {
  84533. return this._ranges[name];
  84534. };
  84535. /**
  84536. * Gets the list of all animation ranges defined on this skeleton
  84537. * @returns an array
  84538. */
  84539. Skeleton.prototype.getAnimationRanges = function () {
  84540. var animationRanges = [];
  84541. var name;
  84542. var i = 0;
  84543. for (name in this._ranges) {
  84544. animationRanges[i] = this._ranges[name];
  84545. i++;
  84546. }
  84547. return animationRanges;
  84548. };
  84549. /**
  84550. * Copy animation range from a source skeleton.
  84551. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  84552. * @param source defines the source skeleton
  84553. * @param name defines the name of the range to copy
  84554. * @param rescaleAsRequired defines if rescaling must be applied if required
  84555. * @returns true if operation was successful
  84556. */
  84557. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  84558. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84559. if (this._ranges[name] || !source.getAnimationRange(name)) {
  84560. return false;
  84561. }
  84562. var ret = true;
  84563. var frameOffset = this._getHighestAnimationFrame() + 1;
  84564. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  84565. var boneDict = {};
  84566. var sourceBones = source.bones;
  84567. var nBones;
  84568. var i;
  84569. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  84570. boneDict[sourceBones[i].name] = sourceBones[i];
  84571. }
  84572. if (this.bones.length !== sourceBones.length) {
  84573. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  84574. ret = false;
  84575. }
  84576. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  84577. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  84578. var boneName = this.bones[i].name;
  84579. var sourceBone = boneDict[boneName];
  84580. if (sourceBone) {
  84581. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  84582. }
  84583. else {
  84584. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  84585. ret = false;
  84586. }
  84587. }
  84588. // do not call createAnimationRange(), since it also is done to bones, which was already done
  84589. var range = source.getAnimationRange(name);
  84590. if (range) {
  84591. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  84592. }
  84593. return ret;
  84594. };
  84595. /**
  84596. * Forces the skeleton to go to rest pose
  84597. */
  84598. Skeleton.prototype.returnToRest = function () {
  84599. for (var index = 0; index < this.bones.length; index++) {
  84600. this.bones[index].returnToRest();
  84601. }
  84602. };
  84603. Skeleton.prototype._getHighestAnimationFrame = function () {
  84604. var ret = 0;
  84605. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84606. if (this.bones[i].animations[0]) {
  84607. var highest = this.bones[i].animations[0].getHighestFrame();
  84608. if (ret < highest) {
  84609. ret = highest;
  84610. }
  84611. }
  84612. }
  84613. return ret;
  84614. };
  84615. /**
  84616. * Begin a specific animation range
  84617. * @param name defines the name of the range to start
  84618. * @param loop defines if looping must be turned on (false by default)
  84619. * @param speedRatio defines the speed ratio to apply (1 by default)
  84620. * @param onAnimationEnd defines a callback which will be called when animation will end
  84621. * @returns a new animatable
  84622. */
  84623. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  84624. var range = this.getAnimationRange(name);
  84625. if (!range) {
  84626. return null;
  84627. }
  84628. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  84629. };
  84630. /** @hidden */
  84631. Skeleton.prototype._markAsDirty = function () {
  84632. this._isDirty = true;
  84633. };
  84634. /** @hidden */
  84635. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  84636. this._meshesWithPoseMatrix.push(mesh);
  84637. };
  84638. /** @hidden */
  84639. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  84640. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  84641. if (index > -1) {
  84642. this._meshesWithPoseMatrix.splice(index, 1);
  84643. }
  84644. };
  84645. /** @hidden */
  84646. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  84647. this.onBeforeComputeObservable.notifyObservers(this);
  84648. for (var index = 0; index < this.bones.length; index++) {
  84649. var bone = this.bones[index];
  84650. var parentBone = bone.getParent();
  84651. if (parentBone) {
  84652. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  84653. }
  84654. else {
  84655. if (initialSkinMatrix) {
  84656. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  84657. }
  84658. else {
  84659. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  84660. }
  84661. }
  84662. if (bone._index !== -1) {
  84663. var mappedIndex = bone._index === null ? index : bone._index;
  84664. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  84665. }
  84666. }
  84667. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  84668. };
  84669. /**
  84670. * Build all resources required to render a skeleton
  84671. */
  84672. Skeleton.prototype.prepare = function () {
  84673. if (!this._isDirty) {
  84674. return;
  84675. }
  84676. if (this.needInitialSkinMatrix) {
  84677. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  84678. var mesh = this._meshesWithPoseMatrix[index];
  84679. var poseMatrix = mesh.getPoseMatrix();
  84680. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  84681. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84682. }
  84683. if (this._synchronizedWithMesh !== mesh) {
  84684. this._synchronizedWithMesh = mesh;
  84685. // Prepare bones
  84686. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  84687. var bone = this.bones[boneIndex];
  84688. if (!bone.getParent()) {
  84689. var matrix = bone.getBaseMatrix();
  84690. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  84691. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  84692. }
  84693. }
  84694. }
  84695. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  84696. }
  84697. }
  84698. else {
  84699. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  84700. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84701. }
  84702. this._computeTransformMatrices(this._transformMatrices, null);
  84703. }
  84704. this._isDirty = false;
  84705. this._scene._activeBones.addCount(this.bones.length, false);
  84706. };
  84707. /**
  84708. * Gets the list of animatables currently running for this skeleton
  84709. * @returns an array of animatables
  84710. */
  84711. Skeleton.prototype.getAnimatables = function () {
  84712. if (!this._animatables || this._animatables.length !== this.bones.length) {
  84713. this._animatables = [];
  84714. for (var index = 0; index < this.bones.length; index++) {
  84715. this._animatables.push(this.bones[index]);
  84716. }
  84717. }
  84718. return this._animatables;
  84719. };
  84720. /**
  84721. * Clone the current skeleton
  84722. * @param name defines the name of the new skeleton
  84723. * @param id defines the id of the enw skeleton
  84724. * @returns the new skeleton
  84725. */
  84726. Skeleton.prototype.clone = function (name, id) {
  84727. var result = new Skeleton(name, id || name, this._scene);
  84728. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84729. for (var index = 0; index < this.bones.length; index++) {
  84730. var source = this.bones[index];
  84731. var parentBone = null;
  84732. var parent_1 = source.getParent();
  84733. if (parent_1) {
  84734. var parentIndex = this.bones.indexOf(parent_1);
  84735. parentBone = result.bones[parentIndex];
  84736. }
  84737. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  84738. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  84739. }
  84740. if (this._ranges) {
  84741. result._ranges = {};
  84742. for (var rangeName in this._ranges) {
  84743. var range = this._ranges[rangeName];
  84744. if (range) {
  84745. result._ranges[rangeName] = range.clone();
  84746. }
  84747. }
  84748. }
  84749. this._isDirty = true;
  84750. return result;
  84751. };
  84752. /**
  84753. * Enable animation blending for this skeleton
  84754. * @param blendingSpeed defines the blending speed to apply
  84755. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  84756. */
  84757. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  84758. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  84759. this.bones.forEach(function (bone) {
  84760. bone.animations.forEach(function (animation) {
  84761. animation.enableBlending = true;
  84762. animation.blendingSpeed = blendingSpeed;
  84763. });
  84764. });
  84765. };
  84766. /**
  84767. * Releases all resources associated with the current skeleton
  84768. */
  84769. Skeleton.prototype.dispose = function () {
  84770. this._meshesWithPoseMatrix = [];
  84771. // Animations
  84772. this.getScene().stopAnimation(this);
  84773. // Remove from scene
  84774. this.getScene().removeSkeleton(this);
  84775. };
  84776. /**
  84777. * Serialize the skeleton in a JSON object
  84778. * @returns a JSON object
  84779. */
  84780. Skeleton.prototype.serialize = function () {
  84781. var serializationObject = {};
  84782. serializationObject.name = this.name;
  84783. serializationObject.id = this.id;
  84784. if (this.dimensionsAtRest) {
  84785. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  84786. }
  84787. serializationObject.bones = [];
  84788. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84789. for (var index = 0; index < this.bones.length; index++) {
  84790. var bone = this.bones[index];
  84791. var parent_2 = bone.getParent();
  84792. var serializedBone = {
  84793. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  84794. name: bone.name,
  84795. matrix: bone.getBaseMatrix().toArray(),
  84796. rest: bone.getRestPose().toArray()
  84797. };
  84798. serializationObject.bones.push(serializedBone);
  84799. if (bone.length) {
  84800. serializedBone.length = bone.length;
  84801. }
  84802. if (bone.metadata) {
  84803. serializedBone.metadata = bone.metadata;
  84804. }
  84805. if (bone.animations && bone.animations.length > 0) {
  84806. serializedBone.animation = bone.animations[0].serialize();
  84807. }
  84808. serializationObject.ranges = [];
  84809. for (var name in this._ranges) {
  84810. var source = this._ranges[name];
  84811. if (!source) {
  84812. continue;
  84813. }
  84814. var range = {};
  84815. range.name = name;
  84816. range.from = source.from;
  84817. range.to = source.to;
  84818. serializationObject.ranges.push(range);
  84819. }
  84820. }
  84821. return serializationObject;
  84822. };
  84823. /**
  84824. * Creates a new skeleton from serialized data
  84825. * @param parsedSkeleton defines the serialized data
  84826. * @param scene defines the hosting scene
  84827. * @returns a new skeleton
  84828. */
  84829. Skeleton.Parse = function (parsedSkeleton, scene) {
  84830. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  84831. if (parsedSkeleton.dimensionsAtRest) {
  84832. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  84833. }
  84834. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  84835. var index;
  84836. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  84837. var parsedBone = parsedSkeleton.bones[index];
  84838. var parentBone = null;
  84839. if (parsedBone.parentBoneIndex > -1) {
  84840. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  84841. }
  84842. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  84843. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  84844. if (parsedBone.length) {
  84845. bone.length = parsedBone.length;
  84846. }
  84847. if (parsedBone.metadata) {
  84848. bone.metadata = parsedBone.metadata;
  84849. }
  84850. if (parsedBone.animation) {
  84851. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  84852. }
  84853. }
  84854. // placed after bones, so createAnimationRange can cascade down
  84855. if (parsedSkeleton.ranges) {
  84856. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  84857. var data = parsedSkeleton.ranges[index];
  84858. skeleton.createAnimationRange(data.name, data.from, data.to);
  84859. }
  84860. }
  84861. return skeleton;
  84862. };
  84863. /**
  84864. * Compute all node absolute transforms
  84865. * @param forceUpdate defines if computation must be done even if cache is up to date
  84866. */
  84867. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  84868. if (forceUpdate === void 0) { forceUpdate = false; }
  84869. var renderId = this._scene.getRenderId();
  84870. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  84871. this.bones[0].computeAbsoluteTransforms();
  84872. this._lastAbsoluteTransformsUpdateId = renderId;
  84873. }
  84874. };
  84875. /**
  84876. * Gets the root pose matrix
  84877. * @returns a matrix
  84878. */
  84879. Skeleton.prototype.getPoseMatrix = function () {
  84880. var poseMatrix = null;
  84881. if (this._meshesWithPoseMatrix.length > 0) {
  84882. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  84883. }
  84884. return poseMatrix;
  84885. };
  84886. /**
  84887. * Sorts bones per internal index
  84888. */
  84889. Skeleton.prototype.sortBones = function () {
  84890. var bones = new Array();
  84891. var visited = new Array(this.bones.length);
  84892. for (var index = 0; index < this.bones.length; index++) {
  84893. this._sortBones(index, bones, visited);
  84894. }
  84895. this.bones = bones;
  84896. };
  84897. Skeleton.prototype._sortBones = function (index, bones, visited) {
  84898. if (visited[index]) {
  84899. return;
  84900. }
  84901. visited[index] = true;
  84902. var bone = this.bones[index];
  84903. if (bone._index === undefined) {
  84904. bone._index = index;
  84905. }
  84906. var parentBone = bone.getParent();
  84907. if (parentBone) {
  84908. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  84909. }
  84910. bones.push(bone);
  84911. };
  84912. return Skeleton;
  84913. }());
  84914. BABYLON.Skeleton = Skeleton;
  84915. })(BABYLON || (BABYLON = {}));
  84916. //# sourceMappingURL=babylon.skeleton.js.map
  84917. var BABYLON;
  84918. (function (BABYLON) {
  84919. ;
  84920. /**
  84921. * This groups tools to convert HDR texture to native colors array.
  84922. */
  84923. var HDRTools = /** @class */ (function () {
  84924. function HDRTools() {
  84925. }
  84926. HDRTools.Ldexp = function (mantissa, exponent) {
  84927. if (exponent > 1023) {
  84928. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  84929. }
  84930. if (exponent < -1074) {
  84931. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  84932. }
  84933. return mantissa * Math.pow(2, exponent);
  84934. };
  84935. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  84936. if (exponent > 0) { /*nonzero pixel*/
  84937. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  84938. float32array[index + 0] = red * exponent;
  84939. float32array[index + 1] = green * exponent;
  84940. float32array[index + 2] = blue * exponent;
  84941. }
  84942. else {
  84943. float32array[index + 0] = 0;
  84944. float32array[index + 1] = 0;
  84945. float32array[index + 2] = 0;
  84946. }
  84947. };
  84948. HDRTools.readStringLine = function (uint8array, startIndex) {
  84949. var line = "";
  84950. var character = "";
  84951. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  84952. character = String.fromCharCode(uint8array[i]);
  84953. if (character == "\n") {
  84954. break;
  84955. }
  84956. line += character;
  84957. }
  84958. return line;
  84959. };
  84960. /**
  84961. * Reads header information from an RGBE texture stored in a native array.
  84962. * More information on this format are available here:
  84963. * https://en.wikipedia.org/wiki/RGBE_image_format
  84964. *
  84965. * @param uint8array The binary file stored in native array.
  84966. * @return The header information.
  84967. */
  84968. HDRTools.RGBE_ReadHeader = function (uint8array) {
  84969. var height = 0;
  84970. var width = 0;
  84971. var line = this.readStringLine(uint8array, 0);
  84972. if (line[0] != '#' || line[1] != '?') {
  84973. throw "Bad HDR Format.";
  84974. }
  84975. var endOfHeader = false;
  84976. var findFormat = false;
  84977. var lineIndex = 0;
  84978. do {
  84979. lineIndex += (line.length + 1);
  84980. line = this.readStringLine(uint8array, lineIndex);
  84981. if (line == "FORMAT=32-bit_rle_rgbe") {
  84982. findFormat = true;
  84983. }
  84984. else if (line.length == 0) {
  84985. endOfHeader = true;
  84986. }
  84987. } while (!endOfHeader);
  84988. if (!findFormat) {
  84989. throw "HDR Bad header format, unsupported FORMAT";
  84990. }
  84991. lineIndex += (line.length + 1);
  84992. line = this.readStringLine(uint8array, lineIndex);
  84993. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  84994. var match = sizeRegexp.exec(line);
  84995. // TODO. Support +Y and -X if needed.
  84996. if (!match || match.length < 3) {
  84997. throw "HDR Bad header format, no size";
  84998. }
  84999. width = parseInt(match[2]);
  85000. height = parseInt(match[1]);
  85001. if (width < 8 || width > 0x7fff) {
  85002. throw "HDR Bad header format, unsupported size";
  85003. }
  85004. lineIndex += (line.length + 1);
  85005. return {
  85006. height: height,
  85007. width: width,
  85008. dataPosition: lineIndex
  85009. };
  85010. };
  85011. /**
  85012. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  85013. * This RGBE texture needs to store the information as a panorama.
  85014. *
  85015. * More information on this format are available here:
  85016. * https://en.wikipedia.org/wiki/RGBE_image_format
  85017. *
  85018. * @param buffer The binary file stored in an array buffer.
  85019. * @param size The expected size of the extracted cubemap.
  85020. * @return The Cube Map information.
  85021. */
  85022. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  85023. var uint8array = new Uint8Array(buffer);
  85024. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  85025. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85026. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  85027. return cubeMapData;
  85028. };
  85029. /**
  85030. * Returns the pixels data extracted from an RGBE texture.
  85031. * This pixels will be stored left to right up to down in the R G B order in one array.
  85032. *
  85033. * More information on this format are available here:
  85034. * https://en.wikipedia.org/wiki/RGBE_image_format
  85035. *
  85036. * @param uint8array The binary file stored in an array buffer.
  85037. * @param hdrInfo The header information of the file.
  85038. * @return The pixels data in RGB right to left up to down order.
  85039. */
  85040. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  85041. // Keep for multi format supports.
  85042. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85043. };
  85044. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  85045. var num_scanlines = hdrInfo.height;
  85046. var scanline_width = hdrInfo.width;
  85047. var a, b, c, d, count;
  85048. var dataIndex = hdrInfo.dataPosition;
  85049. var index = 0, endIndex = 0, i = 0;
  85050. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  85051. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  85052. // 3 channels of 4 bytes per pixel in float.
  85053. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  85054. var resultArray = new Float32Array(resultBuffer);
  85055. // read in each successive scanline
  85056. while (num_scanlines > 0) {
  85057. a = uint8array[dataIndex++];
  85058. b = uint8array[dataIndex++];
  85059. c = uint8array[dataIndex++];
  85060. d = uint8array[dataIndex++];
  85061. if (a != 2 || b != 2 || (c & 0x80)) {
  85062. // this file is not run length encoded
  85063. throw "HDR Bad header format, not RLE";
  85064. }
  85065. if (((c << 8) | d) != scanline_width) {
  85066. throw "HDR Bad header format, wrong scan line width";
  85067. }
  85068. index = 0;
  85069. // read each of the four channels for the scanline into the buffer
  85070. for (i = 0; i < 4; i++) {
  85071. endIndex = (i + 1) * scanline_width;
  85072. while (index < endIndex) {
  85073. a = uint8array[dataIndex++];
  85074. b = uint8array[dataIndex++];
  85075. if (a > 128) {
  85076. // a run of the same value
  85077. count = a - 128;
  85078. if ((count == 0) || (count > endIndex - index)) {
  85079. throw "HDR Bad Format, bad scanline data (run)";
  85080. }
  85081. while (count-- > 0) {
  85082. scanLineArray[index++] = b;
  85083. }
  85084. }
  85085. else {
  85086. // a non-run
  85087. count = a;
  85088. if ((count == 0) || (count > endIndex - index)) {
  85089. throw "HDR Bad Format, bad scanline data (non-run)";
  85090. }
  85091. scanLineArray[index++] = b;
  85092. if (--count > 0) {
  85093. for (var j = 0; j < count; j++) {
  85094. scanLineArray[index++] = uint8array[dataIndex++];
  85095. }
  85096. }
  85097. }
  85098. }
  85099. }
  85100. // now convert data from buffer into floats
  85101. for (i = 0; i < scanline_width; i++) {
  85102. a = scanLineArray[i];
  85103. b = scanLineArray[i + scanline_width];
  85104. c = scanLineArray[i + 2 * scanline_width];
  85105. d = scanLineArray[i + 3 * scanline_width];
  85106. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  85107. }
  85108. num_scanlines--;
  85109. }
  85110. return resultArray;
  85111. };
  85112. return HDRTools;
  85113. }());
  85114. BABYLON.HDRTools = HDRTools;
  85115. })(BABYLON || (BABYLON = {}));
  85116. //# sourceMappingURL=babylon.hdr.js.map
  85117. var BABYLON;
  85118. (function (BABYLON) {
  85119. /**
  85120. * This represents a texture coming from an HDR input.
  85121. *
  85122. * The only supported format is currently panorama picture stored in RGBE format.
  85123. * Example of such files can be found on HDRLib: http://hdrlib.com/
  85124. */
  85125. var HDRCubeTexture = /** @class */ (function (_super) {
  85126. __extends(HDRCubeTexture, _super);
  85127. /**
  85128. * Instantiates an HDRTexture from the following parameters.
  85129. *
  85130. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  85131. * @param scene The scene the texture will be used in
  85132. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  85133. * @param noMipmap Forces to not generate the mipmap if true
  85134. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  85135. * @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)
  85136. * @param reserved Reserved flag for internal use.
  85137. */
  85138. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  85139. if (noMipmap === void 0) { noMipmap = false; }
  85140. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85141. if (gammaSpace === void 0) { gammaSpace = false; }
  85142. if (reserved === void 0) { reserved = false; }
  85143. if (onLoad === void 0) { onLoad = null; }
  85144. if (onError === void 0) { onError = null; }
  85145. var _this = _super.call(this, scene) || this;
  85146. _this._generateHarmonics = true;
  85147. _this._onLoad = null;
  85148. _this._onError = null;
  85149. /**
  85150. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  85151. */
  85152. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  85153. _this._isBlocking = true;
  85154. _this._rotationY = 0;
  85155. /**
  85156. * Gets or sets the center of the bounding box associated with the cube texture
  85157. * It must define where the camera used to render the texture was set
  85158. */
  85159. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  85160. if (!url) {
  85161. return _this;
  85162. }
  85163. _this.name = url;
  85164. _this.url = url;
  85165. _this.hasAlpha = false;
  85166. _this.isCube = true;
  85167. _this._textureMatrix = BABYLON.Matrix.Identity();
  85168. _this._onLoad = onLoad;
  85169. _this._onError = onError;
  85170. _this.gammaSpace = gammaSpace;
  85171. _this._noMipmap = noMipmap;
  85172. _this._size = size;
  85173. _this._texture = _this._getFromCache(url, _this._noMipmap);
  85174. if (!_this._texture) {
  85175. if (!scene.useDelayedTextureLoading) {
  85176. _this.loadTexture();
  85177. }
  85178. else {
  85179. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85180. }
  85181. }
  85182. return _this;
  85183. }
  85184. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  85185. /**
  85186. * Gets wether or not the texture is blocking during loading.
  85187. */
  85188. get: function () {
  85189. return this._isBlocking;
  85190. },
  85191. /**
  85192. * Sets wether or not the texture is blocking during loading.
  85193. */
  85194. set: function (value) {
  85195. this._isBlocking = value;
  85196. },
  85197. enumerable: true,
  85198. configurable: true
  85199. });
  85200. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  85201. /**
  85202. * Gets texture matrix rotation angle around Y axis radians.
  85203. */
  85204. get: function () {
  85205. return this._rotationY;
  85206. },
  85207. /**
  85208. * Sets texture matrix rotation angle around Y axis in radians.
  85209. */
  85210. set: function (value) {
  85211. this._rotationY = value;
  85212. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  85213. },
  85214. enumerable: true,
  85215. configurable: true
  85216. });
  85217. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  85218. get: function () {
  85219. return this._boundingBoxSize;
  85220. },
  85221. /**
  85222. * Gets or sets the size of the bounding box associated with the cube texture
  85223. * When defined, the cubemap will switch to local mode
  85224. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  85225. * @example https://www.babylonjs-playground.com/#RNASML
  85226. */
  85227. set: function (value) {
  85228. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  85229. return;
  85230. }
  85231. this._boundingBoxSize = value;
  85232. var scene = this.getScene();
  85233. if (scene) {
  85234. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  85235. }
  85236. },
  85237. enumerable: true,
  85238. configurable: true
  85239. });
  85240. /**
  85241. * Occurs when the file is raw .hdr file.
  85242. */
  85243. HDRCubeTexture.prototype.loadTexture = function () {
  85244. var _this = this;
  85245. var callback = function (buffer) {
  85246. _this.lodGenerationOffset = 0.0;
  85247. _this.lodGenerationScale = 0.8;
  85248. var scene = _this.getScene();
  85249. if (!scene) {
  85250. return null;
  85251. }
  85252. // Extract the raw linear data.
  85253. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  85254. // Generate harmonics if needed.
  85255. if (_this._generateHarmonics) {
  85256. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  85257. _this.sphericalPolynomial = sphericalPolynomial;
  85258. }
  85259. var results = [];
  85260. var byteArray = null;
  85261. // Push each faces.
  85262. for (var j = 0; j < 6; j++) {
  85263. // Create uintarray fallback.
  85264. if (!scene.getEngine().getCaps().textureFloat) {
  85265. // 3 channels of 1 bytes per pixel in bytes.
  85266. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  85267. byteArray = new Uint8Array(byteBuffer);
  85268. }
  85269. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  85270. // If special cases.
  85271. if (_this.gammaSpace || byteArray) {
  85272. for (var i = 0; i < _this._size * _this._size; i++) {
  85273. // Put in gamma space if requested.
  85274. if (_this.gammaSpace) {
  85275. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  85276. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  85277. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  85278. }
  85279. // Convert to int texture for fallback.
  85280. if (byteArray) {
  85281. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  85282. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  85283. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  85284. // May use luminance instead if the result is not accurate.
  85285. var max = Math.max(Math.max(r, g), b);
  85286. if (max > 255) {
  85287. var scale = 255 / max;
  85288. r *= scale;
  85289. g *= scale;
  85290. b *= scale;
  85291. }
  85292. byteArray[(i * 3) + 0] = r;
  85293. byteArray[(i * 3) + 1] = g;
  85294. byteArray[(i * 3) + 2] = b;
  85295. }
  85296. }
  85297. }
  85298. if (byteArray) {
  85299. results.push(byteArray);
  85300. }
  85301. else {
  85302. results.push(dataFace);
  85303. }
  85304. }
  85305. return results;
  85306. };
  85307. var scene = this.getScene();
  85308. if (scene) {
  85309. 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);
  85310. }
  85311. };
  85312. HDRCubeTexture.prototype.clone = function () {
  85313. var scene = this.getScene();
  85314. if (!scene) {
  85315. return this;
  85316. }
  85317. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  85318. // Base texture
  85319. newTexture.level = this.level;
  85320. newTexture.wrapU = this.wrapU;
  85321. newTexture.wrapV = this.wrapV;
  85322. newTexture.coordinatesIndex = this.coordinatesIndex;
  85323. newTexture.coordinatesMode = this.coordinatesMode;
  85324. return newTexture;
  85325. };
  85326. // Methods
  85327. HDRCubeTexture.prototype.delayLoad = function () {
  85328. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85329. return;
  85330. }
  85331. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85332. this._texture = this._getFromCache(this.url, this._noMipmap);
  85333. if (!this._texture) {
  85334. this.loadTexture();
  85335. }
  85336. };
  85337. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  85338. return this._textureMatrix;
  85339. };
  85340. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  85341. this._textureMatrix = value;
  85342. };
  85343. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85344. var texture = null;
  85345. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85346. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  85347. texture.name = parsedTexture.name;
  85348. texture.hasAlpha = parsedTexture.hasAlpha;
  85349. texture.level = parsedTexture.level;
  85350. texture.coordinatesMode = parsedTexture.coordinatesMode;
  85351. texture.isBlocking = parsedTexture.isBlocking;
  85352. }
  85353. if (texture) {
  85354. if (parsedTexture.boundingBoxPosition) {
  85355. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  85356. }
  85357. if (parsedTexture.boundingBoxSize) {
  85358. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  85359. }
  85360. if (parsedTexture.rotationY) {
  85361. texture.rotationY = parsedTexture.rotationY;
  85362. }
  85363. }
  85364. return texture;
  85365. };
  85366. HDRCubeTexture.prototype.serialize = function () {
  85367. if (!this.name) {
  85368. return null;
  85369. }
  85370. var serializationObject = {};
  85371. serializationObject.name = this.name;
  85372. serializationObject.hasAlpha = this.hasAlpha;
  85373. serializationObject.isCube = true;
  85374. serializationObject.level = this.level;
  85375. serializationObject.size = this._size;
  85376. serializationObject.coordinatesMode = this.coordinatesMode;
  85377. serializationObject.useInGammaSpace = this.gammaSpace;
  85378. serializationObject.generateHarmonics = this._generateHarmonics;
  85379. serializationObject.customType = "BABYLON.HDRCubeTexture";
  85380. serializationObject.noMipmap = this._noMipmap;
  85381. serializationObject.isBlocking = this._isBlocking;
  85382. serializationObject.rotationY = this._rotationY;
  85383. return serializationObject;
  85384. };
  85385. HDRCubeTexture._facesMapping = [
  85386. "right",
  85387. "left",
  85388. "up",
  85389. "down",
  85390. "front",
  85391. "back"
  85392. ];
  85393. return HDRCubeTexture;
  85394. }(BABYLON.BaseTexture));
  85395. BABYLON.HDRCubeTexture = HDRCubeTexture;
  85396. })(BABYLON || (BABYLON = {}));
  85397. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  85398. var BABYLON;
  85399. (function (BABYLON) {
  85400. /**
  85401. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  85402. */
  85403. var PanoramaToCubeMapTools = /** @class */ (function () {
  85404. function PanoramaToCubeMapTools() {
  85405. }
  85406. /**
  85407. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  85408. *
  85409. * @param float32Array The source data.
  85410. * @param inputWidth The width of the input panorama.
  85411. * @param inputhHeight The height of the input panorama.
  85412. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  85413. * @return The cubemap data
  85414. */
  85415. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  85416. if (!float32Array) {
  85417. throw "ConvertPanoramaToCubemap: input cannot be null";
  85418. }
  85419. if (float32Array.length != inputWidth * inputHeight * 3) {
  85420. throw "ConvertPanoramaToCubemap: input size is wrong";
  85421. }
  85422. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  85423. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  85424. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  85425. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  85426. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  85427. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  85428. return {
  85429. front: textureFront,
  85430. back: textureBack,
  85431. left: textureLeft,
  85432. right: textureRight,
  85433. up: textureUp,
  85434. down: textureDown,
  85435. size: size,
  85436. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85437. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  85438. gammaSpace: false,
  85439. };
  85440. };
  85441. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  85442. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  85443. var textureArray = new Float32Array(buffer);
  85444. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  85445. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  85446. var dy = 1 / texSize;
  85447. var fy = 0;
  85448. for (var y = 0; y < texSize; y++) {
  85449. var xv1 = faceData[0];
  85450. var xv2 = faceData[2];
  85451. for (var x = 0; x < texSize; x++) {
  85452. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  85453. v.normalize();
  85454. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  85455. // 3 channels per pixels
  85456. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  85457. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  85458. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  85459. xv1 = xv1.add(rotDX1);
  85460. xv2 = xv2.add(rotDX2);
  85461. }
  85462. fy += dy;
  85463. }
  85464. return textureArray;
  85465. };
  85466. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  85467. var theta = Math.atan2(vDir.z, vDir.x);
  85468. var phi = Math.acos(vDir.y);
  85469. while (theta < -Math.PI)
  85470. theta += 2 * Math.PI;
  85471. while (theta > Math.PI)
  85472. theta -= 2 * Math.PI;
  85473. var dx = theta / Math.PI;
  85474. var dy = phi / Math.PI;
  85475. // recenter.
  85476. dx = dx * 0.5 + 0.5;
  85477. var px = Math.round(dx * inputWidth);
  85478. if (px < 0)
  85479. px = 0;
  85480. else if (px >= inputWidth)
  85481. px = inputWidth - 1;
  85482. var py = Math.round(dy * inputHeight);
  85483. if (py < 0)
  85484. py = 0;
  85485. else if (py >= inputHeight)
  85486. py = inputHeight - 1;
  85487. var inputY = (inputHeight - py - 1);
  85488. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  85489. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  85490. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  85491. return {
  85492. r: r,
  85493. g: g,
  85494. b: b
  85495. };
  85496. };
  85497. PanoramaToCubeMapTools.FACE_FRONT = [
  85498. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85499. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85500. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85501. new BABYLON.Vector3(1.0, 1.0, -1.0)
  85502. ];
  85503. PanoramaToCubeMapTools.FACE_BACK = [
  85504. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85505. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85506. new BABYLON.Vector3(1.0, 1.0, 1.0),
  85507. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  85508. ];
  85509. PanoramaToCubeMapTools.FACE_RIGHT = [
  85510. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85511. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85512. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85513. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85514. ];
  85515. PanoramaToCubeMapTools.FACE_LEFT = [
  85516. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85517. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85518. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85519. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  85520. ];
  85521. PanoramaToCubeMapTools.FACE_DOWN = [
  85522. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85523. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85524. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85525. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85526. ];
  85527. PanoramaToCubeMapTools.FACE_UP = [
  85528. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85529. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85530. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85531. new BABYLON.Vector3(1.0, -1.0, -1.0)
  85532. ];
  85533. return PanoramaToCubeMapTools;
  85534. }());
  85535. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  85536. })(BABYLON || (BABYLON = {}));
  85537. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  85538. var BABYLON;
  85539. (function (BABYLON) {
  85540. var IndexedVector2 = /** @class */ (function (_super) {
  85541. __extends(IndexedVector2, _super);
  85542. function IndexedVector2(original, index) {
  85543. var _this = _super.call(this, original.x, original.y) || this;
  85544. _this.index = index;
  85545. return _this;
  85546. }
  85547. return IndexedVector2;
  85548. }(BABYLON.Vector2));
  85549. var PolygonPoints = /** @class */ (function () {
  85550. function PolygonPoints() {
  85551. this.elements = new Array();
  85552. }
  85553. PolygonPoints.prototype.add = function (originalPoints) {
  85554. var _this = this;
  85555. var result = new Array();
  85556. originalPoints.forEach(function (point) {
  85557. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  85558. var newPoint = new IndexedVector2(point, _this.elements.length);
  85559. result.push(newPoint);
  85560. _this.elements.push(newPoint);
  85561. }
  85562. });
  85563. return result;
  85564. };
  85565. PolygonPoints.prototype.computeBounds = function () {
  85566. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85567. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85568. this.elements.forEach(function (point) {
  85569. // x
  85570. if (point.x < lmin.x) {
  85571. lmin.x = point.x;
  85572. }
  85573. else if (point.x > lmax.x) {
  85574. lmax.x = point.x;
  85575. }
  85576. // y
  85577. if (point.y < lmin.y) {
  85578. lmin.y = point.y;
  85579. }
  85580. else if (point.y > lmax.y) {
  85581. lmax.y = point.y;
  85582. }
  85583. });
  85584. return {
  85585. min: lmin,
  85586. max: lmax,
  85587. width: lmax.x - lmin.x,
  85588. height: lmax.y - lmin.y
  85589. };
  85590. };
  85591. return PolygonPoints;
  85592. }());
  85593. var Polygon = /** @class */ (function () {
  85594. function Polygon() {
  85595. }
  85596. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  85597. return [
  85598. new BABYLON.Vector2(xmin, ymin),
  85599. new BABYLON.Vector2(xmax, ymin),
  85600. new BABYLON.Vector2(xmax, ymax),
  85601. new BABYLON.Vector2(xmin, ymax)
  85602. ];
  85603. };
  85604. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  85605. if (cx === void 0) { cx = 0; }
  85606. if (cy === void 0) { cy = 0; }
  85607. if (numberOfSides === void 0) { numberOfSides = 32; }
  85608. var result = new Array();
  85609. var angle = 0;
  85610. var increment = (Math.PI * 2) / numberOfSides;
  85611. for (var i = 0; i < numberOfSides; i++) {
  85612. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  85613. angle -= increment;
  85614. }
  85615. return result;
  85616. };
  85617. Polygon.Parse = function (input) {
  85618. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  85619. var i, result = [];
  85620. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  85621. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  85622. }
  85623. return result;
  85624. };
  85625. Polygon.StartingAt = function (x, y) {
  85626. return BABYLON.Path2.StartingAt(x, y);
  85627. };
  85628. return Polygon;
  85629. }());
  85630. BABYLON.Polygon = Polygon;
  85631. var PolygonMeshBuilder = /** @class */ (function () {
  85632. function PolygonMeshBuilder(name, contours, scene) {
  85633. this._points = new PolygonPoints();
  85634. this._outlinepoints = new PolygonPoints();
  85635. this._holes = new Array();
  85636. this._epoints = new Array();
  85637. this._eholes = new Array();
  85638. this._name = name;
  85639. this._scene = scene;
  85640. var points;
  85641. if (contours instanceof BABYLON.Path2) {
  85642. points = contours.getPoints();
  85643. }
  85644. else {
  85645. points = contours;
  85646. }
  85647. this._addToepoint(points);
  85648. this._points.add(points);
  85649. this._outlinepoints.add(points);
  85650. if (typeof earcut === 'undefined') {
  85651. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  85652. }
  85653. }
  85654. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  85655. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  85656. var p = points_1[_i];
  85657. this._epoints.push(p.x, p.y);
  85658. }
  85659. };
  85660. PolygonMeshBuilder.prototype.addHole = function (hole) {
  85661. this._points.add(hole);
  85662. var holepoints = new PolygonPoints();
  85663. holepoints.add(hole);
  85664. this._holes.push(holepoints);
  85665. this._eholes.push(this._epoints.length / 2);
  85666. this._addToepoint(hole);
  85667. return this;
  85668. };
  85669. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  85670. var _this = this;
  85671. if (updatable === void 0) { updatable = false; }
  85672. if (depth === void 0) { depth = 0; }
  85673. var result = new BABYLON.Mesh(this._name, this._scene);
  85674. var normals = new Array();
  85675. var positions = new Array();
  85676. var uvs = new Array();
  85677. var bounds = this._points.computeBounds();
  85678. this._points.elements.forEach(function (p) {
  85679. normals.push(0, 1.0, 0);
  85680. positions.push(p.x, 0, p.y);
  85681. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  85682. });
  85683. var indices = new Array();
  85684. var res = earcut(this._epoints, this._eholes, 2);
  85685. for (var i = 0; i < res.length; i++) {
  85686. indices.push(res[i]);
  85687. }
  85688. if (depth > 0) {
  85689. var positionscount = (positions.length / 3); //get the current pointcount
  85690. this._points.elements.forEach(function (p) {
  85691. normals.push(0, -1.0, 0);
  85692. positions.push(p.x, -depth, p.y);
  85693. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  85694. });
  85695. var totalCount = indices.length;
  85696. for (var i = 0; i < totalCount; i += 3) {
  85697. var i0 = indices[i + 0];
  85698. var i1 = indices[i + 1];
  85699. var i2 = indices[i + 2];
  85700. indices.push(i2 + positionscount);
  85701. indices.push(i1 + positionscount);
  85702. indices.push(i0 + positionscount);
  85703. }
  85704. //Add the sides
  85705. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  85706. this._holes.forEach(function (hole) {
  85707. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  85708. });
  85709. }
  85710. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  85711. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  85712. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  85713. result.setIndices(indices);
  85714. return result;
  85715. };
  85716. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  85717. var StartIndex = positions.length / 3;
  85718. var ulength = 0;
  85719. for (var i = 0; i < points.elements.length; i++) {
  85720. var p = points.elements[i];
  85721. var p1;
  85722. if ((i + 1) > points.elements.length - 1) {
  85723. p1 = points.elements[0];
  85724. }
  85725. else {
  85726. p1 = points.elements[i + 1];
  85727. }
  85728. positions.push(p.x, 0, p.y);
  85729. positions.push(p.x, -depth, p.y);
  85730. positions.push(p1.x, 0, p1.y);
  85731. positions.push(p1.x, -depth, p1.y);
  85732. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  85733. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  85734. var v3 = v2.subtract(v1);
  85735. var v4 = new BABYLON.Vector3(0, 1, 0);
  85736. var vn = BABYLON.Vector3.Cross(v3, v4);
  85737. vn = vn.normalize();
  85738. uvs.push(ulength / bounds.width, 0);
  85739. uvs.push(ulength / bounds.width, 1);
  85740. ulength += v3.length();
  85741. uvs.push((ulength / bounds.width), 0);
  85742. uvs.push((ulength / bounds.width), 1);
  85743. if (!flip) {
  85744. normals.push(-vn.x, -vn.y, -vn.z);
  85745. normals.push(-vn.x, -vn.y, -vn.z);
  85746. normals.push(-vn.x, -vn.y, -vn.z);
  85747. normals.push(-vn.x, -vn.y, -vn.z);
  85748. indices.push(StartIndex);
  85749. indices.push(StartIndex + 1);
  85750. indices.push(StartIndex + 2);
  85751. indices.push(StartIndex + 1);
  85752. indices.push(StartIndex + 3);
  85753. indices.push(StartIndex + 2);
  85754. }
  85755. else {
  85756. normals.push(vn.x, vn.y, vn.z);
  85757. normals.push(vn.x, vn.y, vn.z);
  85758. normals.push(vn.x, vn.y, vn.z);
  85759. normals.push(vn.x, vn.y, vn.z);
  85760. indices.push(StartIndex);
  85761. indices.push(StartIndex + 2);
  85762. indices.push(StartIndex + 1);
  85763. indices.push(StartIndex + 1);
  85764. indices.push(StartIndex + 2);
  85765. indices.push(StartIndex + 3);
  85766. }
  85767. StartIndex += 4;
  85768. }
  85769. ;
  85770. };
  85771. return PolygonMeshBuilder;
  85772. }());
  85773. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  85774. })(BABYLON || (BABYLON = {}));
  85775. //# sourceMappingURL=babylon.polygonMesh.js.map
  85776. var BABYLON;
  85777. (function (BABYLON) {
  85778. // Unique ID when we import meshes from Babylon to CSG
  85779. var currentCSGMeshId = 0;
  85780. // # class Vertex
  85781. // Represents a vertex of a polygon. Use your own vertex class instead of this
  85782. // one to provide additional features like texture coordinates and vertex
  85783. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  85784. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  85785. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  85786. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  85787. // is not used anywhere else.
  85788. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  85789. var Vertex = /** @class */ (function () {
  85790. function Vertex(pos, normal, uv) {
  85791. this.pos = pos;
  85792. this.normal = normal;
  85793. this.uv = uv;
  85794. }
  85795. Vertex.prototype.clone = function () {
  85796. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  85797. };
  85798. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  85799. // orientation of a polygon is flipped.
  85800. Vertex.prototype.flip = function () {
  85801. this.normal = this.normal.scale(-1);
  85802. };
  85803. // Create a new vertex between this vertex and `other` by linearly
  85804. // interpolating all properties using a parameter of `t`. Subclasses should
  85805. // override this to interpolate additional properties.
  85806. Vertex.prototype.interpolate = function (other, t) {
  85807. 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));
  85808. };
  85809. return Vertex;
  85810. }());
  85811. // # class Plane
  85812. // Represents a plane in 3D space.
  85813. var Plane = /** @class */ (function () {
  85814. function Plane(normal, w) {
  85815. this.normal = normal;
  85816. this.w = w;
  85817. }
  85818. Plane.FromPoints = function (a, b, c) {
  85819. var v0 = c.subtract(a);
  85820. var v1 = b.subtract(a);
  85821. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  85822. return null;
  85823. }
  85824. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  85825. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  85826. };
  85827. Plane.prototype.clone = function () {
  85828. return new Plane(this.normal.clone(), this.w);
  85829. };
  85830. Plane.prototype.flip = function () {
  85831. this.normal.scaleInPlace(-1);
  85832. this.w = -this.w;
  85833. };
  85834. // Split `polygon` by this plane if needed, then put the polygon or polygon
  85835. // fragments in the appropriate lists. Coplanar polygons go into either
  85836. // `coplanarFront` or `coplanarBack` depending on their orientation with
  85837. // respect to this plane. Polygons in front or in back of this plane go into
  85838. // either `front` or `back`.
  85839. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  85840. var COPLANAR = 0;
  85841. var FRONT = 1;
  85842. var BACK = 2;
  85843. var SPANNING = 3;
  85844. // Classify each point as well as the entire polygon into one of the above
  85845. // four classes.
  85846. var polygonType = 0;
  85847. var types = [];
  85848. var i;
  85849. var t;
  85850. for (i = 0; i < polygon.vertices.length; i++) {
  85851. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  85852. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  85853. polygonType |= type;
  85854. types.push(type);
  85855. }
  85856. // Put the polygon in the correct list, splitting it when necessary.
  85857. switch (polygonType) {
  85858. case COPLANAR:
  85859. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  85860. break;
  85861. case FRONT:
  85862. front.push(polygon);
  85863. break;
  85864. case BACK:
  85865. back.push(polygon);
  85866. break;
  85867. case SPANNING:
  85868. var f = [], b = [];
  85869. for (i = 0; i < polygon.vertices.length; i++) {
  85870. var j = (i + 1) % polygon.vertices.length;
  85871. var ti = types[i], tj = types[j];
  85872. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  85873. if (ti !== BACK)
  85874. f.push(vi);
  85875. if (ti !== FRONT)
  85876. b.push(ti !== BACK ? vi.clone() : vi);
  85877. if ((ti | tj) === SPANNING) {
  85878. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  85879. var v = vi.interpolate(vj, t);
  85880. f.push(v);
  85881. b.push(v.clone());
  85882. }
  85883. }
  85884. var poly;
  85885. if (f.length >= 3) {
  85886. poly = new Polygon(f, polygon.shared);
  85887. if (poly.plane)
  85888. front.push(poly);
  85889. }
  85890. if (b.length >= 3) {
  85891. poly = new Polygon(b, polygon.shared);
  85892. if (poly.plane)
  85893. back.push(poly);
  85894. }
  85895. break;
  85896. }
  85897. };
  85898. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  85899. // point is on the plane.
  85900. Plane.EPSILON = 1e-5;
  85901. return Plane;
  85902. }());
  85903. // # class Polygon
  85904. // Represents a convex polygon. The vertices used to initialize a polygon must
  85905. // be coplanar and form a convex loop.
  85906. //
  85907. // Each convex polygon has a `shared` property, which is shared between all
  85908. // polygons that are clones of each other or were split from the same polygon.
  85909. // This can be used to define per-polygon properties (such as surface color).
  85910. var Polygon = /** @class */ (function () {
  85911. function Polygon(vertices, shared) {
  85912. this.vertices = vertices;
  85913. this.shared = shared;
  85914. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  85915. }
  85916. Polygon.prototype.clone = function () {
  85917. var vertices = this.vertices.map(function (v) { return v.clone(); });
  85918. return new Polygon(vertices, this.shared);
  85919. };
  85920. Polygon.prototype.flip = function () {
  85921. this.vertices.reverse().map(function (v) { v.flip(); });
  85922. this.plane.flip();
  85923. };
  85924. return Polygon;
  85925. }());
  85926. // # class Node
  85927. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  85928. // by picking a polygon to split along. That polygon (and all other coplanar
  85929. // polygons) are added directly to that node and the other polygons are added to
  85930. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  85931. // no distinction between internal and leaf nodes.
  85932. var Node = /** @class */ (function () {
  85933. function Node(polygons) {
  85934. this.plane = null;
  85935. this.front = null;
  85936. this.back = null;
  85937. this.polygons = new Array();
  85938. if (polygons) {
  85939. this.build(polygons);
  85940. }
  85941. }
  85942. Node.prototype.clone = function () {
  85943. var node = new Node();
  85944. node.plane = this.plane && this.plane.clone();
  85945. node.front = this.front && this.front.clone();
  85946. node.back = this.back && this.back.clone();
  85947. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  85948. return node;
  85949. };
  85950. // Convert solid space to empty space and empty space to solid space.
  85951. Node.prototype.invert = function () {
  85952. for (var i = 0; i < this.polygons.length; i++) {
  85953. this.polygons[i].flip();
  85954. }
  85955. if (this.plane) {
  85956. this.plane.flip();
  85957. }
  85958. if (this.front) {
  85959. this.front.invert();
  85960. }
  85961. if (this.back) {
  85962. this.back.invert();
  85963. }
  85964. var temp = this.front;
  85965. this.front = this.back;
  85966. this.back = temp;
  85967. };
  85968. // Recursively remove all polygons in `polygons` that are inside this BSP
  85969. // tree.
  85970. Node.prototype.clipPolygons = function (polygons) {
  85971. if (!this.plane)
  85972. return polygons.slice();
  85973. var front = new Array(), back = new Array();
  85974. for (var i = 0; i < polygons.length; i++) {
  85975. this.plane.splitPolygon(polygons[i], front, back, front, back);
  85976. }
  85977. if (this.front) {
  85978. front = this.front.clipPolygons(front);
  85979. }
  85980. if (this.back) {
  85981. back = this.back.clipPolygons(back);
  85982. }
  85983. else {
  85984. back = [];
  85985. }
  85986. return front.concat(back);
  85987. };
  85988. // Remove all polygons in this BSP tree that are inside the other BSP tree
  85989. // `bsp`.
  85990. Node.prototype.clipTo = function (bsp) {
  85991. this.polygons = bsp.clipPolygons(this.polygons);
  85992. if (this.front)
  85993. this.front.clipTo(bsp);
  85994. if (this.back)
  85995. this.back.clipTo(bsp);
  85996. };
  85997. // Return a list of all polygons in this BSP tree.
  85998. Node.prototype.allPolygons = function () {
  85999. var polygons = this.polygons.slice();
  86000. if (this.front)
  86001. polygons = polygons.concat(this.front.allPolygons());
  86002. if (this.back)
  86003. polygons = polygons.concat(this.back.allPolygons());
  86004. return polygons;
  86005. };
  86006. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  86007. // new polygons are filtered down to the bottom of the tree and become new
  86008. // nodes there. Each set of polygons is partitioned using the first polygon
  86009. // (no heuristic is used to pick a good split).
  86010. Node.prototype.build = function (polygons) {
  86011. if (!polygons.length)
  86012. return;
  86013. if (!this.plane)
  86014. this.plane = polygons[0].plane.clone();
  86015. var front = new Array(), back = new Array();
  86016. for (var i = 0; i < polygons.length; i++) {
  86017. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  86018. }
  86019. if (front.length) {
  86020. if (!this.front)
  86021. this.front = new Node();
  86022. this.front.build(front);
  86023. }
  86024. if (back.length) {
  86025. if (!this.back)
  86026. this.back = new Node();
  86027. this.back.build(back);
  86028. }
  86029. };
  86030. return Node;
  86031. }());
  86032. var CSG = /** @class */ (function () {
  86033. function CSG() {
  86034. this.polygons = new Array();
  86035. }
  86036. // Convert BABYLON.Mesh to BABYLON.CSG
  86037. CSG.FromMesh = function (mesh) {
  86038. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  86039. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  86040. if (mesh instanceof BABYLON.Mesh) {
  86041. mesh.computeWorldMatrix(true);
  86042. matrix = mesh.getWorldMatrix();
  86043. meshPosition = mesh.position.clone();
  86044. meshRotation = mesh.rotation.clone();
  86045. if (mesh.rotationQuaternion) {
  86046. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  86047. }
  86048. meshScaling = mesh.scaling.clone();
  86049. }
  86050. else {
  86051. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  86052. }
  86053. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  86054. var subMeshes = mesh.subMeshes;
  86055. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  86056. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  86057. vertices = [];
  86058. for (var j = 0; j < 3; j++) {
  86059. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  86060. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  86061. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  86062. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  86063. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  86064. vertex = new Vertex(position, normal, uv);
  86065. vertices.push(vertex);
  86066. }
  86067. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  86068. // To handle the case of degenerated triangle
  86069. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  86070. if (polygon.plane)
  86071. polygons.push(polygon);
  86072. }
  86073. }
  86074. var csg = CSG.FromPolygons(polygons);
  86075. csg.matrix = matrix;
  86076. csg.position = meshPosition;
  86077. csg.rotation = meshRotation;
  86078. csg.scaling = meshScaling;
  86079. csg.rotationQuaternion = meshRotationQuaternion;
  86080. currentCSGMeshId++;
  86081. return csg;
  86082. };
  86083. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  86084. CSG.FromPolygons = function (polygons) {
  86085. var csg = new CSG();
  86086. csg.polygons = polygons;
  86087. return csg;
  86088. };
  86089. CSG.prototype.clone = function () {
  86090. var csg = new CSG();
  86091. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  86092. csg.copyTransformAttributes(this);
  86093. return csg;
  86094. };
  86095. CSG.prototype.union = function (csg) {
  86096. var a = new Node(this.clone().polygons);
  86097. var b = new Node(csg.clone().polygons);
  86098. a.clipTo(b);
  86099. b.clipTo(a);
  86100. b.invert();
  86101. b.clipTo(a);
  86102. b.invert();
  86103. a.build(b.allPolygons());
  86104. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86105. };
  86106. CSG.prototype.unionInPlace = function (csg) {
  86107. var a = new Node(this.polygons);
  86108. var b = new Node(csg.polygons);
  86109. a.clipTo(b);
  86110. b.clipTo(a);
  86111. b.invert();
  86112. b.clipTo(a);
  86113. b.invert();
  86114. a.build(b.allPolygons());
  86115. this.polygons = a.allPolygons();
  86116. };
  86117. CSG.prototype.subtract = function (csg) {
  86118. var a = new Node(this.clone().polygons);
  86119. var b = new Node(csg.clone().polygons);
  86120. a.invert();
  86121. a.clipTo(b);
  86122. b.clipTo(a);
  86123. b.invert();
  86124. b.clipTo(a);
  86125. b.invert();
  86126. a.build(b.allPolygons());
  86127. a.invert();
  86128. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86129. };
  86130. CSG.prototype.subtractInPlace = function (csg) {
  86131. var a = new Node(this.polygons);
  86132. var b = new Node(csg.polygons);
  86133. a.invert();
  86134. a.clipTo(b);
  86135. b.clipTo(a);
  86136. b.invert();
  86137. b.clipTo(a);
  86138. b.invert();
  86139. a.build(b.allPolygons());
  86140. a.invert();
  86141. this.polygons = a.allPolygons();
  86142. };
  86143. CSG.prototype.intersect = function (csg) {
  86144. var a = new Node(this.clone().polygons);
  86145. var b = new Node(csg.clone().polygons);
  86146. a.invert();
  86147. b.clipTo(a);
  86148. b.invert();
  86149. a.clipTo(b);
  86150. b.clipTo(a);
  86151. a.build(b.allPolygons());
  86152. a.invert();
  86153. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86154. };
  86155. CSG.prototype.intersectInPlace = function (csg) {
  86156. var a = new Node(this.polygons);
  86157. var b = new Node(csg.polygons);
  86158. a.invert();
  86159. b.clipTo(a);
  86160. b.invert();
  86161. a.clipTo(b);
  86162. b.clipTo(a);
  86163. a.build(b.allPolygons());
  86164. a.invert();
  86165. this.polygons = a.allPolygons();
  86166. };
  86167. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  86168. // not modified.
  86169. CSG.prototype.inverse = function () {
  86170. var csg = this.clone();
  86171. csg.inverseInPlace();
  86172. return csg;
  86173. };
  86174. CSG.prototype.inverseInPlace = function () {
  86175. this.polygons.map(function (p) { p.flip(); });
  86176. };
  86177. // This is used to keep meshes transformations so they can be restored
  86178. // when we build back a Babylon Mesh
  86179. // NB : All CSG operations are performed in world coordinates
  86180. CSG.prototype.copyTransformAttributes = function (csg) {
  86181. this.matrix = csg.matrix;
  86182. this.position = csg.position;
  86183. this.rotation = csg.rotation;
  86184. this.scaling = csg.scaling;
  86185. this.rotationQuaternion = csg.rotationQuaternion;
  86186. return this;
  86187. };
  86188. // Build Raw mesh from CSG
  86189. // Coordinates here are in world space
  86190. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  86191. var matrix = this.matrix.clone();
  86192. matrix.invert();
  86193. 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;
  86194. if (keepSubMeshes) {
  86195. // Sort Polygons, since subMeshes are indices range
  86196. polygons.sort(function (a, b) {
  86197. if (a.shared.meshId === b.shared.meshId) {
  86198. return a.shared.subMeshId - b.shared.subMeshId;
  86199. }
  86200. else {
  86201. return a.shared.meshId - b.shared.meshId;
  86202. }
  86203. });
  86204. }
  86205. for (var i = 0, il = polygons.length; i < il; i++) {
  86206. polygon = polygons[i];
  86207. // Building SubMeshes
  86208. if (!subMesh_dict[polygon.shared.meshId]) {
  86209. subMesh_dict[polygon.shared.meshId] = {};
  86210. }
  86211. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  86212. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  86213. indexStart: +Infinity,
  86214. indexEnd: -Infinity,
  86215. materialIndex: polygon.shared.materialIndex
  86216. };
  86217. }
  86218. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  86219. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  86220. polygonIndices[0] = 0;
  86221. polygonIndices[1] = j - 1;
  86222. polygonIndices[2] = j;
  86223. for (var k = 0; k < 3; k++) {
  86224. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  86225. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  86226. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  86227. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  86228. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  86229. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  86230. // Check if 2 points can be merged
  86231. if (!(typeof vertex_idx !== 'undefined' &&
  86232. normals[vertex_idx * 3] === localNormal.x &&
  86233. normals[vertex_idx * 3 + 1] === localNormal.y &&
  86234. normals[vertex_idx * 3 + 2] === localNormal.z &&
  86235. uvs[vertex_idx * 2] === uv.x &&
  86236. uvs[vertex_idx * 2 + 1] === uv.y)) {
  86237. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  86238. uvs.push(uv.x, uv.y);
  86239. normals.push(normal.x, normal.y, normal.z);
  86240. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  86241. }
  86242. indices.push(vertex_idx);
  86243. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  86244. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  86245. currentIndex++;
  86246. }
  86247. }
  86248. }
  86249. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  86250. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  86251. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  86252. mesh.setIndices(indices, null);
  86253. if (keepSubMeshes) {
  86254. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  86255. var materialIndexOffset = 0, materialMaxIndex;
  86256. mesh.subMeshes = new Array();
  86257. for (var m in subMesh_dict) {
  86258. materialMaxIndex = -1;
  86259. for (var sm in subMesh_dict[m]) {
  86260. subMesh_obj = subMesh_dict[m][sm];
  86261. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  86262. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  86263. }
  86264. materialIndexOffset += ++materialMaxIndex;
  86265. }
  86266. }
  86267. return mesh;
  86268. };
  86269. // Build Mesh from CSG taking material and transforms into account
  86270. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  86271. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  86272. mesh.material = material;
  86273. mesh.position.copyFrom(this.position);
  86274. mesh.rotation.copyFrom(this.rotation);
  86275. if (this.rotationQuaternion) {
  86276. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  86277. }
  86278. mesh.scaling.copyFrom(this.scaling);
  86279. mesh.computeWorldMatrix(true);
  86280. return mesh;
  86281. };
  86282. return CSG;
  86283. }());
  86284. BABYLON.CSG = CSG;
  86285. })(BABYLON || (BABYLON = {}));
  86286. //# sourceMappingURL=babylon.csg.js.map
  86287. var BABYLON;
  86288. (function (BABYLON) {
  86289. var LensFlare = /** @class */ (function () {
  86290. function LensFlare(size, position, color, imgUrl, system) {
  86291. this.size = size;
  86292. this.position = position;
  86293. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86294. this.color = color || new BABYLON.Color3(1, 1, 1);
  86295. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  86296. this._system = system;
  86297. system.lensFlares.push(this);
  86298. }
  86299. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  86300. return new LensFlare(size, position, color, imgUrl, system);
  86301. };
  86302. LensFlare.prototype.dispose = function () {
  86303. if (this.texture) {
  86304. this.texture.dispose();
  86305. }
  86306. // Remove from scene
  86307. var index = this._system.lensFlares.indexOf(this);
  86308. this._system.lensFlares.splice(index, 1);
  86309. };
  86310. ;
  86311. return LensFlare;
  86312. }());
  86313. BABYLON.LensFlare = LensFlare;
  86314. })(BABYLON || (BABYLON = {}));
  86315. //# sourceMappingURL=babylon.lensFlare.js.map
  86316. var BABYLON;
  86317. (function (BABYLON) {
  86318. // Adds the parser to the scene parsers.
  86319. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  86320. // Lens flares
  86321. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  86322. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  86323. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  86324. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  86325. container.lensFlareSystems.push(lf);
  86326. }
  86327. }
  86328. });
  86329. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  86330. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86331. if (this.lensFlareSystems[index].name === name) {
  86332. return this.lensFlareSystems[index];
  86333. }
  86334. }
  86335. return null;
  86336. };
  86337. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  86338. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86339. if (this.lensFlareSystems[index].id === id) {
  86340. return this.lensFlareSystems[index];
  86341. }
  86342. }
  86343. return null;
  86344. };
  86345. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  86346. var index = this.lensFlareSystems.indexOf(toRemove);
  86347. if (index !== -1) {
  86348. this.lensFlareSystems.splice(index, 1);
  86349. }
  86350. return index;
  86351. };
  86352. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  86353. this.lensFlareSystems.push(newLensFlareSystem);
  86354. };
  86355. /**
  86356. * Defines the lens flare scene component responsible to manage any lens flares
  86357. * in a given scene.
  86358. */
  86359. var LensFlareSystemSceneComponent = /** @class */ (function () {
  86360. /**
  86361. * Creates a new instance of the component for the given scene
  86362. * @param scene Defines the scene to register the component in
  86363. */
  86364. function LensFlareSystemSceneComponent(scene) {
  86365. /**
  86366. * The component name helpfull to identify the component in the list of scene components.
  86367. */
  86368. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  86369. this.scene = scene;
  86370. scene.lensFlareSystems = new Array();
  86371. }
  86372. /**
  86373. * Registers the component in a given scene
  86374. */
  86375. LensFlareSystemSceneComponent.prototype.register = function () {
  86376. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  86377. };
  86378. /**
  86379. * Rebuilds the elements related to this component in case of
  86380. * context lost for instance.
  86381. */
  86382. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  86383. // Nothing to do for lens flare
  86384. };
  86385. /**
  86386. * Adds all the element from the container to the scene
  86387. * @param container the container holding the elements
  86388. */
  86389. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  86390. var _this = this;
  86391. if (!container.lensFlareSystems) {
  86392. return;
  86393. }
  86394. container.lensFlareSystems.forEach(function (o) {
  86395. _this.scene.addLensFlareSystem(o);
  86396. });
  86397. };
  86398. /**
  86399. * Removes all the elements in the container from the scene
  86400. * @param container contains the elements to remove
  86401. */
  86402. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  86403. var _this = this;
  86404. if (!container.lensFlareSystems) {
  86405. return;
  86406. }
  86407. container.lensFlareSystems.forEach(function (o) {
  86408. _this.scene.removeLensFlareSystem(o);
  86409. });
  86410. };
  86411. /**
  86412. * Serializes the component data to the specified json object
  86413. * @param serializationObject The object to serialize to
  86414. */
  86415. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  86416. // Lens flares
  86417. serializationObject.lensFlareSystems = [];
  86418. var lensFlareSystems = this.scene.lensFlareSystems;
  86419. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  86420. var lensFlareSystem = lensFlareSystems_1[_i];
  86421. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  86422. }
  86423. };
  86424. /**
  86425. * Disposes the component and the associated ressources.
  86426. */
  86427. LensFlareSystemSceneComponent.prototype.dispose = function () {
  86428. var lensFlareSystems = this.scene.lensFlareSystems;
  86429. while (lensFlareSystems.length) {
  86430. lensFlareSystems[0].dispose();
  86431. }
  86432. };
  86433. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  86434. // Lens flares
  86435. if (this.scene.lensFlaresEnabled) {
  86436. var lensFlareSystems = this.scene.lensFlareSystems;
  86437. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86438. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  86439. var lensFlareSystem = lensFlareSystems_2[_i];
  86440. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  86441. lensFlareSystem.render();
  86442. }
  86443. }
  86444. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86445. }
  86446. };
  86447. return LensFlareSystemSceneComponent;
  86448. }());
  86449. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  86450. })(BABYLON || (BABYLON = {}));
  86451. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  86452. var BABYLON;
  86453. (function (BABYLON) {
  86454. var LensFlareSystem = /** @class */ (function () {
  86455. function LensFlareSystem(name, emitter, scene) {
  86456. this.name = name;
  86457. this.lensFlares = new Array();
  86458. this.borderLimit = 300;
  86459. this.viewportBorder = 0;
  86460. this.layerMask = 0x0FFFFFFF;
  86461. this._vertexBuffers = {};
  86462. this._isEnabled = true;
  86463. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86464. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  86465. if (!component) {
  86466. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  86467. scene._addComponent(component);
  86468. }
  86469. this._emitter = emitter;
  86470. this.id = name;
  86471. scene.lensFlareSystems.push(this);
  86472. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  86473. var engine = scene.getEngine();
  86474. // VBO
  86475. var vertices = [];
  86476. vertices.push(1, 1);
  86477. vertices.push(-1, 1);
  86478. vertices.push(-1, -1);
  86479. vertices.push(1, -1);
  86480. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86481. // Indices
  86482. var indices = [];
  86483. indices.push(0);
  86484. indices.push(1);
  86485. indices.push(2);
  86486. indices.push(0);
  86487. indices.push(2);
  86488. indices.push(3);
  86489. this._indexBuffer = engine.createIndexBuffer(indices);
  86490. // Effects
  86491. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  86492. }
  86493. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  86494. get: function () {
  86495. return this._isEnabled;
  86496. },
  86497. set: function (value) {
  86498. this._isEnabled = value;
  86499. },
  86500. enumerable: true,
  86501. configurable: true
  86502. });
  86503. LensFlareSystem.prototype.getScene = function () {
  86504. return this._scene;
  86505. };
  86506. LensFlareSystem.prototype.getEmitter = function () {
  86507. return this._emitter;
  86508. };
  86509. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  86510. this._emitter = newEmitter;
  86511. };
  86512. LensFlareSystem.prototype.getEmitterPosition = function () {
  86513. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  86514. };
  86515. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  86516. var position = this.getEmitterPosition();
  86517. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  86518. this._positionX = position.x;
  86519. this._positionY = position.y;
  86520. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  86521. if (this.viewportBorder > 0) {
  86522. globalViewport.x -= this.viewportBorder;
  86523. globalViewport.y -= this.viewportBorder;
  86524. globalViewport.width += this.viewportBorder * 2;
  86525. globalViewport.height += this.viewportBorder * 2;
  86526. position.x += this.viewportBorder;
  86527. position.y += this.viewportBorder;
  86528. this._positionX += this.viewportBorder;
  86529. this._positionY += this.viewportBorder;
  86530. }
  86531. if (position.z > 0) {
  86532. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  86533. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  86534. return true;
  86535. }
  86536. return true;
  86537. }
  86538. return false;
  86539. };
  86540. /** @hidden */
  86541. LensFlareSystem.prototype._isVisible = function () {
  86542. if (!this._isEnabled || !this._scene.activeCamera) {
  86543. return false;
  86544. }
  86545. var emitterPosition = this.getEmitterPosition();
  86546. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  86547. var distance = direction.length();
  86548. direction.normalize();
  86549. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  86550. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  86551. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  86552. };
  86553. LensFlareSystem.prototype.render = function () {
  86554. if (!this._effect.isReady() || !this._scene.activeCamera)
  86555. return false;
  86556. var engine = this._scene.getEngine();
  86557. var viewport = this._scene.activeCamera.viewport;
  86558. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  86559. // Position
  86560. if (!this.computeEffectivePosition(globalViewport)) {
  86561. return false;
  86562. }
  86563. // Visibility
  86564. if (!this._isVisible()) {
  86565. return false;
  86566. }
  86567. // Intensity
  86568. var awayX;
  86569. var awayY;
  86570. if (this._positionX < this.borderLimit + globalViewport.x) {
  86571. awayX = this.borderLimit + globalViewport.x - this._positionX;
  86572. }
  86573. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  86574. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  86575. }
  86576. else {
  86577. awayX = 0;
  86578. }
  86579. if (this._positionY < this.borderLimit + globalViewport.y) {
  86580. awayY = this.borderLimit + globalViewport.y - this._positionY;
  86581. }
  86582. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  86583. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  86584. }
  86585. else {
  86586. awayY = 0;
  86587. }
  86588. var away = (awayX > awayY) ? awayX : awayY;
  86589. away -= this.viewportBorder;
  86590. if (away > this.borderLimit) {
  86591. away = this.borderLimit;
  86592. }
  86593. var intensity = 1.0 - (away / this.borderLimit);
  86594. if (intensity < 0) {
  86595. return false;
  86596. }
  86597. if (intensity > 1.0) {
  86598. intensity = 1.0;
  86599. }
  86600. if (this.viewportBorder > 0) {
  86601. globalViewport.x += this.viewportBorder;
  86602. globalViewport.y += this.viewportBorder;
  86603. globalViewport.width -= this.viewportBorder * 2;
  86604. globalViewport.height -= this.viewportBorder * 2;
  86605. this._positionX -= this.viewportBorder;
  86606. this._positionY -= this.viewportBorder;
  86607. }
  86608. // Position
  86609. var centerX = globalViewport.x + globalViewport.width / 2;
  86610. var centerY = globalViewport.y + globalViewport.height / 2;
  86611. var distX = centerX - this._positionX;
  86612. var distY = centerY - this._positionY;
  86613. // Effects
  86614. engine.enableEffect(this._effect);
  86615. engine.setState(false);
  86616. engine.setDepthBuffer(false);
  86617. // VBOs
  86618. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  86619. // Flares
  86620. for (var index = 0; index < this.lensFlares.length; index++) {
  86621. var flare = this.lensFlares[index];
  86622. engine.setAlphaMode(flare.alphaMode);
  86623. var x = centerX - (distX * flare.position);
  86624. var y = centerY - (distY * flare.position);
  86625. var cw = flare.size;
  86626. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  86627. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  86628. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  86629. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  86630. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  86631. // Texture
  86632. this._effect.setTexture("textureSampler", flare.texture);
  86633. // Color
  86634. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  86635. // Draw order
  86636. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86637. }
  86638. engine.setDepthBuffer(true);
  86639. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86640. return true;
  86641. };
  86642. LensFlareSystem.prototype.dispose = function () {
  86643. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86644. if (vertexBuffer) {
  86645. vertexBuffer.dispose();
  86646. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86647. }
  86648. if (this._indexBuffer) {
  86649. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86650. this._indexBuffer = null;
  86651. }
  86652. while (this.lensFlares.length) {
  86653. this.lensFlares[0].dispose();
  86654. }
  86655. // Remove from scene
  86656. var index = this._scene.lensFlareSystems.indexOf(this);
  86657. this._scene.lensFlareSystems.splice(index, 1);
  86658. };
  86659. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  86660. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  86661. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  86662. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  86663. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  86664. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  86665. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  86666. var parsedFlare = parsedLensFlareSystem.flares[index];
  86667. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  86668. }
  86669. return lensFlareSystem;
  86670. };
  86671. LensFlareSystem.prototype.serialize = function () {
  86672. var serializationObject = {};
  86673. serializationObject.id = this.id;
  86674. serializationObject.name = this.name;
  86675. serializationObject.emitterId = this.getEmitter().id;
  86676. serializationObject.borderLimit = this.borderLimit;
  86677. serializationObject.flares = [];
  86678. for (var index = 0; index < this.lensFlares.length; index++) {
  86679. var flare = this.lensFlares[index];
  86680. serializationObject.flares.push({
  86681. size: flare.size,
  86682. position: flare.position,
  86683. color: flare.color.asArray(),
  86684. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  86685. });
  86686. }
  86687. return serializationObject;
  86688. };
  86689. return LensFlareSystem;
  86690. }());
  86691. BABYLON.LensFlareSystem = LensFlareSystem;
  86692. })(BABYLON || (BABYLON = {}));
  86693. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  86694. var BABYLON;
  86695. (function (BABYLON) {
  86696. /**
  86697. * This is a holder class for the physics joint created by the physics plugin.
  86698. * It holds a set of functions to control the underlying joint.
  86699. */
  86700. var PhysicsJoint = /** @class */ (function () {
  86701. function PhysicsJoint(type, jointData) {
  86702. this.type = type;
  86703. this.jointData = jointData;
  86704. jointData.nativeParams = jointData.nativeParams || {};
  86705. }
  86706. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  86707. get: function () {
  86708. return this._physicsJoint;
  86709. },
  86710. set: function (newJoint) {
  86711. if (this._physicsJoint) {
  86712. //remove from the wolrd
  86713. }
  86714. this._physicsJoint = newJoint;
  86715. },
  86716. enumerable: true,
  86717. configurable: true
  86718. });
  86719. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  86720. set: function (physicsPlugin) {
  86721. this._physicsPlugin = physicsPlugin;
  86722. },
  86723. enumerable: true,
  86724. configurable: true
  86725. });
  86726. /**
  86727. * Execute a function that is physics-plugin specific.
  86728. * @param {Function} func the function that will be executed.
  86729. * It accepts two parameters: the physics world and the physics joint.
  86730. */
  86731. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  86732. func(this._physicsPlugin.world, this._physicsJoint);
  86733. };
  86734. //TODO check if the native joints are the same
  86735. //Joint Types
  86736. PhysicsJoint.DistanceJoint = 0;
  86737. PhysicsJoint.HingeJoint = 1;
  86738. PhysicsJoint.BallAndSocketJoint = 2;
  86739. PhysicsJoint.WheelJoint = 3;
  86740. PhysicsJoint.SliderJoint = 4;
  86741. //OIMO
  86742. PhysicsJoint.PrismaticJoint = 5;
  86743. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  86744. PhysicsJoint.UniversalJoint = 6;
  86745. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  86746. //Cannon
  86747. //Similar to a Ball-Joint. Different in params
  86748. PhysicsJoint.PointToPointJoint = 8;
  86749. //Cannon only at the moment
  86750. PhysicsJoint.SpringJoint = 9;
  86751. PhysicsJoint.LockJoint = 10;
  86752. return PhysicsJoint;
  86753. }());
  86754. BABYLON.PhysicsJoint = PhysicsJoint;
  86755. /**
  86756. * A class representing a physics distance joint.
  86757. */
  86758. var DistanceJoint = /** @class */ (function (_super) {
  86759. __extends(DistanceJoint, _super);
  86760. function DistanceJoint(jointData) {
  86761. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  86762. }
  86763. /**
  86764. * Update the predefined distance.
  86765. */
  86766. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  86767. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  86768. };
  86769. return DistanceJoint;
  86770. }(PhysicsJoint));
  86771. BABYLON.DistanceJoint = DistanceJoint;
  86772. var MotorEnabledJoint = /** @class */ (function (_super) {
  86773. __extends(MotorEnabledJoint, _super);
  86774. function MotorEnabledJoint(type, jointData) {
  86775. return _super.call(this, type, jointData) || this;
  86776. }
  86777. /**
  86778. * Set the motor values.
  86779. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86780. * @param {number} force the force to apply
  86781. * @param {number} maxForce max force for this motor.
  86782. */
  86783. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  86784. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86785. };
  86786. /**
  86787. * Set the motor's limits.
  86788. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86789. */
  86790. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86791. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86792. };
  86793. return MotorEnabledJoint;
  86794. }(PhysicsJoint));
  86795. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  86796. /**
  86797. * This class represents a single hinge physics joint
  86798. */
  86799. var HingeJoint = /** @class */ (function (_super) {
  86800. __extends(HingeJoint, _super);
  86801. function HingeJoint(jointData) {
  86802. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  86803. }
  86804. /**
  86805. * Set the motor values.
  86806. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86807. * @param {number} force the force to apply
  86808. * @param {number} maxForce max force for this motor.
  86809. */
  86810. HingeJoint.prototype.setMotor = function (force, maxForce) {
  86811. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86812. };
  86813. /**
  86814. * Set the motor's limits.
  86815. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86816. */
  86817. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86818. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86819. };
  86820. return HingeJoint;
  86821. }(MotorEnabledJoint));
  86822. BABYLON.HingeJoint = HingeJoint;
  86823. /**
  86824. * This class represents a dual hinge physics joint (same as wheel joint)
  86825. */
  86826. var Hinge2Joint = /** @class */ (function (_super) {
  86827. __extends(Hinge2Joint, _super);
  86828. function Hinge2Joint(jointData) {
  86829. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  86830. }
  86831. /**
  86832. * Set the motor values.
  86833. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86834. * @param {number} force the force to apply
  86835. * @param {number} maxForce max force for this motor.
  86836. * @param {motorIndex} the motor's index, 0 or 1.
  86837. */
  86838. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  86839. if (motorIndex === void 0) { motorIndex = 0; }
  86840. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  86841. };
  86842. /**
  86843. * Set the motor limits.
  86844. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86845. * @param {number} upperLimit the upper limit
  86846. * @param {number} lowerLimit lower limit
  86847. * @param {motorIndex} the motor's index, 0 or 1.
  86848. */
  86849. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  86850. if (motorIndex === void 0) { motorIndex = 0; }
  86851. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  86852. };
  86853. return Hinge2Joint;
  86854. }(MotorEnabledJoint));
  86855. BABYLON.Hinge2Joint = Hinge2Joint;
  86856. })(BABYLON || (BABYLON = {}));
  86857. //# sourceMappingURL=babylon.physicsJoint.js.map
  86858. var BABYLON;
  86859. (function (BABYLON) {
  86860. var PhysicsImpostor = /** @class */ (function () {
  86861. function PhysicsImpostor(object, type, _options, _scene) {
  86862. if (_options === void 0) { _options = { mass: 0 }; }
  86863. var _this = this;
  86864. this.object = object;
  86865. this.type = type;
  86866. this._options = _options;
  86867. this._scene = _scene;
  86868. this._bodyUpdateRequired = false;
  86869. this._onBeforePhysicsStepCallbacks = new Array();
  86870. this._onAfterPhysicsStepCallbacks = new Array();
  86871. this._onPhysicsCollideCallbacks = [];
  86872. this._deltaPosition = BABYLON.Vector3.Zero();
  86873. this._isDisposed = false;
  86874. //temp variables for parent rotation calculations
  86875. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  86876. this._tmpQuat = new BABYLON.Quaternion();
  86877. this._tmpQuat2 = new BABYLON.Quaternion();
  86878. /**
  86879. * this function is executed by the physics engine.
  86880. */
  86881. this.beforeStep = function () {
  86882. if (!_this._physicsEngine) {
  86883. return;
  86884. }
  86885. _this.object.translate(_this._deltaPosition, -1);
  86886. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  86887. _this.object.computeWorldMatrix(false);
  86888. if (_this.object.parent && _this.object.rotationQuaternion) {
  86889. _this.getParentsRotation();
  86890. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  86891. }
  86892. else {
  86893. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  86894. }
  86895. if (!_this._options.disableBidirectionalTransformation) {
  86896. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  86897. }
  86898. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  86899. func(_this);
  86900. });
  86901. };
  86902. /**
  86903. * this function is executed by the physics engine.
  86904. */
  86905. this.afterStep = function () {
  86906. if (!_this._physicsEngine) {
  86907. return;
  86908. }
  86909. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  86910. func(_this);
  86911. });
  86912. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  86913. // object has now its world rotation. needs to be converted to local.
  86914. if (_this.object.parent && _this.object.rotationQuaternion) {
  86915. _this.getParentsRotation();
  86916. _this._tmpQuat.conjugateInPlace();
  86917. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  86918. }
  86919. // take the position set and make it the absolute position of this object.
  86920. _this.object.setAbsolutePosition(_this.object.position);
  86921. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  86922. _this.object.translate(_this._deltaPosition, 1);
  86923. };
  86924. /**
  86925. * Legacy collision detection event support
  86926. */
  86927. this.onCollideEvent = null;
  86928. //event and body object due to cannon's event-based architecture.
  86929. this.onCollide = function (e) {
  86930. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  86931. return;
  86932. }
  86933. if (!_this._physicsEngine) {
  86934. return;
  86935. }
  86936. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  86937. if (otherImpostor) {
  86938. // Legacy collision detection event support
  86939. if (_this.onCollideEvent) {
  86940. _this.onCollideEvent(_this, otherImpostor);
  86941. }
  86942. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  86943. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  86944. }).forEach(function (obj) {
  86945. obj.callback(_this, otherImpostor);
  86946. });
  86947. }
  86948. };
  86949. //sanity check!
  86950. if (!this.object) {
  86951. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  86952. return;
  86953. }
  86954. //legacy support for old syntax.
  86955. if (!this._scene && object.getScene) {
  86956. this._scene = object.getScene();
  86957. }
  86958. if (!this._scene) {
  86959. return;
  86960. }
  86961. this._physicsEngine = this._scene.getPhysicsEngine();
  86962. if (!this._physicsEngine) {
  86963. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  86964. }
  86965. else {
  86966. //set the object's quaternion, if not set
  86967. if (!this.object.rotationQuaternion) {
  86968. if (this.object.rotation) {
  86969. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  86970. }
  86971. else {
  86972. this.object.rotationQuaternion = new BABYLON.Quaternion();
  86973. }
  86974. }
  86975. //default options params
  86976. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  86977. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  86978. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  86979. this._joints = [];
  86980. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  86981. if (!this.object.parent || this._options.ignoreParent) {
  86982. this._init();
  86983. }
  86984. else if (this.object.parent.physicsImpostor) {
  86985. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  86986. }
  86987. }
  86988. }
  86989. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  86990. get: function () {
  86991. return this._isDisposed;
  86992. },
  86993. enumerable: true,
  86994. configurable: true
  86995. });
  86996. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  86997. get: function () {
  86998. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  86999. },
  87000. set: function (value) {
  87001. this.setMass(value);
  87002. },
  87003. enumerable: true,
  87004. configurable: true
  87005. });
  87006. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  87007. get: function () {
  87008. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  87009. },
  87010. set: function (value) {
  87011. if (!this._physicsEngine) {
  87012. return;
  87013. }
  87014. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  87015. },
  87016. enumerable: true,
  87017. configurable: true
  87018. });
  87019. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  87020. get: function () {
  87021. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  87022. },
  87023. set: function (value) {
  87024. if (!this._physicsEngine) {
  87025. return;
  87026. }
  87027. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  87028. },
  87029. enumerable: true,
  87030. configurable: true
  87031. });
  87032. /**
  87033. * This function will completly initialize this impostor.
  87034. * It will create a new body - but only if this mesh has no parent.
  87035. * If it has, this impostor will not be used other than to define the impostor
  87036. * of the child mesh.
  87037. * @hidden
  87038. */
  87039. PhysicsImpostor.prototype._init = function () {
  87040. if (!this._physicsEngine) {
  87041. return;
  87042. }
  87043. this._physicsEngine.removeImpostor(this);
  87044. this.physicsBody = null;
  87045. this._parent = this._parent || this._getPhysicsParent();
  87046. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  87047. this._physicsEngine.addImpostor(this);
  87048. }
  87049. };
  87050. PhysicsImpostor.prototype._getPhysicsParent = function () {
  87051. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  87052. var parentMesh = this.object.parent;
  87053. return parentMesh.physicsImpostor;
  87054. }
  87055. return null;
  87056. };
  87057. /**
  87058. * Should a new body be generated.
  87059. */
  87060. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  87061. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  87062. };
  87063. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  87064. this.forceUpdate();
  87065. };
  87066. /**
  87067. * Force a regeneration of this or the parent's impostor's body.
  87068. * Use under cautious - This will remove all joints already implemented.
  87069. */
  87070. PhysicsImpostor.prototype.forceUpdate = function () {
  87071. this._init();
  87072. if (this.parent && !this._options.ignoreParent) {
  87073. this.parent.forceUpdate();
  87074. }
  87075. };
  87076. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  87077. /*public get mesh(): AbstractMesh {
  87078. return this._mesh;
  87079. }*/
  87080. /**
  87081. * Gets the body that holds this impostor. Either its own, or its parent.
  87082. */
  87083. get: function () {
  87084. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  87085. },
  87086. /**
  87087. * Set the physics body. Used mainly by the physics engine/plugin
  87088. */
  87089. set: function (physicsBody) {
  87090. if (this._physicsBody && this._physicsEngine) {
  87091. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  87092. }
  87093. this._physicsBody = physicsBody;
  87094. this.resetUpdateFlags();
  87095. },
  87096. enumerable: true,
  87097. configurable: true
  87098. });
  87099. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  87100. get: function () {
  87101. return !this._options.ignoreParent && this._parent ? this._parent : null;
  87102. },
  87103. set: function (value) {
  87104. this._parent = value;
  87105. },
  87106. enumerable: true,
  87107. configurable: true
  87108. });
  87109. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  87110. this._bodyUpdateRequired = false;
  87111. };
  87112. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  87113. if (this.object.getBoundingInfo) {
  87114. var q = this.object.rotationQuaternion;
  87115. //reset rotation
  87116. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  87117. //calculate the world matrix with no rotation
  87118. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87119. var boundingInfo = this.object.getBoundingInfo();
  87120. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  87121. //bring back the rotation
  87122. this.object.rotationQuaternion = q;
  87123. //calculate the world matrix with the new rotation
  87124. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87125. return size;
  87126. }
  87127. else {
  87128. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  87129. }
  87130. };
  87131. PhysicsImpostor.prototype.getObjectCenter = function () {
  87132. if (this.object.getBoundingInfo) {
  87133. var boundingInfo = this.object.getBoundingInfo();
  87134. return boundingInfo.boundingBox.centerWorld;
  87135. }
  87136. else {
  87137. return this.object.position;
  87138. }
  87139. };
  87140. /**
  87141. * Get a specific parametes from the options parameter.
  87142. */
  87143. PhysicsImpostor.prototype.getParam = function (paramName) {
  87144. return this._options[paramName];
  87145. };
  87146. /**
  87147. * Sets a specific parameter in the options given to the physics plugin
  87148. */
  87149. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  87150. this._options[paramName] = value;
  87151. this._bodyUpdateRequired = true;
  87152. };
  87153. /**
  87154. * Specifically change the body's mass option. Won't recreate the physics body object
  87155. */
  87156. PhysicsImpostor.prototype.setMass = function (mass) {
  87157. if (this.getParam("mass") !== mass) {
  87158. this.setParam("mass", mass);
  87159. }
  87160. if (this._physicsEngine) {
  87161. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  87162. }
  87163. };
  87164. PhysicsImpostor.prototype.getLinearVelocity = function () {
  87165. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  87166. };
  87167. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  87168. if (this._physicsEngine) {
  87169. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  87170. }
  87171. };
  87172. PhysicsImpostor.prototype.getAngularVelocity = function () {
  87173. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  87174. };
  87175. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  87176. if (this._physicsEngine) {
  87177. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  87178. }
  87179. };
  87180. /**
  87181. * Execute a function with the physics plugin native code.
  87182. * Provide a function the will have two variables - the world object and the physics body object.
  87183. */
  87184. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  87185. if (this._physicsEngine) {
  87186. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  87187. }
  87188. };
  87189. /**
  87190. * Register a function that will be executed before the physics world is stepping forward.
  87191. */
  87192. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  87193. this._onBeforePhysicsStepCallbacks.push(func);
  87194. };
  87195. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  87196. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  87197. if (index > -1) {
  87198. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  87199. }
  87200. else {
  87201. BABYLON.Tools.Warn("Function to remove was not found");
  87202. }
  87203. };
  87204. /**
  87205. * Register a function that will be executed after the physics step
  87206. */
  87207. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  87208. this._onAfterPhysicsStepCallbacks.push(func);
  87209. };
  87210. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  87211. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  87212. if (index > -1) {
  87213. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  87214. }
  87215. else {
  87216. BABYLON.Tools.Warn("Function to remove was not found");
  87217. }
  87218. };
  87219. /**
  87220. * register a function that will be executed when this impostor collides against a different body.
  87221. */
  87222. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  87223. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87224. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  87225. };
  87226. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  87227. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87228. var index = -1;
  87229. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  87230. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  87231. // chcek the arrays match
  87232. var sameList = cbDef.otherImpostors.every(function (impostor) {
  87233. return collidedAgainstList.indexOf(impostor) > -1;
  87234. });
  87235. if (sameList) {
  87236. index = idx;
  87237. }
  87238. return sameList;
  87239. }
  87240. return false;
  87241. });
  87242. if (found) {
  87243. this._onPhysicsCollideCallbacks.splice(index, 1);
  87244. }
  87245. else {
  87246. BABYLON.Tools.Warn("Function to remove was not found");
  87247. }
  87248. };
  87249. PhysicsImpostor.prototype.getParentsRotation = function () {
  87250. var parent = this.object.parent;
  87251. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  87252. while (parent) {
  87253. if (parent.rotationQuaternion) {
  87254. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  87255. }
  87256. else {
  87257. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  87258. }
  87259. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  87260. parent = parent.parent;
  87261. }
  87262. return this._tmpQuat;
  87263. };
  87264. /**
  87265. * Apply a force
  87266. */
  87267. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  87268. if (this._physicsEngine) {
  87269. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  87270. }
  87271. return this;
  87272. };
  87273. /**
  87274. * Apply an impulse
  87275. */
  87276. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  87277. if (this._physicsEngine) {
  87278. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  87279. }
  87280. return this;
  87281. };
  87282. /**
  87283. * A help function to create a joint.
  87284. */
  87285. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  87286. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  87287. this.addJoint(otherImpostor, joint);
  87288. return this;
  87289. };
  87290. /**
  87291. * Add a joint to this impostor with a different impostor.
  87292. */
  87293. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  87294. this._joints.push({
  87295. otherImpostor: otherImpostor,
  87296. joint: joint
  87297. });
  87298. if (this._physicsEngine) {
  87299. this._physicsEngine.addJoint(this, otherImpostor, joint);
  87300. }
  87301. return this;
  87302. };
  87303. /**
  87304. * Will keep this body still, in a sleep mode.
  87305. */
  87306. PhysicsImpostor.prototype.sleep = function () {
  87307. if (this._physicsEngine) {
  87308. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  87309. }
  87310. return this;
  87311. };
  87312. /**
  87313. * Wake the body up.
  87314. */
  87315. PhysicsImpostor.prototype.wakeUp = function () {
  87316. if (this._physicsEngine) {
  87317. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  87318. }
  87319. return this;
  87320. };
  87321. PhysicsImpostor.prototype.clone = function (newObject) {
  87322. if (!newObject)
  87323. return null;
  87324. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  87325. };
  87326. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  87327. var _this = this;
  87328. //no dispose if no physics engine is available.
  87329. if (!this._physicsEngine) {
  87330. return;
  87331. }
  87332. this._joints.forEach(function (j) {
  87333. if (_this._physicsEngine) {
  87334. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  87335. }
  87336. });
  87337. //dispose the physics body
  87338. this._physicsEngine.removeImpostor(this);
  87339. if (this.parent) {
  87340. this.parent.forceUpdate();
  87341. }
  87342. else {
  87343. /*this._object.getChildMeshes().forEach(function(mesh) {
  87344. if (mesh.physicsImpostor) {
  87345. if (disposeChildren) {
  87346. mesh.physicsImpostor.dispose();
  87347. mesh.physicsImpostor = null;
  87348. }
  87349. }
  87350. })*/
  87351. }
  87352. this._isDisposed = true;
  87353. };
  87354. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  87355. this._deltaPosition.copyFrom(position);
  87356. };
  87357. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  87358. if (!this._deltaRotation) {
  87359. this._deltaRotation = new BABYLON.Quaternion();
  87360. }
  87361. this._deltaRotation.copyFrom(rotation);
  87362. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  87363. };
  87364. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  87365. if (this._physicsEngine) {
  87366. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  87367. }
  87368. return this;
  87369. };
  87370. PhysicsImpostor.prototype.getRadius = function () {
  87371. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  87372. };
  87373. /**
  87374. * Sync a bone with this impostor
  87375. * @param bone The bone to sync to the impostor.
  87376. * @param boneMesh The mesh that the bone is influencing.
  87377. * @param jointPivot The pivot of the joint / bone in local space.
  87378. * @param distToJoint Optional distance from the impostor to the joint.
  87379. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87380. */
  87381. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  87382. var tempVec = PhysicsImpostor._tmpVecs[0];
  87383. var mesh = this.object;
  87384. if (mesh.rotationQuaternion) {
  87385. if (adjustRotation) {
  87386. var tempQuat = PhysicsImpostor._tmpQuat;
  87387. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  87388. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  87389. }
  87390. else {
  87391. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  87392. }
  87393. }
  87394. tempVec.x = 0;
  87395. tempVec.y = 0;
  87396. tempVec.z = 0;
  87397. if (jointPivot) {
  87398. tempVec.x = jointPivot.x;
  87399. tempVec.y = jointPivot.y;
  87400. tempVec.z = jointPivot.z;
  87401. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  87402. if (distToJoint === undefined || distToJoint === null) {
  87403. distToJoint = jointPivot.length();
  87404. }
  87405. tempVec.x *= distToJoint;
  87406. tempVec.y *= distToJoint;
  87407. tempVec.z *= distToJoint;
  87408. }
  87409. if (bone.getParent()) {
  87410. tempVec.addInPlace(mesh.getAbsolutePosition());
  87411. bone.setAbsolutePosition(tempVec, boneMesh);
  87412. }
  87413. else {
  87414. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  87415. boneMesh.position.x -= tempVec.x;
  87416. boneMesh.position.y -= tempVec.y;
  87417. boneMesh.position.z -= tempVec.z;
  87418. }
  87419. };
  87420. /**
  87421. * Sync impostor to a bone
  87422. * @param bone The bone that the impostor will be synced to.
  87423. * @param boneMesh The mesh that the bone is influencing.
  87424. * @param jointPivot The pivot of the joint / bone in local space.
  87425. * @param distToJoint Optional distance from the impostor to the joint.
  87426. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87427. * @param boneAxis Optional vector3 axis the bone is aligned with
  87428. */
  87429. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  87430. var mesh = this.object;
  87431. if (mesh.rotationQuaternion) {
  87432. if (adjustRotation) {
  87433. var tempQuat = PhysicsImpostor._tmpQuat;
  87434. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  87435. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  87436. }
  87437. else {
  87438. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  87439. }
  87440. }
  87441. var pos = PhysicsImpostor._tmpVecs[0];
  87442. var boneDir = PhysicsImpostor._tmpVecs[1];
  87443. if (!boneAxis) {
  87444. boneAxis = PhysicsImpostor._tmpVecs[2];
  87445. boneAxis.x = 0;
  87446. boneAxis.y = 1;
  87447. boneAxis.z = 0;
  87448. }
  87449. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  87450. bone.getAbsolutePositionToRef(boneMesh, pos);
  87451. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  87452. distToJoint = jointPivot.length();
  87453. }
  87454. if (distToJoint !== undefined && distToJoint !== null) {
  87455. pos.x += boneDir.x * distToJoint;
  87456. pos.y += boneDir.y * distToJoint;
  87457. pos.z += boneDir.z * distToJoint;
  87458. }
  87459. mesh.setAbsolutePosition(pos);
  87460. };
  87461. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  87462. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  87463. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87464. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  87465. //Impostor types
  87466. PhysicsImpostor.NoImpostor = 0;
  87467. PhysicsImpostor.SphereImpostor = 1;
  87468. PhysicsImpostor.BoxImpostor = 2;
  87469. PhysicsImpostor.PlaneImpostor = 3;
  87470. PhysicsImpostor.MeshImpostor = 4;
  87471. PhysicsImpostor.CylinderImpostor = 7;
  87472. PhysicsImpostor.ParticleImpostor = 8;
  87473. PhysicsImpostor.HeightmapImpostor = 9;
  87474. return PhysicsImpostor;
  87475. }());
  87476. BABYLON.PhysicsImpostor = PhysicsImpostor;
  87477. })(BABYLON || (BABYLON = {}));
  87478. //# sourceMappingURL=babylon.physicsImpostor.js.map
  87479. var BABYLON;
  87480. (function (BABYLON) {
  87481. var PhysicsEngine = /** @class */ (function () {
  87482. function PhysicsEngine(gravity, _physicsPlugin) {
  87483. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  87484. this._physicsPlugin = _physicsPlugin;
  87485. //new methods and parameters
  87486. this._impostors = [];
  87487. this._joints = [];
  87488. if (!this._physicsPlugin.isSupported()) {
  87489. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  87490. + "Please make sure it is included.");
  87491. }
  87492. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  87493. this.setGravity(gravity);
  87494. this.setTimeStep();
  87495. }
  87496. PhysicsEngine.prototype.setGravity = function (gravity) {
  87497. this.gravity = gravity;
  87498. this._physicsPlugin.setGravity(this.gravity);
  87499. };
  87500. /**
  87501. * Set the time step of the physics engine.
  87502. * default is 1/60.
  87503. * To slow it down, enter 1/600 for example.
  87504. * To speed it up, 1/30
  87505. * @param {number} newTimeStep the new timestep to apply to this world.
  87506. */
  87507. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  87508. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  87509. this._physicsPlugin.setTimeStep(newTimeStep);
  87510. };
  87511. /**
  87512. * Get the time step of the physics engine.
  87513. */
  87514. PhysicsEngine.prototype.getTimeStep = function () {
  87515. return this._physicsPlugin.getTimeStep();
  87516. };
  87517. PhysicsEngine.prototype.dispose = function () {
  87518. this._impostors.forEach(function (impostor) {
  87519. impostor.dispose();
  87520. });
  87521. this._physicsPlugin.dispose();
  87522. };
  87523. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  87524. return this._physicsPlugin.name;
  87525. };
  87526. /**
  87527. * Adding a new impostor for the impostor tracking.
  87528. * This will be done by the impostor itself.
  87529. * @param {PhysicsImpostor} impostor the impostor to add
  87530. */
  87531. PhysicsEngine.prototype.addImpostor = function (impostor) {
  87532. impostor.uniqueId = this._impostors.push(impostor);
  87533. //if no parent, generate the body
  87534. if (!impostor.parent) {
  87535. this._physicsPlugin.generatePhysicsBody(impostor);
  87536. }
  87537. };
  87538. /**
  87539. * Remove an impostor from the engine.
  87540. * This impostor and its mesh will not longer be updated by the physics engine.
  87541. * @param {PhysicsImpostor} impostor the impostor to remove
  87542. */
  87543. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  87544. var index = this._impostors.indexOf(impostor);
  87545. if (index > -1) {
  87546. var removed = this._impostors.splice(index, 1);
  87547. //Is it needed?
  87548. if (removed.length) {
  87549. //this will also remove it from the world.
  87550. removed[0].physicsBody = null;
  87551. }
  87552. }
  87553. };
  87554. /**
  87555. * Add a joint to the physics engine
  87556. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  87557. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  87558. * @param {PhysicsJoint} the joint that will connect both impostors.
  87559. */
  87560. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  87561. var impostorJoint = {
  87562. mainImpostor: mainImpostor,
  87563. connectedImpostor: connectedImpostor,
  87564. joint: joint
  87565. };
  87566. joint.physicsPlugin = this._physicsPlugin;
  87567. this._joints.push(impostorJoint);
  87568. this._physicsPlugin.generateJoint(impostorJoint);
  87569. };
  87570. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  87571. var matchingJoints = this._joints.filter(function (impostorJoint) {
  87572. return (impostorJoint.connectedImpostor === connectedImpostor
  87573. && impostorJoint.joint === joint
  87574. && impostorJoint.mainImpostor === mainImpostor);
  87575. });
  87576. if (matchingJoints.length) {
  87577. this._physicsPlugin.removeJoint(matchingJoints[0]);
  87578. //TODO remove it from the list as well
  87579. }
  87580. };
  87581. /**
  87582. * Called by the scene. no need to call it.
  87583. * @hidden
  87584. */
  87585. PhysicsEngine.prototype._step = function (delta) {
  87586. var _this = this;
  87587. //check if any mesh has no body / requires an update
  87588. this._impostors.forEach(function (impostor) {
  87589. if (impostor.isBodyInitRequired()) {
  87590. _this._physicsPlugin.generatePhysicsBody(impostor);
  87591. }
  87592. });
  87593. if (delta > 0.1) {
  87594. delta = 0.1;
  87595. }
  87596. else if (delta <= 0) {
  87597. delta = 1.0 / 60.0;
  87598. }
  87599. this._physicsPlugin.executeStep(delta, this._impostors);
  87600. };
  87601. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  87602. return this._physicsPlugin;
  87603. };
  87604. PhysicsEngine.prototype.getImpostors = function () {
  87605. return this._impostors;
  87606. };
  87607. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  87608. for (var i = 0; i < this._impostors.length; ++i) {
  87609. if (this._impostors[i].object === object) {
  87610. return this._impostors[i];
  87611. }
  87612. }
  87613. return null;
  87614. };
  87615. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  87616. for (var i = 0; i < this._impostors.length; ++i) {
  87617. if (this._impostors[i].physicsBody === body) {
  87618. return this._impostors[i];
  87619. }
  87620. }
  87621. return null;
  87622. };
  87623. // Statics
  87624. PhysicsEngine.Epsilon = 0.001;
  87625. return PhysicsEngine;
  87626. }());
  87627. BABYLON.PhysicsEngine = PhysicsEngine;
  87628. })(BABYLON || (BABYLON = {}));
  87629. //# sourceMappingURL=babylon.physicsEngine.js.map
  87630. var BABYLON;
  87631. (function (BABYLON) {
  87632. var PhysicsHelper = /** @class */ (function () {
  87633. function PhysicsHelper(scene) {
  87634. this._scene = scene;
  87635. this._physicsEngine = this._scene.getPhysicsEngine();
  87636. if (!this._physicsEngine) {
  87637. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  87638. }
  87639. }
  87640. /**
  87641. * @param {Vector3} origin the origin of the explosion
  87642. * @param {number} radius the explosion radius
  87643. * @param {number} strength the explosion strength
  87644. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87645. */
  87646. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  87647. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87648. if (!this._physicsEngine) {
  87649. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  87650. return null;
  87651. }
  87652. var impostors = this._physicsEngine.getImpostors();
  87653. if (impostors.length === 0) {
  87654. return null;
  87655. }
  87656. var event = new PhysicsRadialExplosionEvent(this._scene);
  87657. impostors.forEach(function (impostor) {
  87658. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87659. if (!impostorForceAndContactPoint) {
  87660. return;
  87661. }
  87662. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87663. });
  87664. event.dispose(false);
  87665. return event;
  87666. };
  87667. /**
  87668. * @param {Vector3} origin the origin of the explosion
  87669. * @param {number} radius the explosion radius
  87670. * @param {number} strength the explosion strength
  87671. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87672. */
  87673. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  87674. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87675. if (!this._physicsEngine) {
  87676. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87677. return null;
  87678. }
  87679. var impostors = this._physicsEngine.getImpostors();
  87680. if (impostors.length === 0) {
  87681. return null;
  87682. }
  87683. var event = new PhysicsRadialExplosionEvent(this._scene);
  87684. impostors.forEach(function (impostor) {
  87685. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87686. if (!impostorForceAndContactPoint) {
  87687. return;
  87688. }
  87689. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87690. });
  87691. event.dispose(false);
  87692. return event;
  87693. };
  87694. /**
  87695. * @param {Vector3} origin the origin of the explosion
  87696. * @param {number} radius the explosion radius
  87697. * @param {number} strength the explosion strength
  87698. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87699. */
  87700. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  87701. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87702. if (!this._physicsEngine) {
  87703. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87704. return null;
  87705. }
  87706. var impostors = this._physicsEngine.getImpostors();
  87707. if (impostors.length === 0) {
  87708. return null;
  87709. }
  87710. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  87711. event.dispose(false);
  87712. return event;
  87713. };
  87714. /**
  87715. * @param {Vector3} origin the origin of the updraft
  87716. * @param {number} radius the radius of the updraft
  87717. * @param {number} strength the strength of the updraft
  87718. * @param {number} height the height of the updraft
  87719. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  87720. */
  87721. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  87722. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  87723. if (!this._physicsEngine) {
  87724. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87725. return null;
  87726. }
  87727. if (this._physicsEngine.getImpostors().length === 0) {
  87728. return null;
  87729. }
  87730. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  87731. event.dispose(false);
  87732. return event;
  87733. };
  87734. /**
  87735. * @param {Vector3} origin the of the vortex
  87736. * @param {number} radius the radius of the vortex
  87737. * @param {number} strength the strength of the vortex
  87738. * @param {number} height the height of the vortex
  87739. */
  87740. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  87741. if (!this._physicsEngine) {
  87742. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87743. return null;
  87744. }
  87745. if (this._physicsEngine.getImpostors().length === 0) {
  87746. return null;
  87747. }
  87748. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  87749. event.dispose(false);
  87750. return event;
  87751. };
  87752. return PhysicsHelper;
  87753. }());
  87754. BABYLON.PhysicsHelper = PhysicsHelper;
  87755. /***** Radial explosion *****/
  87756. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  87757. function PhysicsRadialExplosionEvent(scene) {
  87758. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  87759. this._rays = [];
  87760. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  87761. this._scene = scene;
  87762. }
  87763. /**
  87764. * Returns the data related to the radial explosion event (sphere & rays).
  87765. * @returns {PhysicsRadialExplosionEventData}
  87766. */
  87767. PhysicsRadialExplosionEvent.prototype.getData = function () {
  87768. this._dataFetched = true;
  87769. return {
  87770. sphere: this._sphere,
  87771. rays: this._rays,
  87772. };
  87773. };
  87774. /**
  87775. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  87776. * @param impostor
  87777. * @param {Vector3} origin the origin of the explosion
  87778. * @param {number} radius the explosion radius
  87779. * @param {number} strength the explosion strength
  87780. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  87781. * @returns {Nullable<PhysicsForceAndContactPoint>}
  87782. */
  87783. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  87784. if (impostor.mass === 0) {
  87785. return null;
  87786. }
  87787. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  87788. return null;
  87789. }
  87790. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87791. return null;
  87792. }
  87793. var impostorObjectCenter = impostor.getObjectCenter();
  87794. var direction = impostorObjectCenter.subtract(origin);
  87795. var ray = new BABYLON.Ray(origin, direction, radius);
  87796. this._rays.push(ray);
  87797. var hit = ray.intersectsMesh(impostor.object);
  87798. var contactPoint = hit.pickedPoint;
  87799. if (!contactPoint) {
  87800. return null;
  87801. }
  87802. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  87803. if (distanceFromOrigin > radius) {
  87804. return null;
  87805. }
  87806. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  87807. ? strength
  87808. : strength * (1 - (distanceFromOrigin / radius));
  87809. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87810. return { force: force, contactPoint: contactPoint };
  87811. };
  87812. /**
  87813. * Disposes the sphere.
  87814. * @param {bolean} force
  87815. */
  87816. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  87817. var _this = this;
  87818. if (force === void 0) { force = true; }
  87819. if (force) {
  87820. this._sphere.dispose();
  87821. }
  87822. else {
  87823. setTimeout(function () {
  87824. if (!_this._dataFetched) {
  87825. _this._sphere.dispose();
  87826. }
  87827. }, 0);
  87828. }
  87829. };
  87830. /*** Helpers ***/
  87831. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  87832. if (!this._sphere) {
  87833. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  87834. this._sphere.isVisible = false;
  87835. }
  87836. };
  87837. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  87838. var impostorObject = impostor.object;
  87839. this._prepareSphere();
  87840. this._sphere.position = origin;
  87841. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  87842. this._sphere._updateBoundingInfo();
  87843. this._sphere.computeWorldMatrix(true);
  87844. return this._sphere.intersectsMesh(impostorObject, true);
  87845. };
  87846. return PhysicsRadialExplosionEvent;
  87847. }());
  87848. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  87849. /***** Gravitational Field *****/
  87850. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  87851. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  87852. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87853. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87854. this._physicsHelper = physicsHelper;
  87855. this._scene = scene;
  87856. this._origin = origin;
  87857. this._radius = radius;
  87858. this._strength = strength;
  87859. this._falloff = falloff;
  87860. this._tickCallback = this._tick.bind(this);
  87861. }
  87862. /**
  87863. * Returns the data related to the gravitational field event (sphere).
  87864. * @returns {PhysicsGravitationalFieldEventData}
  87865. */
  87866. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  87867. this._dataFetched = true;
  87868. return {
  87869. sphere: this._sphere,
  87870. };
  87871. };
  87872. /**
  87873. * Enables the gravitational field.
  87874. */
  87875. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  87876. this._tickCallback.call(this);
  87877. this._scene.registerBeforeRender(this._tickCallback);
  87878. };
  87879. /**
  87880. * Disables the gravitational field.
  87881. */
  87882. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  87883. this._scene.unregisterBeforeRender(this._tickCallback);
  87884. };
  87885. /**
  87886. * Disposes the sphere.
  87887. * @param {bolean} force
  87888. */
  87889. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  87890. var _this = this;
  87891. if (force === void 0) { force = true; }
  87892. if (force) {
  87893. this._sphere.dispose();
  87894. }
  87895. else {
  87896. setTimeout(function () {
  87897. if (!_this._dataFetched) {
  87898. _this._sphere.dispose();
  87899. }
  87900. }, 0);
  87901. }
  87902. };
  87903. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  87904. // Since the params won't change, we fetch the event only once
  87905. if (this._sphere) {
  87906. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87907. }
  87908. else {
  87909. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87910. if (radialExplosionEvent) {
  87911. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  87912. }
  87913. }
  87914. };
  87915. return PhysicsGravitationalFieldEvent;
  87916. }());
  87917. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  87918. /***** Updraft *****/
  87919. var PhysicsUpdraftEvent = /** @class */ (function () {
  87920. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  87921. this._scene = _scene;
  87922. this._origin = _origin;
  87923. this._radius = _radius;
  87924. this._strength = _strength;
  87925. this._height = _height;
  87926. this._updraftMode = _updraftMode;
  87927. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87928. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  87929. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87930. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87931. this._physicsEngine = this._scene.getPhysicsEngine();
  87932. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87933. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87934. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87935. this._originDirection = this._origin.subtract(this._originTop).normalize();
  87936. }
  87937. this._tickCallback = this._tick.bind(this);
  87938. }
  87939. /**
  87940. * Returns the data related to the updraft event (cylinder).
  87941. * @returns {PhysicsUpdraftEventData}
  87942. */
  87943. PhysicsUpdraftEvent.prototype.getData = function () {
  87944. this._dataFetched = true;
  87945. return {
  87946. cylinder: this._cylinder,
  87947. };
  87948. };
  87949. /**
  87950. * Enables the updraft.
  87951. */
  87952. PhysicsUpdraftEvent.prototype.enable = function () {
  87953. this._tickCallback.call(this);
  87954. this._scene.registerBeforeRender(this._tickCallback);
  87955. };
  87956. /**
  87957. * Disables the cortex.
  87958. */
  87959. PhysicsUpdraftEvent.prototype.disable = function () {
  87960. this._scene.unregisterBeforeRender(this._tickCallback);
  87961. };
  87962. /**
  87963. * Disposes the sphere.
  87964. * @param {bolean} force
  87965. */
  87966. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  87967. var _this = this;
  87968. if (force === void 0) { force = true; }
  87969. if (force) {
  87970. this._cylinder.dispose();
  87971. }
  87972. else {
  87973. setTimeout(function () {
  87974. if (!_this._dataFetched) {
  87975. _this._cylinder.dispose();
  87976. }
  87977. }, 0);
  87978. }
  87979. };
  87980. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87981. if (impostor.mass === 0) {
  87982. return null;
  87983. }
  87984. if (!this._intersectsWithCylinder(impostor)) {
  87985. return null;
  87986. }
  87987. var impostorObjectCenter = impostor.getObjectCenter();
  87988. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87989. var direction = this._originDirection;
  87990. }
  87991. else {
  87992. var direction = impostorObjectCenter.subtract(this._originTop);
  87993. }
  87994. var multiplier = this._strength * -1;
  87995. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87996. return { force: force, contactPoint: impostorObjectCenter };
  87997. };
  87998. PhysicsUpdraftEvent.prototype._tick = function () {
  87999. var _this = this;
  88000. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88001. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88002. if (!impostorForceAndContactPoint) {
  88003. return;
  88004. }
  88005. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88006. });
  88007. };
  88008. /*** Helpers ***/
  88009. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  88010. if (!this._cylinder) {
  88011. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  88012. height: this._height,
  88013. diameter: this._radius * 2,
  88014. }, this._scene);
  88015. this._cylinder.isVisible = false;
  88016. }
  88017. };
  88018. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  88019. var impostorObject = impostor.object;
  88020. this._prepareCylinder();
  88021. this._cylinder.position = this._cylinderPosition;
  88022. return this._cylinder.intersectsMesh(impostorObject, true);
  88023. };
  88024. return PhysicsUpdraftEvent;
  88025. }());
  88026. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  88027. /***** Vortex *****/
  88028. var PhysicsVortexEvent = /** @class */ (function () {
  88029. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  88030. this._scene = _scene;
  88031. this._origin = _origin;
  88032. this._radius = _radius;
  88033. this._strength = _strength;
  88034. this._height = _height;
  88035. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88036. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  88037. this._updraftMultiplier = 0.02;
  88038. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88039. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88040. this._physicsEngine = this._scene.getPhysicsEngine();
  88041. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88042. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88043. this._tickCallback = this._tick.bind(this);
  88044. }
  88045. /**
  88046. * Returns the data related to the vortex event (cylinder).
  88047. * @returns {PhysicsVortexEventData}
  88048. */
  88049. PhysicsVortexEvent.prototype.getData = function () {
  88050. this._dataFetched = true;
  88051. return {
  88052. cylinder: this._cylinder,
  88053. };
  88054. };
  88055. /**
  88056. * Enables the vortex.
  88057. */
  88058. PhysicsVortexEvent.prototype.enable = function () {
  88059. this._tickCallback.call(this);
  88060. this._scene.registerBeforeRender(this._tickCallback);
  88061. };
  88062. /**
  88063. * Disables the cortex.
  88064. */
  88065. PhysicsVortexEvent.prototype.disable = function () {
  88066. this._scene.unregisterBeforeRender(this._tickCallback);
  88067. };
  88068. /**
  88069. * Disposes the sphere.
  88070. * @param {bolean} force
  88071. */
  88072. PhysicsVortexEvent.prototype.dispose = function (force) {
  88073. var _this = this;
  88074. if (force === void 0) { force = true; }
  88075. if (force) {
  88076. this._cylinder.dispose();
  88077. }
  88078. else {
  88079. setTimeout(function () {
  88080. if (!_this._dataFetched) {
  88081. _this._cylinder.dispose();
  88082. }
  88083. }, 0);
  88084. }
  88085. };
  88086. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88087. if (impostor.mass === 0) {
  88088. return null;
  88089. }
  88090. if (!this._intersectsWithCylinder(impostor)) {
  88091. return null;
  88092. }
  88093. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88094. return null;
  88095. }
  88096. var impostorObjectCenter = impostor.getObjectCenter();
  88097. 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)
  88098. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  88099. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  88100. var hit = ray.intersectsMesh(impostor.object);
  88101. var contactPoint = hit.pickedPoint;
  88102. if (!contactPoint) {
  88103. return null;
  88104. }
  88105. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  88106. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  88107. var directionToOrigin = contactPoint.normalize();
  88108. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88109. directionToOrigin = directionToOrigin.negate();
  88110. }
  88111. // TODO: find a more physically based solution
  88112. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88113. var forceX = directionToOrigin.x * this._strength / 8;
  88114. var forceY = directionToOrigin.y * this._updraftMultiplier;
  88115. var forceZ = directionToOrigin.z * this._strength / 8;
  88116. }
  88117. else {
  88118. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  88119. var forceY = this._originTop.y * this._updraftMultiplier;
  88120. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  88121. }
  88122. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  88123. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  88124. return { force: force, contactPoint: impostorObjectCenter };
  88125. };
  88126. PhysicsVortexEvent.prototype._tick = function () {
  88127. var _this = this;
  88128. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88129. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88130. if (!impostorForceAndContactPoint) {
  88131. return;
  88132. }
  88133. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88134. });
  88135. };
  88136. /*** Helpers ***/
  88137. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  88138. if (!this._cylinder) {
  88139. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  88140. height: this._height,
  88141. diameter: this._radius * 2,
  88142. }, this._scene);
  88143. this._cylinder.isVisible = false;
  88144. }
  88145. };
  88146. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  88147. var impostorObject = impostor.object;
  88148. this._prepareCylinder();
  88149. this._cylinder.position = this._cylinderPosition;
  88150. return this._cylinder.intersectsMesh(impostorObject, true);
  88151. };
  88152. return PhysicsVortexEvent;
  88153. }());
  88154. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  88155. /***** Enums *****/
  88156. /**
  88157. * The strenght of the force in correspondence to the distance of the affected object
  88158. */
  88159. var PhysicsRadialImpulseFalloff;
  88160. (function (PhysicsRadialImpulseFalloff) {
  88161. /** Defines that impulse is constant in strength across it's whole radius */
  88162. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  88163. /** DEfines that impulse gets weaker if it's further from the origin */
  88164. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  88165. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  88166. /**
  88167. * The strenght of the force in correspondence to the distance of the affected object
  88168. */
  88169. var PhysicsUpdraftMode;
  88170. (function (PhysicsUpdraftMode) {
  88171. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  88172. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  88173. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  88174. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  88175. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  88176. })(BABYLON || (BABYLON = {}));
  88177. //# sourceMappingURL=babylon.physicsHelper.js.map
  88178. var BABYLON;
  88179. (function (BABYLON) {
  88180. var CannonJSPlugin = /** @class */ (function () {
  88181. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  88182. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  88183. if (iterations === void 0) { iterations = 10; }
  88184. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  88185. this.name = "CannonJSPlugin";
  88186. this._physicsMaterials = new Array();
  88187. this._fixedTimeStep = 1 / 60;
  88188. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  88189. this.BJSCANNON = CANNON;
  88190. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  88191. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  88192. this._tmpPosition = BABYLON.Vector3.Zero();
  88193. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  88194. this._tmpUnityRotation = new BABYLON.Quaternion();
  88195. if (!this.isSupported()) {
  88196. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  88197. return;
  88198. }
  88199. this._extendNamespace();
  88200. this.world = new this.BJSCANNON.World();
  88201. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  88202. this.world.solver.iterations = iterations;
  88203. }
  88204. CannonJSPlugin.prototype.setGravity = function (gravity) {
  88205. this.world.gravity.copy(gravity);
  88206. };
  88207. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  88208. this._fixedTimeStep = timeStep;
  88209. };
  88210. CannonJSPlugin.prototype.getTimeStep = function () {
  88211. return this._fixedTimeStep;
  88212. };
  88213. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  88214. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  88215. };
  88216. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88217. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88218. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88219. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  88220. };
  88221. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88222. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88223. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88224. impostor.physicsBody.applyForce(impulse, worldPoint);
  88225. };
  88226. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88227. //parent-child relationship. Does this impostor has a parent impostor?
  88228. if (impostor.parent) {
  88229. if (impostor.physicsBody) {
  88230. this.removePhysicsBody(impostor);
  88231. //TODO is that needed?
  88232. impostor.forceUpdate();
  88233. }
  88234. return;
  88235. }
  88236. //should a new body be created for this impostor?
  88237. if (impostor.isBodyInitRequired()) {
  88238. var shape = this._createShape(impostor);
  88239. //unregister events, if body is being changed
  88240. var oldBody = impostor.physicsBody;
  88241. if (oldBody) {
  88242. this.removePhysicsBody(impostor);
  88243. }
  88244. //create the body and material
  88245. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  88246. var bodyCreationObject = {
  88247. mass: impostor.getParam("mass"),
  88248. material: material
  88249. };
  88250. // A simple extend, in case native options were used.
  88251. var nativeOptions = impostor.getParam("nativeOptions");
  88252. for (var key in nativeOptions) {
  88253. if (nativeOptions.hasOwnProperty(key)) {
  88254. bodyCreationObject[key] = nativeOptions[key];
  88255. }
  88256. }
  88257. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  88258. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  88259. this.world.addEventListener("preStep", impostor.beforeStep);
  88260. this.world.addEventListener("postStep", impostor.afterStep);
  88261. impostor.physicsBody.addShape(shape);
  88262. this.world.add(impostor.physicsBody);
  88263. //try to keep the body moving in the right direction by taking old properties.
  88264. //Should be tested!
  88265. if (oldBody) {
  88266. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  88267. impostor.physicsBody[param].copy(oldBody[param]);
  88268. });
  88269. }
  88270. this._processChildMeshes(impostor);
  88271. }
  88272. //now update the body's transformation
  88273. this._updatePhysicsBodyTransformation(impostor);
  88274. };
  88275. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  88276. var _this = this;
  88277. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  88278. var currentRotation = mainImpostor.object.rotationQuaternion;
  88279. if (meshChildren.length) {
  88280. var processMesh = function (localPosition, mesh) {
  88281. if (!currentRotation || !mesh.rotationQuaternion) {
  88282. return;
  88283. }
  88284. var childImpostor = mesh.getPhysicsImpostor();
  88285. if (childImpostor) {
  88286. var parent = childImpostor.parent;
  88287. if (parent !== mainImpostor) {
  88288. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  88289. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  88290. if (childImpostor.physicsBody) {
  88291. _this.removePhysicsBody(childImpostor);
  88292. childImpostor.physicsBody = null;
  88293. }
  88294. childImpostor.parent = mainImpostor;
  88295. childImpostor.resetUpdateFlags();
  88296. 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));
  88297. //Add the mass of the children.
  88298. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  88299. }
  88300. }
  88301. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  88302. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  88303. };
  88304. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  88305. }
  88306. };
  88307. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88308. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  88309. this.world.removeEventListener("preStep", impostor.beforeStep);
  88310. this.world.removeEventListener("postStep", impostor.afterStep);
  88311. this.world.remove(impostor.physicsBody);
  88312. };
  88313. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88314. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88315. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88316. if (!mainBody || !connectedBody) {
  88317. return;
  88318. }
  88319. var constraint;
  88320. var jointData = impostorJoint.joint.jointData;
  88321. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  88322. var constraintData = {
  88323. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  88324. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  88325. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  88326. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  88327. maxForce: jointData.nativeParams.maxForce,
  88328. collideConnected: !!jointData.collision
  88329. };
  88330. switch (impostorJoint.joint.type) {
  88331. case BABYLON.PhysicsJoint.HingeJoint:
  88332. case BABYLON.PhysicsJoint.Hinge2Joint:
  88333. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  88334. break;
  88335. case BABYLON.PhysicsJoint.DistanceJoint:
  88336. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  88337. break;
  88338. case BABYLON.PhysicsJoint.SpringJoint:
  88339. var springData = jointData;
  88340. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  88341. restLength: springData.length,
  88342. stiffness: springData.stiffness,
  88343. damping: springData.damping,
  88344. localAnchorA: constraintData.pivotA,
  88345. localAnchorB: constraintData.pivotB
  88346. });
  88347. break;
  88348. case BABYLON.PhysicsJoint.LockJoint:
  88349. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  88350. break;
  88351. case BABYLON.PhysicsJoint.PointToPointJoint:
  88352. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88353. default:
  88354. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  88355. break;
  88356. }
  88357. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  88358. constraint.collideConnected = !!jointData.collision;
  88359. impostorJoint.joint.physicsJoint = constraint;
  88360. //don't add spring as constraint, as it is not one.
  88361. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  88362. this.world.addConstraint(constraint);
  88363. }
  88364. else {
  88365. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  88366. constraint.applyForce();
  88367. });
  88368. }
  88369. };
  88370. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88371. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  88372. };
  88373. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  88374. var index;
  88375. var mat;
  88376. for (index = 0; index < this._physicsMaterials.length; index++) {
  88377. mat = this._physicsMaterials[index];
  88378. if (mat.friction === friction && mat.restitution === restitution) {
  88379. return mat;
  88380. }
  88381. }
  88382. var currentMat = new this.BJSCANNON.Material(name);
  88383. currentMat.friction = friction;
  88384. currentMat.restitution = restitution;
  88385. this._physicsMaterials.push(currentMat);
  88386. return currentMat;
  88387. };
  88388. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  88389. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  88390. };
  88391. CannonJSPlugin.prototype._createShape = function (impostor) {
  88392. var object = impostor.object;
  88393. var returnValue;
  88394. var extendSize = impostor.getObjectExtendSize();
  88395. switch (impostor.type) {
  88396. case BABYLON.PhysicsImpostor.SphereImpostor:
  88397. var radiusX = extendSize.x;
  88398. var radiusY = extendSize.y;
  88399. var radiusZ = extendSize.z;
  88400. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  88401. break;
  88402. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  88403. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88404. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  88405. break;
  88406. case BABYLON.PhysicsImpostor.BoxImpostor:
  88407. var box = extendSize.scale(0.5);
  88408. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  88409. break;
  88410. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88411. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  88412. returnValue = new this.BJSCANNON.Plane();
  88413. break;
  88414. case BABYLON.PhysicsImpostor.MeshImpostor:
  88415. // should transform the vertex data to world coordinates!!
  88416. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  88417. var rawFaces = object.getIndices ? object.getIndices() : [];
  88418. if (!rawVerts)
  88419. return;
  88420. // get only scale! so the object could transform correctly.
  88421. var oldPosition = object.position.clone();
  88422. var oldRotation = object.rotation && object.rotation.clone();
  88423. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  88424. object.position.copyFromFloats(0, 0, 0);
  88425. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88426. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88427. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88428. var transform = object.computeWorldMatrix(true);
  88429. // convert rawVerts to object space
  88430. var temp = new Array();
  88431. var index;
  88432. for (index = 0; index < rawVerts.length; index += 3) {
  88433. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  88434. }
  88435. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  88436. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  88437. //now set back the transformation!
  88438. object.position.copyFrom(oldPosition);
  88439. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  88440. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  88441. break;
  88442. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  88443. var oldPosition2 = object.position.clone();
  88444. var oldRotation2 = object.rotation && object.rotation.clone();
  88445. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  88446. object.position.copyFromFloats(0, 0, 0);
  88447. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88448. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88449. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88450. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  88451. returnValue = this._createHeightmap(object);
  88452. object.position.copyFrom(oldPosition2);
  88453. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  88454. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  88455. object.computeWorldMatrix(true);
  88456. break;
  88457. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88458. returnValue = new this.BJSCANNON.Particle();
  88459. break;
  88460. }
  88461. return returnValue;
  88462. };
  88463. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  88464. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88465. var transform = object.computeWorldMatrix(true);
  88466. // convert rawVerts to object space
  88467. var temp = new Array();
  88468. var index;
  88469. for (index = 0; index < pos.length; index += 3) {
  88470. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  88471. }
  88472. pos = temp;
  88473. var matrix = new Array();
  88474. //For now pointDepth will not be used and will be automatically calculated.
  88475. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  88476. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  88477. var boundingInfo = object.getBoundingInfo();
  88478. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  88479. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  88480. var elementSize = dim * 2 / arraySize;
  88481. for (var i = 0; i < pos.length; i = i + 3) {
  88482. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  88483. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  88484. var y = -pos[i + 2] + minY;
  88485. if (!matrix[x]) {
  88486. matrix[x] = [];
  88487. }
  88488. if (!matrix[x][z]) {
  88489. matrix[x][z] = y;
  88490. }
  88491. matrix[x][z] = Math.max(y, matrix[x][z]);
  88492. }
  88493. for (var x = 0; x <= arraySize; ++x) {
  88494. if (!matrix[x]) {
  88495. var loc = 1;
  88496. while (!matrix[(x + loc) % arraySize]) {
  88497. loc++;
  88498. }
  88499. matrix[x] = matrix[(x + loc) % arraySize].slice();
  88500. //console.log("missing x", x);
  88501. }
  88502. for (var z = 0; z <= arraySize; ++z) {
  88503. if (!matrix[x][z]) {
  88504. var loc = 1;
  88505. var newValue;
  88506. while (newValue === undefined) {
  88507. newValue = matrix[x][(z + loc++) % arraySize];
  88508. }
  88509. matrix[x][z] = newValue;
  88510. }
  88511. }
  88512. }
  88513. var shape = new this.BJSCANNON.Heightfield(matrix, {
  88514. elementSize: elementSize
  88515. });
  88516. //For future reference, needed for body transformation
  88517. shape.minY = minY;
  88518. return shape;
  88519. };
  88520. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  88521. var object = impostor.object;
  88522. //make sure it is updated...
  88523. object.computeWorldMatrix && object.computeWorldMatrix(true);
  88524. // The delta between the mesh position and the mesh bounding box center
  88525. var bInfo = object.getBoundingInfo();
  88526. if (!bInfo)
  88527. return;
  88528. var center = impostor.getObjectCenter();
  88529. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  88530. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  88531. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  88532. this._tmpPosition.copyFrom(center);
  88533. var quaternion = object.rotationQuaternion;
  88534. if (!quaternion) {
  88535. return;
  88536. }
  88537. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  88538. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  88539. //-90 DEG in X, precalculated
  88540. quaternion = quaternion.multiply(this._minus90X);
  88541. //Invert! (Precalculated, 90 deg in X)
  88542. //No need to clone. this will never change.
  88543. impostor.setDeltaRotation(this._plus90X);
  88544. }
  88545. //If it is a heightfield, if should be centered.
  88546. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  88547. var mesh = object;
  88548. var boundingInfo = mesh.getBoundingInfo();
  88549. //calculate the correct body position:
  88550. var rotationQuaternion = mesh.rotationQuaternion;
  88551. mesh.rotationQuaternion = this._tmpUnityRotation;
  88552. mesh.computeWorldMatrix(true);
  88553. //get original center with no rotation
  88554. var c = center.clone();
  88555. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  88556. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  88557. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  88558. mesh.setPreTransformMatrix(p);
  88559. mesh.computeWorldMatrix(true);
  88560. //calculate the translation
  88561. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  88562. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  88563. //add it inverted to the delta
  88564. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  88565. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  88566. //rotation is back
  88567. mesh.rotationQuaternion = rotationQuaternion;
  88568. mesh.setPreTransformMatrix(oldPivot);
  88569. mesh.computeWorldMatrix(true);
  88570. }
  88571. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  88572. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  88573. //this._tmpPosition.copyFrom(object.position);
  88574. }
  88575. impostor.setDeltaPosition(this._tmpDeltaPosition);
  88576. //Now update the impostor object
  88577. impostor.physicsBody.position.copy(this._tmpPosition);
  88578. impostor.physicsBody.quaternion.copy(quaternion);
  88579. };
  88580. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88581. impostor.object.position.copyFrom(impostor.physicsBody.position);
  88582. if (impostor.object.rotationQuaternion) {
  88583. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  88584. }
  88585. };
  88586. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88587. impostor.physicsBody.position.copy(newPosition);
  88588. impostor.physicsBody.quaternion.copy(newRotation);
  88589. };
  88590. CannonJSPlugin.prototype.isSupported = function () {
  88591. return this.BJSCANNON !== undefined;
  88592. };
  88593. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88594. impostor.physicsBody.velocity.copy(velocity);
  88595. };
  88596. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88597. impostor.physicsBody.angularVelocity.copy(velocity);
  88598. };
  88599. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88600. var v = impostor.physicsBody.velocity;
  88601. if (!v) {
  88602. return null;
  88603. }
  88604. return new BABYLON.Vector3(v.x, v.y, v.z);
  88605. };
  88606. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88607. var v = impostor.physicsBody.angularVelocity;
  88608. if (!v) {
  88609. return null;
  88610. }
  88611. return new BABYLON.Vector3(v.x, v.y, v.z);
  88612. };
  88613. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88614. impostor.physicsBody.mass = mass;
  88615. impostor.physicsBody.updateMassProperties();
  88616. };
  88617. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  88618. return impostor.physicsBody.mass;
  88619. };
  88620. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  88621. return impostor.physicsBody.material.friction;
  88622. };
  88623. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88624. impostor.physicsBody.material.friction = friction;
  88625. };
  88626. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88627. return impostor.physicsBody.material.restitution;
  88628. };
  88629. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88630. impostor.physicsBody.material.restitution = restitution;
  88631. };
  88632. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  88633. impostor.physicsBody.sleep();
  88634. };
  88635. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  88636. impostor.physicsBody.wakeUp();
  88637. };
  88638. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88639. joint.physicsJoint.distance = maxDistance;
  88640. };
  88641. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88642. // if (!motorIndex) {
  88643. // joint.physicsJoint.enableMotor();
  88644. // }
  88645. // }
  88646. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88647. // if (!motorIndex) {
  88648. // joint.physicsJoint.disableMotor();
  88649. // }
  88650. // }
  88651. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88652. if (!motorIndex) {
  88653. joint.physicsJoint.enableMotor();
  88654. joint.physicsJoint.setMotorSpeed(speed);
  88655. if (maxForce) {
  88656. this.setLimit(joint, maxForce);
  88657. }
  88658. }
  88659. };
  88660. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  88661. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  88662. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  88663. };
  88664. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88665. var body = impostor.physicsBody;
  88666. mesh.position.x = body.position.x;
  88667. mesh.position.y = body.position.y;
  88668. mesh.position.z = body.position.z;
  88669. if (mesh.rotationQuaternion) {
  88670. mesh.rotationQuaternion.x = body.quaternion.x;
  88671. mesh.rotationQuaternion.y = body.quaternion.y;
  88672. mesh.rotationQuaternion.z = body.quaternion.z;
  88673. mesh.rotationQuaternion.w = body.quaternion.w;
  88674. }
  88675. };
  88676. CannonJSPlugin.prototype.getRadius = function (impostor) {
  88677. var shape = impostor.physicsBody.shapes[0];
  88678. return shape.boundingSphereRadius;
  88679. };
  88680. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88681. var shape = impostor.physicsBody.shapes[0];
  88682. result.x = shape.halfExtents.x * 2;
  88683. result.y = shape.halfExtents.y * 2;
  88684. result.z = shape.halfExtents.z * 2;
  88685. };
  88686. CannonJSPlugin.prototype.dispose = function () {
  88687. };
  88688. CannonJSPlugin.prototype._extendNamespace = function () {
  88689. //this will force cannon to execute at least one step when using interpolation
  88690. var step_tmp1 = new this.BJSCANNON.Vec3();
  88691. var Engine = this.BJSCANNON;
  88692. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  88693. maxSubSteps = maxSubSteps || 10;
  88694. timeSinceLastCalled = timeSinceLastCalled || 0;
  88695. if (timeSinceLastCalled === 0) {
  88696. this.internalStep(dt);
  88697. this.time += dt;
  88698. }
  88699. else {
  88700. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  88701. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  88702. var t0 = performance.now();
  88703. for (var i = 0; i !== internalSteps; i++) {
  88704. this.internalStep(dt);
  88705. if (performance.now() - t0 > dt * 1000) {
  88706. break;
  88707. }
  88708. }
  88709. this.time += timeSinceLastCalled;
  88710. var h = this.time % dt;
  88711. var h_div_dt = h / dt;
  88712. var interpvelo = step_tmp1;
  88713. var bodies = this.bodies;
  88714. for (var j = 0; j !== bodies.length; j++) {
  88715. var b = bodies[j];
  88716. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  88717. b.position.vsub(b.previousPosition, interpvelo);
  88718. interpvelo.scale(h_div_dt, interpvelo);
  88719. b.position.vadd(interpvelo, b.interpolatedPosition);
  88720. }
  88721. else {
  88722. b.interpolatedPosition.copy(b.position);
  88723. b.interpolatedQuaternion.copy(b.quaternion);
  88724. }
  88725. }
  88726. }
  88727. };
  88728. };
  88729. return CannonJSPlugin;
  88730. }());
  88731. BABYLON.CannonJSPlugin = CannonJSPlugin;
  88732. })(BABYLON || (BABYLON = {}));
  88733. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  88734. var BABYLON;
  88735. (function (BABYLON) {
  88736. var OimoJSPlugin = /** @class */ (function () {
  88737. function OimoJSPlugin(iterations) {
  88738. this.name = "OimoJSPlugin";
  88739. this._tmpImpostorsArray = [];
  88740. this._tmpPositionVector = BABYLON.Vector3.Zero();
  88741. this.BJSOIMO = OIMO;
  88742. this.world = new this.BJSOIMO.World({
  88743. iterations: iterations
  88744. });
  88745. this.world.clear();
  88746. }
  88747. OimoJSPlugin.prototype.setGravity = function (gravity) {
  88748. this.world.gravity.copy(gravity);
  88749. };
  88750. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  88751. this.world.timeStep = timeStep;
  88752. };
  88753. OimoJSPlugin.prototype.getTimeStep = function () {
  88754. return this.world.timeStep;
  88755. };
  88756. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  88757. var _this = this;
  88758. impostors.forEach(function (impostor) {
  88759. impostor.beforeStep();
  88760. });
  88761. this.world.step();
  88762. impostors.forEach(function (impostor) {
  88763. impostor.afterStep();
  88764. //update the ordered impostors array
  88765. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  88766. });
  88767. //check for collisions
  88768. var contact = this.world.contacts;
  88769. while (contact !== null) {
  88770. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  88771. contact = contact.next;
  88772. continue;
  88773. }
  88774. //is this body colliding with any other? get the impostor
  88775. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  88776. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  88777. if (!mainImpostor || !collidingImpostor) {
  88778. contact = contact.next;
  88779. continue;
  88780. }
  88781. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  88782. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  88783. contact = contact.next;
  88784. }
  88785. };
  88786. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88787. var mass = impostor.physicsBody.mass;
  88788. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  88789. };
  88790. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88791. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  88792. this.applyImpulse(impostor, force, contactPoint);
  88793. };
  88794. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88795. var _this = this;
  88796. //parent-child relationship. Does this impostor has a parent impostor?
  88797. if (impostor.parent) {
  88798. if (impostor.physicsBody) {
  88799. this.removePhysicsBody(impostor);
  88800. //TODO is that needed?
  88801. impostor.forceUpdate();
  88802. }
  88803. return;
  88804. }
  88805. if (impostor.isBodyInitRequired()) {
  88806. var bodyConfig = {
  88807. name: impostor.uniqueId,
  88808. //Oimo must have mass, also for static objects.
  88809. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  88810. size: [],
  88811. type: [],
  88812. pos: [],
  88813. posShape: [],
  88814. rot: [],
  88815. rotShape: [],
  88816. move: impostor.getParam("mass") !== 0,
  88817. density: impostor.getParam("mass"),
  88818. friction: impostor.getParam("friction"),
  88819. restitution: impostor.getParam("restitution"),
  88820. //Supporting older versions of Oimo
  88821. world: this.world
  88822. };
  88823. var impostors = [impostor];
  88824. var addToArray = function (parent) {
  88825. if (!parent.getChildMeshes)
  88826. return;
  88827. parent.getChildMeshes().forEach(function (m) {
  88828. if (m.physicsImpostor) {
  88829. impostors.push(m.physicsImpostor);
  88830. //m.physicsImpostor._init();
  88831. }
  88832. });
  88833. };
  88834. addToArray(impostor.object);
  88835. var checkWithEpsilon_1 = function (value) {
  88836. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  88837. };
  88838. var globalQuaternion_1 = new BABYLON.Quaternion();
  88839. impostors.forEach(function (i) {
  88840. if (!i.object.rotationQuaternion) {
  88841. return;
  88842. }
  88843. //get the correct bounding box
  88844. var oldQuaternion = i.object.rotationQuaternion;
  88845. globalQuaternion_1 = oldQuaternion.clone();
  88846. var rot = oldQuaternion.toEulerAngles();
  88847. var extendSize = i.getObjectExtendSize();
  88848. var radToDeg = 57.295779513082320876;
  88849. if (i === impostor) {
  88850. var center = impostor.getObjectCenter();
  88851. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  88852. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  88853. //Can also use Array.prototype.push.apply
  88854. bodyConfig.pos.push(center.x);
  88855. bodyConfig.pos.push(center.y);
  88856. bodyConfig.pos.push(center.z);
  88857. bodyConfig.posShape.push(0, 0, 0);
  88858. //tmp solution
  88859. bodyConfig.rot.push(0);
  88860. bodyConfig.rot.push(0);
  88861. bodyConfig.rot.push(0);
  88862. bodyConfig.rotShape.push(0, 0, 0);
  88863. }
  88864. else {
  88865. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  88866. bodyConfig.posShape.push(localPosition.x);
  88867. bodyConfig.posShape.push(localPosition.y);
  88868. bodyConfig.posShape.push(localPosition.z);
  88869. bodyConfig.pos.push(0, 0, 0);
  88870. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  88871. bodyConfig.rot.push(0);
  88872. bodyConfig.rot.push(0);
  88873. bodyConfig.rot.push(0);
  88874. bodyConfig.rotShape.push(rot.x * radToDeg);
  88875. bodyConfig.rotShape.push(rot.y * radToDeg);
  88876. bodyConfig.rotShape.push(rot.z * radToDeg);
  88877. }
  88878. // register mesh
  88879. switch (i.type) {
  88880. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88881. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  88882. case BABYLON.PhysicsImpostor.SphereImpostor:
  88883. var radiusX = extendSize.x;
  88884. var radiusY = extendSize.y;
  88885. var radiusZ = extendSize.z;
  88886. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  88887. bodyConfig.type.push('sphere');
  88888. //due to the way oimo works with compounds, add 3 times
  88889. bodyConfig.size.push(size);
  88890. bodyConfig.size.push(size);
  88891. bodyConfig.size.push(size);
  88892. break;
  88893. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88894. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  88895. var sizeY = checkWithEpsilon_1(extendSize.y);
  88896. bodyConfig.type.push('cylinder');
  88897. bodyConfig.size.push(sizeX);
  88898. bodyConfig.size.push(sizeY);
  88899. //due to the way oimo works with compounds, add one more value.
  88900. bodyConfig.size.push(sizeY);
  88901. break;
  88902. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88903. case BABYLON.PhysicsImpostor.BoxImpostor:
  88904. default:
  88905. var sizeX = checkWithEpsilon_1(extendSize.x);
  88906. var sizeY = checkWithEpsilon_1(extendSize.y);
  88907. var sizeZ = checkWithEpsilon_1(extendSize.z);
  88908. bodyConfig.type.push('box');
  88909. //if (i === impostor) {
  88910. bodyConfig.size.push(sizeX);
  88911. bodyConfig.size.push(sizeY);
  88912. bodyConfig.size.push(sizeZ);
  88913. //} else {
  88914. // bodyConfig.size.push(0,0,0);
  88915. //}
  88916. break;
  88917. }
  88918. //actually not needed, but hey...
  88919. i.object.rotationQuaternion = oldQuaternion;
  88920. });
  88921. impostor.physicsBody = this.world.add(bodyConfig);
  88922. // set the quaternion, ignoring the previously defined (euler) rotation
  88923. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  88924. // update with delta 0, so the body will reveive the new rotation.
  88925. impostor.physicsBody.updatePosition(0);
  88926. }
  88927. else {
  88928. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  88929. }
  88930. impostor.setDeltaPosition(this._tmpPositionVector);
  88931. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  88932. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  88933. };
  88934. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88935. //impostor.physicsBody.dispose();
  88936. //Same as : (older oimo versions)
  88937. this.world.removeRigidBody(impostor.physicsBody);
  88938. };
  88939. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88940. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88941. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88942. if (!mainBody || !connectedBody) {
  88943. return;
  88944. }
  88945. var jointData = impostorJoint.joint.jointData;
  88946. var options = jointData.nativeParams || {};
  88947. var type;
  88948. var nativeJointData = {
  88949. body1: mainBody,
  88950. body2: connectedBody,
  88951. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  88952. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  88953. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  88954. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  88955. min: options.min,
  88956. max: options.max,
  88957. collision: options.collision || jointData.collision,
  88958. spring: options.spring,
  88959. //supporting older version of Oimo
  88960. world: this.world
  88961. };
  88962. switch (impostorJoint.joint.type) {
  88963. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88964. type = "jointBall";
  88965. break;
  88966. case BABYLON.PhysicsJoint.SpringJoint:
  88967. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  88968. var springData = jointData;
  88969. nativeJointData.min = springData.length || nativeJointData.min;
  88970. //Max should also be set, just make sure it is at least min
  88971. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  88972. case BABYLON.PhysicsJoint.DistanceJoint:
  88973. type = "jointDistance";
  88974. nativeJointData.max = jointData.maxDistance;
  88975. break;
  88976. case BABYLON.PhysicsJoint.PrismaticJoint:
  88977. type = "jointPrisme";
  88978. break;
  88979. case BABYLON.PhysicsJoint.SliderJoint:
  88980. type = "jointSlide";
  88981. break;
  88982. case BABYLON.PhysicsJoint.WheelJoint:
  88983. type = "jointWheel";
  88984. break;
  88985. case BABYLON.PhysicsJoint.HingeJoint:
  88986. default:
  88987. type = "jointHinge";
  88988. break;
  88989. }
  88990. nativeJointData.type = type;
  88991. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  88992. };
  88993. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88994. //Bug in Oimo prevents us from disposing a joint in the playground
  88995. //joint.joint.physicsJoint.dispose();
  88996. //So we will bruteforce it!
  88997. try {
  88998. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  88999. }
  89000. catch (e) {
  89001. BABYLON.Tools.Warn(e);
  89002. }
  89003. };
  89004. OimoJSPlugin.prototype.isSupported = function () {
  89005. return this.BJSOIMO !== undefined;
  89006. };
  89007. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89008. if (!impostor.physicsBody.sleeping) {
  89009. //TODO check that
  89010. /*if (impostor.physicsBody.shapes.next) {
  89011. var parentShape = this._getLastShape(impostor.physicsBody);
  89012. impostor.object.position.copyFrom(parentShape.position);
  89013. console.log(parentShape.position);
  89014. } else {*/
  89015. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  89016. //}
  89017. if (impostor.object.rotationQuaternion) {
  89018. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  89019. }
  89020. }
  89021. };
  89022. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89023. var body = impostor.physicsBody;
  89024. body.position.copy(newPosition);
  89025. body.orientation.copy(newRotation);
  89026. body.syncShapes();
  89027. body.awake();
  89028. };
  89029. /*private _getLastShape(body: any): any {
  89030. var lastShape = body.shapes;
  89031. while (lastShape.next) {
  89032. lastShape = lastShape.next;
  89033. }
  89034. return lastShape;
  89035. }*/
  89036. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89037. impostor.physicsBody.linearVelocity.copy(velocity);
  89038. };
  89039. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89040. impostor.physicsBody.angularVelocity.copy(velocity);
  89041. };
  89042. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89043. var v = impostor.physicsBody.linearVelocity;
  89044. if (!v) {
  89045. return null;
  89046. }
  89047. return new BABYLON.Vector3(v.x, v.y, v.z);
  89048. };
  89049. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89050. var v = impostor.physicsBody.angularVelocity;
  89051. if (!v) {
  89052. return null;
  89053. }
  89054. return new BABYLON.Vector3(v.x, v.y, v.z);
  89055. };
  89056. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89057. var staticBody = mass === 0;
  89058. //this will actually set the body's density and not its mass.
  89059. //But this is how oimo treats the mass variable.
  89060. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  89061. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  89062. };
  89063. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  89064. return impostor.physicsBody.shapes.density;
  89065. };
  89066. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  89067. return impostor.physicsBody.shapes.friction;
  89068. };
  89069. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89070. impostor.physicsBody.shapes.friction = friction;
  89071. };
  89072. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89073. return impostor.physicsBody.shapes.restitution;
  89074. };
  89075. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89076. impostor.physicsBody.shapes.restitution = restitution;
  89077. };
  89078. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  89079. impostor.physicsBody.sleep();
  89080. };
  89081. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  89082. impostor.physicsBody.awake();
  89083. };
  89084. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89085. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  89086. if (minDistance !== void 0) {
  89087. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  89088. }
  89089. };
  89090. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89091. //TODO separate rotational and transational motors.
  89092. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89093. if (motor) {
  89094. motor.setMotor(speed, maxForce);
  89095. }
  89096. };
  89097. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  89098. //TODO separate rotational and transational motors.
  89099. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89100. if (motor) {
  89101. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  89102. }
  89103. };
  89104. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89105. var body = impostor.physicsBody;
  89106. mesh.position.x = body.position.x;
  89107. mesh.position.y = body.position.y;
  89108. mesh.position.z = body.position.z;
  89109. if (mesh.rotationQuaternion) {
  89110. mesh.rotationQuaternion.x = body.orientation.x;
  89111. mesh.rotationQuaternion.y = body.orientation.y;
  89112. mesh.rotationQuaternion.z = body.orientation.z;
  89113. mesh.rotationQuaternion.w = body.orientation.s;
  89114. }
  89115. };
  89116. OimoJSPlugin.prototype.getRadius = function (impostor) {
  89117. return impostor.physicsBody.shapes.radius;
  89118. };
  89119. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89120. var shape = impostor.physicsBody.shapes;
  89121. result.x = shape.halfWidth * 2;
  89122. result.y = shape.halfHeight * 2;
  89123. result.z = shape.halfDepth * 2;
  89124. };
  89125. OimoJSPlugin.prototype.dispose = function () {
  89126. this.world.clear();
  89127. };
  89128. return OimoJSPlugin;
  89129. }());
  89130. BABYLON.OimoJSPlugin = OimoJSPlugin;
  89131. })(BABYLON || (BABYLON = {}));
  89132. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  89133. var BABYLON;
  89134. (function (BABYLON) {
  89135. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  89136. // All values and structures referenced from:
  89137. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  89138. var DDS_MAGIC = 0x20534444;
  89139. var
  89140. //DDSD_CAPS = 0x1,
  89141. //DDSD_HEIGHT = 0x2,
  89142. //DDSD_WIDTH = 0x4,
  89143. //DDSD_PITCH = 0x8,
  89144. //DDSD_PIXELFORMAT = 0x1000,
  89145. DDSD_MIPMAPCOUNT = 0x20000;
  89146. //DDSD_LINEARSIZE = 0x80000,
  89147. //DDSD_DEPTH = 0x800000;
  89148. // var DDSCAPS_COMPLEX = 0x8,
  89149. // DDSCAPS_MIPMAP = 0x400000,
  89150. // DDSCAPS_TEXTURE = 0x1000;
  89151. var DDSCAPS2_CUBEMAP = 0x200;
  89152. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  89153. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  89154. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  89155. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  89156. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  89157. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  89158. // DDSCAPS2_VOLUME = 0x200000;
  89159. var
  89160. //DDPF_ALPHAPIXELS = 0x1,
  89161. //DDPF_ALPHA = 0x2,
  89162. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  89163. //DDPF_YUV = 0x200,
  89164. DDPF_LUMINANCE = 0x20000;
  89165. function FourCCToInt32(value) {
  89166. return value.charCodeAt(0) +
  89167. (value.charCodeAt(1) << 8) +
  89168. (value.charCodeAt(2) << 16) +
  89169. (value.charCodeAt(3) << 24);
  89170. }
  89171. function Int32ToFourCC(value) {
  89172. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  89173. }
  89174. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  89175. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  89176. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  89177. var FOURCC_DX10 = FourCCToInt32("DX10");
  89178. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  89179. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  89180. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  89181. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  89182. var headerLengthInt = 31; // The header length in 32 bit ints
  89183. // Offsets into the header array
  89184. var off_magic = 0;
  89185. var off_size = 1;
  89186. var off_flags = 2;
  89187. var off_height = 3;
  89188. var off_width = 4;
  89189. var off_mipmapCount = 7;
  89190. var off_pfFlags = 20;
  89191. var off_pfFourCC = 21;
  89192. var off_RGBbpp = 22;
  89193. var off_RMask = 23;
  89194. var off_GMask = 24;
  89195. var off_BMask = 25;
  89196. var off_AMask = 26;
  89197. // var off_caps1 = 27;
  89198. var off_caps2 = 28;
  89199. // var off_caps3 = 29;
  89200. // var off_caps4 = 30;
  89201. var off_dxgiFormat = 32;
  89202. ;
  89203. var DDSTools = /** @class */ (function () {
  89204. function DDSTools() {
  89205. }
  89206. DDSTools.GetDDSInfo = function (arrayBuffer) {
  89207. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89208. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  89209. var mipmapCount = 1;
  89210. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  89211. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89212. }
  89213. var fourCC = header[off_pfFourCC];
  89214. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  89215. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89216. switch (fourCC) {
  89217. case FOURCC_D3DFMT_R16G16B16A16F:
  89218. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89219. break;
  89220. case FOURCC_D3DFMT_R32G32B32A32F:
  89221. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89222. break;
  89223. case FOURCC_DX10:
  89224. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  89225. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89226. break;
  89227. }
  89228. }
  89229. return {
  89230. width: header[off_width],
  89231. height: header[off_height],
  89232. mipmapCount: mipmapCount,
  89233. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  89234. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  89235. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  89236. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  89237. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  89238. dxgiFormat: dxgiFormat,
  89239. textureType: textureType
  89240. };
  89241. };
  89242. DDSTools._ToHalfFloat = function (value) {
  89243. if (!DDSTools._FloatView) {
  89244. DDSTools._FloatView = new Float32Array(1);
  89245. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  89246. }
  89247. DDSTools._FloatView[0] = value;
  89248. var x = DDSTools._Int32View[0];
  89249. var bits = (x >> 16) & 0x8000; /* Get the sign */
  89250. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  89251. var e = (x >> 23) & 0xff; /* Using int is faster here */
  89252. /* If zero, or denormal, or exponent underflows too much for a denormal
  89253. * half, return signed zero. */
  89254. if (e < 103) {
  89255. return bits;
  89256. }
  89257. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  89258. if (e > 142) {
  89259. bits |= 0x7c00;
  89260. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  89261. * not Inf, so make sure we set one mantissa bit too. */
  89262. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  89263. return bits;
  89264. }
  89265. /* If exponent underflows but not too much, return a denormal */
  89266. if (e < 113) {
  89267. m |= 0x0800;
  89268. /* Extra rounding may overflow and set mantissa to 0 and exponent
  89269. * to 1, which is OK. */
  89270. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  89271. return bits;
  89272. }
  89273. bits |= ((e - 112) << 10) | (m >> 1);
  89274. bits += m & 1;
  89275. return bits;
  89276. };
  89277. DDSTools._FromHalfFloat = function (value) {
  89278. var s = (value & 0x8000) >> 15;
  89279. var e = (value & 0x7C00) >> 10;
  89280. var f = value & 0x03FF;
  89281. if (e === 0) {
  89282. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  89283. }
  89284. else if (e == 0x1F) {
  89285. return f ? NaN : ((s ? -1 : 1) * Infinity);
  89286. }
  89287. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  89288. };
  89289. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89290. var destArray = new Float32Array(dataLength);
  89291. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89292. var index = 0;
  89293. for (var y = 0; y < height; y++) {
  89294. for (var x = 0; x < width; x++) {
  89295. var srcPos = (x + y * width) * 4;
  89296. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  89297. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  89298. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  89299. if (DDSTools.StoreLODInAlphaChannel) {
  89300. destArray[index + 3] = lod;
  89301. }
  89302. else {
  89303. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  89304. }
  89305. index += 4;
  89306. }
  89307. }
  89308. return destArray;
  89309. };
  89310. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89311. if (DDSTools.StoreLODInAlphaChannel) {
  89312. var destArray = new Uint16Array(dataLength);
  89313. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89314. var index = 0;
  89315. for (var y = 0; y < height; y++) {
  89316. for (var x = 0; x < width; x++) {
  89317. var srcPos = (x + y * width) * 4;
  89318. destArray[index] = srcData[srcPos];
  89319. destArray[index + 1] = srcData[srcPos + 1];
  89320. destArray[index + 2] = srcData[srcPos + 2];
  89321. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  89322. index += 4;
  89323. }
  89324. }
  89325. return destArray;
  89326. }
  89327. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  89328. };
  89329. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89330. if (DDSTools.StoreLODInAlphaChannel) {
  89331. var destArray = new Float32Array(dataLength);
  89332. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89333. var index = 0;
  89334. for (var y = 0; y < height; y++) {
  89335. for (var x = 0; x < width; x++) {
  89336. var srcPos = (x + y * width) * 4;
  89337. destArray[index] = srcData[srcPos];
  89338. destArray[index + 1] = srcData[srcPos + 1];
  89339. destArray[index + 2] = srcData[srcPos + 2];
  89340. destArray[index + 3] = lod;
  89341. index += 4;
  89342. }
  89343. }
  89344. return destArray;
  89345. }
  89346. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  89347. };
  89348. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89349. var destArray = new Uint8Array(dataLength);
  89350. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89351. var index = 0;
  89352. for (var y = 0; y < height; y++) {
  89353. for (var x = 0; x < width; x++) {
  89354. var srcPos = (x + y * width) * 4;
  89355. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  89356. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  89357. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  89358. if (DDSTools.StoreLODInAlphaChannel) {
  89359. destArray[index + 3] = lod;
  89360. }
  89361. else {
  89362. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  89363. }
  89364. index += 4;
  89365. }
  89366. }
  89367. return destArray;
  89368. };
  89369. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89370. var destArray = new Uint8Array(dataLength);
  89371. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89372. var index = 0;
  89373. for (var y = 0; y < height; y++) {
  89374. for (var x = 0; x < width; x++) {
  89375. var srcPos = (x + y * width) * 4;
  89376. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  89377. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  89378. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  89379. if (DDSTools.StoreLODInAlphaChannel) {
  89380. destArray[index + 3] = lod;
  89381. }
  89382. else {
  89383. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  89384. }
  89385. index += 4;
  89386. }
  89387. }
  89388. return destArray;
  89389. };
  89390. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  89391. var byteArray = new Uint8Array(dataLength);
  89392. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89393. var index = 0;
  89394. for (var y = 0; y < height; y++) {
  89395. for (var x = 0; x < width; x++) {
  89396. var srcPos = (x + y * width) * 4;
  89397. byteArray[index] = srcData[srcPos + rOffset];
  89398. byteArray[index + 1] = srcData[srcPos + gOffset];
  89399. byteArray[index + 2] = srcData[srcPos + bOffset];
  89400. byteArray[index + 3] = srcData[srcPos + aOffset];
  89401. index += 4;
  89402. }
  89403. }
  89404. return byteArray;
  89405. };
  89406. DDSTools._ExtractLongWordOrder = function (value) {
  89407. if (value === 0 || value === 255 || value === -16777216) {
  89408. return 0;
  89409. }
  89410. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  89411. };
  89412. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  89413. var byteArray = new Uint8Array(dataLength);
  89414. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89415. var index = 0;
  89416. for (var y = 0; y < height; y++) {
  89417. for (var x = 0; x < width; x++) {
  89418. var srcPos = (x + y * width) * 3;
  89419. byteArray[index] = srcData[srcPos + rOffset];
  89420. byteArray[index + 1] = srcData[srcPos + gOffset];
  89421. byteArray[index + 2] = srcData[srcPos + bOffset];
  89422. index += 3;
  89423. }
  89424. }
  89425. return byteArray;
  89426. };
  89427. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  89428. var byteArray = new Uint8Array(dataLength);
  89429. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89430. var index = 0;
  89431. for (var y = 0; y < height; y++) {
  89432. for (var x = 0; x < width; x++) {
  89433. var srcPos = (x + y * width);
  89434. byteArray[index] = srcData[srcPos];
  89435. index++;
  89436. }
  89437. }
  89438. return byteArray;
  89439. };
  89440. /**
  89441. * Uploads DDS Levels to a Babylon Texture
  89442. * @hidden
  89443. */
  89444. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  89445. if (lodIndex === void 0) { lodIndex = -1; }
  89446. var sphericalPolynomialFaces = null;
  89447. if (info.sphericalPolynomial) {
  89448. sphericalPolynomialFaces = new Array();
  89449. }
  89450. var ext = engine.getCaps().s3tc;
  89451. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89452. var fourCC, width, height, dataLength = 0, dataOffset;
  89453. var byteArray, mipmapCount, mip;
  89454. var internalCompressedFormat = 0;
  89455. var blockBytes = 1;
  89456. if (header[off_magic] !== DDS_MAGIC) {
  89457. BABYLON.Tools.Error("Invalid magic number in DDS header");
  89458. return;
  89459. }
  89460. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  89461. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  89462. return;
  89463. }
  89464. if (info.isCompressed && !ext) {
  89465. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  89466. return;
  89467. }
  89468. var bpp = header[off_RGBbpp];
  89469. dataOffset = header[off_size] + 4;
  89470. var computeFormats = false;
  89471. if (info.isFourCC) {
  89472. fourCC = header[off_pfFourCC];
  89473. switch (fourCC) {
  89474. case FOURCC_DXT1:
  89475. blockBytes = 8;
  89476. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  89477. break;
  89478. case FOURCC_DXT3:
  89479. blockBytes = 16;
  89480. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  89481. break;
  89482. case FOURCC_DXT5:
  89483. blockBytes = 16;
  89484. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  89485. break;
  89486. case FOURCC_D3DFMT_R16G16B16A16F:
  89487. computeFormats = true;
  89488. break;
  89489. case FOURCC_D3DFMT_R32G32B32A32F:
  89490. computeFormats = true;
  89491. break;
  89492. case FOURCC_DX10:
  89493. // There is an additionnal header so dataOffset need to be changed
  89494. dataOffset += 5 * 4; // 5 uints
  89495. var supported = false;
  89496. switch (info.dxgiFormat) {
  89497. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  89498. computeFormats = true;
  89499. supported = true;
  89500. break;
  89501. case DXGI_FORMAT_B8G8R8X8_UNORM:
  89502. info.isRGB = true;
  89503. info.isFourCC = false;
  89504. bpp = 32;
  89505. supported = true;
  89506. break;
  89507. }
  89508. if (supported) {
  89509. break;
  89510. }
  89511. default:
  89512. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  89513. return;
  89514. }
  89515. }
  89516. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  89517. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  89518. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  89519. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  89520. if (computeFormats) {
  89521. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  89522. }
  89523. mipmapCount = 1;
  89524. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  89525. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89526. }
  89527. for (var face = 0; face < faces; face++) {
  89528. width = header[off_width];
  89529. height = header[off_height];
  89530. for (mip = 0; mip < mipmapCount; ++mip) {
  89531. if (lodIndex === -1 || lodIndex === mip) {
  89532. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  89533. var i = (lodIndex === -1) ? mip : 0;
  89534. if (!info.isCompressed && info.isFourCC) {
  89535. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89536. dataLength = width * height * 4;
  89537. var floatArray = null;
  89538. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  89539. if (bpp === 128) {
  89540. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89541. if (sphericalPolynomialFaces && i == 0) {
  89542. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89543. }
  89544. }
  89545. else if (bpp === 64) {
  89546. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89547. if (sphericalPolynomialFaces && i == 0) {
  89548. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89549. }
  89550. }
  89551. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89552. }
  89553. else {
  89554. if (bpp === 128) {
  89555. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89556. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89557. if (sphericalPolynomialFaces && i == 0) {
  89558. sphericalPolynomialFaces.push(floatArray);
  89559. }
  89560. }
  89561. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  89562. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89563. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89564. if (sphericalPolynomialFaces && i == 0) {
  89565. sphericalPolynomialFaces.push(floatArray);
  89566. }
  89567. }
  89568. else { // 64
  89569. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89570. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89571. if (sphericalPolynomialFaces && i == 0) {
  89572. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89573. }
  89574. }
  89575. }
  89576. if (floatArray) {
  89577. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  89578. }
  89579. }
  89580. else if (info.isRGB) {
  89581. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89582. if (bpp === 24) {
  89583. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  89584. dataLength = width * height * 3;
  89585. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  89586. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89587. }
  89588. else { // 32
  89589. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89590. dataLength = width * height * 4;
  89591. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  89592. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89593. }
  89594. }
  89595. else if (info.isLuminance) {
  89596. var unpackAlignment = engine._getUnpackAlignement();
  89597. var unpaddedRowSize = width;
  89598. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  89599. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  89600. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  89601. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  89602. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89603. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89604. }
  89605. else {
  89606. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  89607. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  89608. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89609. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  89610. }
  89611. }
  89612. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  89613. width *= 0.5;
  89614. height *= 0.5;
  89615. width = Math.max(1.0, width);
  89616. height = Math.max(1.0, height);
  89617. }
  89618. if (currentFace !== undefined) {
  89619. // Loading a single face
  89620. break;
  89621. }
  89622. }
  89623. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  89624. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  89625. size: header[off_width],
  89626. right: sphericalPolynomialFaces[0],
  89627. left: sphericalPolynomialFaces[1],
  89628. up: sphericalPolynomialFaces[2],
  89629. down: sphericalPolynomialFaces[3],
  89630. front: sphericalPolynomialFaces[4],
  89631. back: sphericalPolynomialFaces[5],
  89632. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  89633. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89634. gammaSpace: false,
  89635. });
  89636. }
  89637. else {
  89638. info.sphericalPolynomial = undefined;
  89639. }
  89640. };
  89641. DDSTools.StoreLODInAlphaChannel = false;
  89642. return DDSTools;
  89643. }());
  89644. BABYLON.DDSTools = DDSTools;
  89645. })(BABYLON || (BABYLON = {}));
  89646. //# sourceMappingURL=babylon.dds.js.map
  89647. var BABYLON;
  89648. (function (BABYLON) {
  89649. /**
  89650. * Implementation of the DDS Texture Loader.
  89651. */
  89652. var DDSTextureLoader = /** @class */ (function () {
  89653. function DDSTextureLoader() {
  89654. /**
  89655. * Defines wether the loader supports cascade loading the different faces.
  89656. */
  89657. this.supportCascades = true;
  89658. }
  89659. /**
  89660. * This returns if the loader support the current file information.
  89661. * @param extension defines the file extension of the file being loaded
  89662. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89663. * @param fallback defines the fallback internal texture if any
  89664. * @param isBase64 defines whether the texture is encoded as a base64
  89665. * @param isBuffer defines whether the texture data are stored as a buffer
  89666. * @returns true if the loader can load the specified file
  89667. */
  89668. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89669. return extension.indexOf(".dds") === 0;
  89670. };
  89671. /**
  89672. * Transform the url before loading if required.
  89673. * @param rootUrl the url of the texture
  89674. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89675. * @returns the transformed texture
  89676. */
  89677. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89678. return rootUrl;
  89679. };
  89680. /**
  89681. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89682. * @param rootUrl the url of the texture
  89683. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89684. * @returns the fallback texture
  89685. */
  89686. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89687. return null;
  89688. };
  89689. /**
  89690. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89691. * @param data contains the texture data
  89692. * @param texture defines the BabylonJS internal texture
  89693. * @param createPolynomials will be true if polynomials have been requested
  89694. * @param onLoad defines the callback to trigger once the texture is ready
  89695. * @param onError defines the callback to trigger in case of error
  89696. */
  89697. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  89698. var engine = texture.getEngine();
  89699. var info;
  89700. var loadMipmap = false;
  89701. if (Array.isArray(imgs)) {
  89702. for (var index = 0; index < imgs.length; index++) {
  89703. var data_1 = imgs[index];
  89704. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  89705. texture.width = info.width;
  89706. texture.height = info.height;
  89707. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89708. engine._unpackFlipY(info.isCompressed);
  89709. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  89710. if (!info.isFourCC && info.mipmapCount === 1) {
  89711. engine.generateMipMapsForCubemap(texture);
  89712. }
  89713. }
  89714. }
  89715. else {
  89716. var data = imgs;
  89717. info = BABYLON.DDSTools.GetDDSInfo(data);
  89718. texture.width = info.width;
  89719. texture.height = info.height;
  89720. if (createPolynomials) {
  89721. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  89722. }
  89723. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89724. engine._unpackFlipY(info.isCompressed);
  89725. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  89726. if (!info.isFourCC && info.mipmapCount === 1) {
  89727. engine.generateMipMapsForCubemap(texture);
  89728. }
  89729. }
  89730. engine._setCubeMapTextureParams(loadMipmap);
  89731. texture.isReady = true;
  89732. if (onLoad) {
  89733. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  89734. }
  89735. };
  89736. /**
  89737. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89738. * @param data contains the texture data
  89739. * @param texture defines the BabylonJS internal texture
  89740. * @param callback defines the method to call once ready to upload
  89741. */
  89742. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  89743. var info = BABYLON.DDSTools.GetDDSInfo(data);
  89744. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  89745. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  89746. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  89747. });
  89748. };
  89749. return DDSTextureLoader;
  89750. }());
  89751. // Register the loader.
  89752. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  89753. })(BABYLON || (BABYLON = {}));
  89754. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  89755. var BABYLON;
  89756. (function (BABYLON) {
  89757. /*
  89758. * Based on jsTGALoader - Javascript loader for TGA file
  89759. * By Vincent Thibault
  89760. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  89761. */
  89762. var TGATools = /** @class */ (function () {
  89763. function TGATools() {
  89764. }
  89765. TGATools.GetTGAHeader = function (data) {
  89766. var offset = 0;
  89767. var header = {
  89768. id_length: data[offset++],
  89769. colormap_type: data[offset++],
  89770. image_type: data[offset++],
  89771. colormap_index: data[offset++] | data[offset++] << 8,
  89772. colormap_length: data[offset++] | data[offset++] << 8,
  89773. colormap_size: data[offset++],
  89774. origin: [
  89775. data[offset++] | data[offset++] << 8,
  89776. data[offset++] | data[offset++] << 8
  89777. ],
  89778. width: data[offset++] | data[offset++] << 8,
  89779. height: data[offset++] | data[offset++] << 8,
  89780. pixel_size: data[offset++],
  89781. flags: data[offset++]
  89782. };
  89783. return header;
  89784. };
  89785. /**
  89786. * Uploads TGA content to a Babylon Texture
  89787. * @hidden
  89788. */
  89789. TGATools.UploadContent = function (texture, data) {
  89790. // Not enough data to contain header ?
  89791. if (data.length < 19) {
  89792. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  89793. return;
  89794. }
  89795. // Read Header
  89796. var offset = 18;
  89797. var header = TGATools.GetTGAHeader(data);
  89798. // Assume it's a valid Targa file.
  89799. if (header.id_length + offset > data.length) {
  89800. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  89801. return;
  89802. }
  89803. // Skip not needed data
  89804. offset += header.id_length;
  89805. var use_rle = false;
  89806. var use_pal = false;
  89807. var use_grey = false;
  89808. // Get some informations.
  89809. switch (header.image_type) {
  89810. case TGATools._TYPE_RLE_INDEXED:
  89811. use_rle = true;
  89812. case TGATools._TYPE_INDEXED:
  89813. use_pal = true;
  89814. break;
  89815. case TGATools._TYPE_RLE_RGB:
  89816. use_rle = true;
  89817. case TGATools._TYPE_RGB:
  89818. // use_rgb = true;
  89819. break;
  89820. case TGATools._TYPE_RLE_GREY:
  89821. use_rle = true;
  89822. case TGATools._TYPE_GREY:
  89823. use_grey = true;
  89824. break;
  89825. }
  89826. var pixel_data;
  89827. // var numAlphaBits = header.flags & 0xf;
  89828. var pixel_size = header.pixel_size >> 3;
  89829. var pixel_total = header.width * header.height * pixel_size;
  89830. // Read palettes
  89831. var palettes;
  89832. if (use_pal) {
  89833. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  89834. }
  89835. // Read LRE
  89836. if (use_rle) {
  89837. pixel_data = new Uint8Array(pixel_total);
  89838. var c, count, i;
  89839. var localOffset = 0;
  89840. var pixels = new Uint8Array(pixel_size);
  89841. while (offset < pixel_total && localOffset < pixel_total) {
  89842. c = data[offset++];
  89843. count = (c & 0x7f) + 1;
  89844. // RLE pixels
  89845. if (c & 0x80) {
  89846. // Bind pixel tmp array
  89847. for (i = 0; i < pixel_size; ++i) {
  89848. pixels[i] = data[offset++];
  89849. }
  89850. // Copy pixel array
  89851. for (i = 0; i < count; ++i) {
  89852. pixel_data.set(pixels, localOffset + i * pixel_size);
  89853. }
  89854. localOffset += pixel_size * count;
  89855. }
  89856. // Raw pixels
  89857. else {
  89858. count *= pixel_size;
  89859. for (i = 0; i < count; ++i) {
  89860. pixel_data[localOffset + i] = data[offset++];
  89861. }
  89862. localOffset += count;
  89863. }
  89864. }
  89865. }
  89866. // RAW Pixels
  89867. else {
  89868. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  89869. }
  89870. // Load to texture
  89871. var x_start, y_start, x_step, y_step, y_end, x_end;
  89872. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  89873. default:
  89874. case TGATools._ORIGIN_UL:
  89875. x_start = 0;
  89876. x_step = 1;
  89877. x_end = header.width;
  89878. y_start = 0;
  89879. y_step = 1;
  89880. y_end = header.height;
  89881. break;
  89882. case TGATools._ORIGIN_BL:
  89883. x_start = 0;
  89884. x_step = 1;
  89885. x_end = header.width;
  89886. y_start = header.height - 1;
  89887. y_step = -1;
  89888. y_end = -1;
  89889. break;
  89890. case TGATools._ORIGIN_UR:
  89891. x_start = header.width - 1;
  89892. x_step = -1;
  89893. x_end = -1;
  89894. y_start = 0;
  89895. y_step = 1;
  89896. y_end = header.height;
  89897. break;
  89898. case TGATools._ORIGIN_BR:
  89899. x_start = header.width - 1;
  89900. x_step = -1;
  89901. x_end = -1;
  89902. y_start = header.height - 1;
  89903. y_step = -1;
  89904. y_end = -1;
  89905. break;
  89906. }
  89907. // Load the specify method
  89908. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  89909. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  89910. var engine = texture.getEngine();
  89911. engine._uploadDataToTextureDirectly(texture, imageData);
  89912. };
  89913. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89914. var image = pixel_data, colormap = palettes;
  89915. var width = header.width, height = header.height;
  89916. var color, i = 0, x, y;
  89917. var imageData = new Uint8Array(width * height * 4);
  89918. for (y = y_start; y !== y_end; y += y_step) {
  89919. for (x = x_start; x !== x_end; x += x_step, i++) {
  89920. color = image[i];
  89921. imageData[(x + width * y) * 4 + 3] = 255;
  89922. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  89923. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  89924. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  89925. }
  89926. }
  89927. return imageData;
  89928. };
  89929. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89930. var image = pixel_data;
  89931. var width = header.width, height = header.height;
  89932. var color, i = 0, x, y;
  89933. var imageData = new Uint8Array(width * height * 4);
  89934. for (y = y_start; y !== y_end; y += y_step) {
  89935. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89936. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  89937. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  89938. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  89939. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  89940. imageData[(x + width * y) * 4 + 0] = r;
  89941. imageData[(x + width * y) * 4 + 1] = g;
  89942. imageData[(x + width * y) * 4 + 2] = b;
  89943. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  89944. }
  89945. }
  89946. return imageData;
  89947. };
  89948. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89949. var image = pixel_data;
  89950. var width = header.width, height = header.height;
  89951. var i = 0, x, y;
  89952. var imageData = new Uint8Array(width * height * 4);
  89953. for (y = y_start; y !== y_end; y += y_step) {
  89954. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  89955. imageData[(x + width * y) * 4 + 3] = 255;
  89956. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89957. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89958. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89959. }
  89960. }
  89961. return imageData;
  89962. };
  89963. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89964. var image = pixel_data;
  89965. var width = header.width, height = header.height;
  89966. var i = 0, x, y;
  89967. var imageData = new Uint8Array(width * height * 4);
  89968. for (y = y_start; y !== y_end; y += y_step) {
  89969. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  89970. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89971. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89972. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89973. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  89974. }
  89975. }
  89976. return imageData;
  89977. };
  89978. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89979. var image = pixel_data;
  89980. var width = header.width, height = header.height;
  89981. var color, i = 0, x, y;
  89982. var imageData = new Uint8Array(width * height * 4);
  89983. for (y = y_start; y !== y_end; y += y_step) {
  89984. for (x = x_start; x !== x_end; x += x_step, i++) {
  89985. color = image[i];
  89986. imageData[(x + width * y) * 4 + 0] = color;
  89987. imageData[(x + width * y) * 4 + 1] = color;
  89988. imageData[(x + width * y) * 4 + 2] = color;
  89989. imageData[(x + width * y) * 4 + 3] = 255;
  89990. }
  89991. }
  89992. return imageData;
  89993. };
  89994. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89995. var image = pixel_data;
  89996. var width = header.width, height = header.height;
  89997. var i = 0, x, y;
  89998. var imageData = new Uint8Array(width * height * 4);
  89999. for (y = y_start; y !== y_end; y += y_step) {
  90000. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90001. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  90002. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  90003. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90004. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  90005. }
  90006. }
  90007. return imageData;
  90008. };
  90009. //private static _TYPE_NO_DATA = 0;
  90010. TGATools._TYPE_INDEXED = 1;
  90011. TGATools._TYPE_RGB = 2;
  90012. TGATools._TYPE_GREY = 3;
  90013. TGATools._TYPE_RLE_INDEXED = 9;
  90014. TGATools._TYPE_RLE_RGB = 10;
  90015. TGATools._TYPE_RLE_GREY = 11;
  90016. TGATools._ORIGIN_MASK = 0x30;
  90017. TGATools._ORIGIN_SHIFT = 0x04;
  90018. TGATools._ORIGIN_BL = 0x00;
  90019. TGATools._ORIGIN_BR = 0x01;
  90020. TGATools._ORIGIN_UL = 0x02;
  90021. TGATools._ORIGIN_UR = 0x03;
  90022. return TGATools;
  90023. }());
  90024. BABYLON.TGATools = TGATools;
  90025. })(BABYLON || (BABYLON = {}));
  90026. //# sourceMappingURL=babylon.tga.js.map
  90027. var BABYLON;
  90028. (function (BABYLON) {
  90029. /**
  90030. * Implementation of the TGA Texture Loader.
  90031. */
  90032. var TGATextureLoader = /** @class */ (function () {
  90033. function TGATextureLoader() {
  90034. /**
  90035. * Defines wether the loader supports cascade loading the different faces.
  90036. */
  90037. this.supportCascades = false;
  90038. }
  90039. /**
  90040. * This returns if the loader support the current file information.
  90041. * @param extension defines the file extension of the file being loaded
  90042. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90043. * @param fallback defines the fallback internal texture if any
  90044. * @param isBase64 defines whether the texture is encoded as a base64
  90045. * @param isBuffer defines whether the texture data are stored as a buffer
  90046. * @returns true if the loader can load the specified file
  90047. */
  90048. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90049. return extension.indexOf(".tga") === 0;
  90050. };
  90051. /**
  90052. * Transform the url before loading if required.
  90053. * @param rootUrl the url of the texture
  90054. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90055. * @returns the transformed texture
  90056. */
  90057. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90058. return rootUrl;
  90059. };
  90060. /**
  90061. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90062. * @param rootUrl the url of the texture
  90063. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90064. * @returns the fallback texture
  90065. */
  90066. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90067. return null;
  90068. };
  90069. /**
  90070. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90071. * @param data contains the texture data
  90072. * @param texture defines the BabylonJS internal texture
  90073. * @param createPolynomials will be true if polynomials have been requested
  90074. * @param onLoad defines the callback to trigger once the texture is ready
  90075. * @param onError defines the callback to trigger in case of error
  90076. */
  90077. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90078. throw ".env not supported in Cube.";
  90079. };
  90080. /**
  90081. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90082. * @param data contains the texture data
  90083. * @param texture defines the BabylonJS internal texture
  90084. * @param callback defines the method to call once ready to upload
  90085. */
  90086. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  90087. var uintData = new Uint8Array(data);
  90088. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  90089. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  90090. BABYLON.TGATools.UploadContent(texture, uintData);
  90091. });
  90092. };
  90093. return TGATextureLoader;
  90094. }());
  90095. // Register the loader.
  90096. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  90097. })(BABYLON || (BABYLON = {}));
  90098. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  90099. var BABYLON;
  90100. (function (BABYLON) {
  90101. /**
  90102. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  90103. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  90104. */
  90105. var KhronosTextureContainer = /** @class */ (function () {
  90106. /**
  90107. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  90108. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  90109. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  90110. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  90111. */
  90112. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  90113. this.arrayBuffer = arrayBuffer;
  90114. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  90115. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  90116. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  90117. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  90118. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  90119. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  90120. BABYLON.Tools.Error("texture missing KTX identifier");
  90121. return;
  90122. }
  90123. // load the reset of the header in native 32 bit int
  90124. var header = new Int32Array(this.arrayBuffer, 12, 13);
  90125. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  90126. var oppositeEndianess = header[0] === 0x01020304;
  90127. // read all the header elements in order they exist in the file, without modification (sans endainness)
  90128. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  90129. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  90130. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  90131. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  90132. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  90133. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  90134. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  90135. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  90136. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  90137. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  90138. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  90139. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  90140. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  90141. if (this.glType !== 0) {
  90142. BABYLON.Tools.Error("only compressed formats currently supported");
  90143. return;
  90144. }
  90145. else {
  90146. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  90147. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  90148. }
  90149. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  90150. BABYLON.Tools.Error("only 2D textures currently supported");
  90151. return;
  90152. }
  90153. if (this.numberOfArrayElements !== 0) {
  90154. BABYLON.Tools.Error("texture arrays not currently supported");
  90155. return;
  90156. }
  90157. if (this.numberOfFaces !== facesExpected) {
  90158. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  90159. return;
  90160. }
  90161. // we now have a completely validated file, so could use existence of loadType as success
  90162. // would need to make this more elaborate & adjust checks above to support more than one load type
  90163. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  90164. }
  90165. // not as fast hardware based, but will probably never need to use
  90166. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  90167. return ((val & 0xFF) << 24)
  90168. | ((val & 0xFF00) << 8)
  90169. | ((val >> 8) & 0xFF00)
  90170. | ((val >> 24) & 0xFF);
  90171. };
  90172. /**
  90173. * Uploads KTX content to a Babylon Texture.
  90174. * It is assumed that the texture has already been created & is currently bound
  90175. * @hidden
  90176. */
  90177. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  90178. switch (this.loadType) {
  90179. case KhronosTextureContainer.COMPRESSED_2D:
  90180. this._upload2DCompressedLevels(texture, loadMipmaps);
  90181. break;
  90182. case KhronosTextureContainer.TEX_2D:
  90183. case KhronosTextureContainer.COMPRESSED_3D:
  90184. case KhronosTextureContainer.TEX_3D:
  90185. }
  90186. };
  90187. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  90188. // initialize width & height for level 1
  90189. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  90190. var width = this.pixelWidth;
  90191. var height = this.pixelHeight;
  90192. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  90193. for (var level = 0; level < mipmapCount; level++) {
  90194. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  90195. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  90196. for (var face = 0; face < this.numberOfFaces; face++) {
  90197. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  90198. var engine = texture.getEngine();
  90199. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  90200. dataOffset += imageSize; // add size of the image for the next face/mipmap
  90201. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  90202. }
  90203. width = Math.max(1.0, width * 0.5);
  90204. height = Math.max(1.0, height * 0.5);
  90205. }
  90206. };
  90207. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  90208. // load types
  90209. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  90210. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  90211. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  90212. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  90213. return KhronosTextureContainer;
  90214. }());
  90215. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  90216. })(BABYLON || (BABYLON = {}));
  90217. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  90218. var BABYLON;
  90219. (function (BABYLON) {
  90220. /**
  90221. * Implementation of the KTX Texture Loader.
  90222. */
  90223. var KTXTextureLoader = /** @class */ (function () {
  90224. function KTXTextureLoader() {
  90225. /**
  90226. * Defines wether the loader supports cascade loading the different faces.
  90227. */
  90228. this.supportCascades = false;
  90229. }
  90230. /**
  90231. * This returns if the loader support the current file information.
  90232. * @param extension defines the file extension of the file being loaded
  90233. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90234. * @param fallback defines the fallback internal texture if any
  90235. * @param isBase64 defines whether the texture is encoded as a base64
  90236. * @param isBuffer defines whether the texture data are stored as a buffer
  90237. * @returns true if the loader can load the specified file
  90238. */
  90239. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90240. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  90241. return true;
  90242. }
  90243. return false;
  90244. };
  90245. /**
  90246. * Transform the url before loading if required.
  90247. * @param rootUrl the url of the texture
  90248. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90249. * @returns the transformed texture
  90250. */
  90251. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90252. var lastDot = rootUrl.lastIndexOf('.');
  90253. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  90254. };
  90255. /**
  90256. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90257. * @param rootUrl the url of the texture
  90258. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90259. * @returns the fallback texture
  90260. */
  90261. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90262. // remove the format appended to the rootUrl in the original createCubeTexture call.
  90263. var exp = new RegExp("" + textureFormatInUse + "$");
  90264. return rootUrl.replace(exp, "");
  90265. };
  90266. /**
  90267. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90268. * @param data contains the texture data
  90269. * @param texture defines the BabylonJS internal texture
  90270. * @param createPolynomials will be true if polynomials have been requested
  90271. * @param onLoad defines the callback to trigger once the texture is ready
  90272. * @param onError defines the callback to trigger in case of error
  90273. */
  90274. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90275. if (Array.isArray(data)) {
  90276. return;
  90277. }
  90278. var engine = texture.getEngine();
  90279. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  90280. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  90281. engine._unpackFlipY(true);
  90282. ktx.uploadLevels(texture, texture.generateMipMaps);
  90283. texture.width = ktx.pixelWidth;
  90284. texture.height = ktx.pixelHeight;
  90285. engine._setCubeMapTextureParams(loadMipmap);
  90286. texture.isReady = true;
  90287. };
  90288. /**
  90289. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90290. * @param data contains the texture data
  90291. * @param texture defines the BabylonJS internal texture
  90292. * @param callback defines the method to call once ready to upload
  90293. */
  90294. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  90295. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  90296. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  90297. ktx.uploadLevels(texture, texture.generateMipMaps);
  90298. });
  90299. };
  90300. return KTXTextureLoader;
  90301. }());
  90302. // Register the loader.
  90303. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  90304. })(BABYLON || (BABYLON = {}));
  90305. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  90306. var BABYLON;
  90307. (function (BABYLON) {
  90308. /**
  90309. * Sets of helpers addressing the serialization and deserialization of environment texture
  90310. * stored in a BabylonJS env file.
  90311. * Those files are usually stored as .env files.
  90312. */
  90313. var EnvironmentTextureTools = /** @class */ (function () {
  90314. function EnvironmentTextureTools() {
  90315. }
  90316. /**
  90317. * Gets the environment info from an env file.
  90318. * @param data The array buffer containing the .env bytes.
  90319. * @returns the environment file info (the json header) if successfully parsed.
  90320. */
  90321. EnvironmentTextureTools.GetEnvInfo = function (data) {
  90322. var dataView = new DataView(data);
  90323. var pos = 0;
  90324. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90325. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  90326. BABYLON.Tools.Error('Not a babylon environment map');
  90327. return null;
  90328. }
  90329. }
  90330. // Read json manifest - collect characters up to null terminator
  90331. var manifestString = '';
  90332. var charCode = 0x00;
  90333. while ((charCode = dataView.getUint8(pos++))) {
  90334. manifestString += String.fromCharCode(charCode);
  90335. }
  90336. var manifest = JSON.parse(manifestString);
  90337. if (manifest.specular) {
  90338. // Extend the header with the position of the payload.
  90339. manifest.specular.specularDataPosition = pos;
  90340. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  90341. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  90342. }
  90343. return manifest;
  90344. };
  90345. /**
  90346. * Creates an environment texture from a loaded cube texture.
  90347. * @param texture defines the cube texture to convert in env file
  90348. * @return a promise containing the environment data if succesfull.
  90349. */
  90350. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  90351. var _this = this;
  90352. var internalTexture = texture.getInternalTexture();
  90353. if (!internalTexture) {
  90354. return Promise.reject("The cube texture is invalid.");
  90355. }
  90356. if (!texture._prefiltered) {
  90357. return Promise.reject("The cube texture is invalid (not prefiltered).");
  90358. }
  90359. var engine = internalTexture.getEngine();
  90360. if (engine && engine.premultipliedAlpha) {
  90361. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  90362. }
  90363. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  90364. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  90365. }
  90366. var canvas = engine.getRenderingCanvas();
  90367. if (!canvas) {
  90368. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  90369. }
  90370. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90371. if (!engine.getCaps().textureFloatRender) {
  90372. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90373. if (!engine.getCaps().textureHalfFloatRender) {
  90374. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  90375. }
  90376. }
  90377. var cubeWidth = internalTexture.width;
  90378. var hostingScene = new BABYLON.Scene(engine);
  90379. var specularTextures = {};
  90380. var promises = [];
  90381. // Read and collect all mipmaps data from the cube.
  90382. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  90383. mipmapsCount = Math.round(mipmapsCount);
  90384. var _loop_1 = function (i) {
  90385. var faceWidth = Math.pow(2, mipmapsCount - i);
  90386. var _loop_2 = function (face) {
  90387. var data = texture.readPixels(face, i);
  90388. // Creates a temp texture with the face data.
  90389. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  90390. // And rgbdEncode them.
  90391. var promise = new Promise(function (resolve, reject) {
  90392. 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);
  90393. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90394. rgbdPostProcess.onApply = function (effect) {
  90395. effect._bindTexture("textureSampler", tempTexture);
  90396. };
  90397. // As the process needs to happen on the main canvas, keep track of the current size
  90398. var currentW = engine.getRenderWidth();
  90399. var currentH = engine.getRenderHeight();
  90400. // Set the desired size for the texture
  90401. engine.setSize(faceWidth, faceWidth);
  90402. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  90403. // Reading datas from WebGL
  90404. BABYLON.Tools.ToBlob(canvas, function (blob) {
  90405. var fileReader = new FileReader();
  90406. fileReader.onload = function (event) {
  90407. var arrayBuffer = event.target.result;
  90408. specularTextures[i * 6 + face] = arrayBuffer;
  90409. resolve();
  90410. };
  90411. fileReader.readAsArrayBuffer(blob);
  90412. });
  90413. // Reapply the previous canvas size
  90414. engine.setSize(currentW, currentH);
  90415. });
  90416. });
  90417. promises.push(promise);
  90418. };
  90419. // All faces of the cube.
  90420. for (var face = 0; face < 6; face++) {
  90421. _loop_2(face);
  90422. }
  90423. };
  90424. for (var i = 0; i <= mipmapsCount; i++) {
  90425. _loop_1(i);
  90426. }
  90427. // Once all the textures haves been collected as RGBD stored in PNGs
  90428. return Promise.all(promises).then(function () {
  90429. // We can delete the hosting scene keeping track of all the creation objects
  90430. hostingScene.dispose();
  90431. // Creates the json header for the env texture
  90432. var info = {
  90433. version: 1,
  90434. width: cubeWidth,
  90435. irradiance: _this._CreateEnvTextureIrradiance(texture),
  90436. specular: {
  90437. mipmaps: [],
  90438. lodGenerationScale: texture.lodGenerationScale
  90439. }
  90440. };
  90441. // Sets the specular image data information
  90442. var position = 0;
  90443. for (var i = 0; i <= mipmapsCount; i++) {
  90444. for (var face = 0; face < 6; face++) {
  90445. var byteLength = specularTextures[i * 6 + face].byteLength;
  90446. info.specular.mipmaps.push({
  90447. length: byteLength,
  90448. position: position
  90449. });
  90450. position += byteLength;
  90451. }
  90452. }
  90453. // Encode the JSON as an array buffer
  90454. var infoString = JSON.stringify(info);
  90455. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  90456. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  90457. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  90458. infoView[i] = infoString.charCodeAt(i);
  90459. }
  90460. // Ends up with a null terminator for easier parsing
  90461. infoView[infoString.length] = 0x00;
  90462. // Computes the final required size and creates the storage
  90463. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  90464. var finalBuffer = new ArrayBuffer(totalSize);
  90465. var finalBufferView = new Uint8Array(finalBuffer);
  90466. var dataView = new DataView(finalBuffer);
  90467. // Copy the magic bytes identifying the file in
  90468. var pos = 0;
  90469. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90470. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  90471. }
  90472. // Add the json info
  90473. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  90474. pos += infoBuffer.byteLength;
  90475. // Finally inserts the texture data
  90476. for (var i = 0; i <= mipmapsCount; i++) {
  90477. for (var face = 0; face < 6; face++) {
  90478. var dataBuffer = specularTextures[i * 6 + face];
  90479. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  90480. pos += dataBuffer.byteLength;
  90481. }
  90482. }
  90483. // Voila
  90484. return finalBuffer;
  90485. });
  90486. };
  90487. /**
  90488. * Creates a JSON representation of the spherical data.
  90489. * @param texture defines the texture containing the polynomials
  90490. * @return the JSON representation of the spherical info
  90491. */
  90492. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  90493. var polynmials = texture.sphericalPolynomial;
  90494. if (polynmials == null) {
  90495. return null;
  90496. }
  90497. return {
  90498. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  90499. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  90500. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  90501. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  90502. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  90503. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  90504. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  90505. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  90506. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  90507. };
  90508. };
  90509. /**
  90510. * Uploads the texture info contained in the env file to the GPU.
  90511. * @param texture defines the internal texture to upload to
  90512. * @param arrayBuffer defines the buffer cotaining the data to load
  90513. * @param info defines the texture info retrieved through the GetEnvInfo method
  90514. * @returns a promise
  90515. */
  90516. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  90517. if (info.version !== 1) {
  90518. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  90519. }
  90520. var specularInfo = info.specular;
  90521. if (!specularInfo) {
  90522. // Nothing else parsed so far
  90523. return Promise.resolve();
  90524. }
  90525. // Double checks the enclosed info
  90526. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  90527. mipmapsCount = Math.round(mipmapsCount) + 1;
  90528. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  90529. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  90530. }
  90531. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  90532. var imageData = new Array(mipmapsCount);
  90533. for (var i = 0; i < mipmapsCount; i++) {
  90534. imageData[i] = new Array(6);
  90535. for (var face = 0; face < 6; face++) {
  90536. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  90537. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  90538. }
  90539. }
  90540. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  90541. };
  90542. /**
  90543. * Uploads the levels of image data to the GPU.
  90544. * @param texture defines the internal texture to upload to
  90545. * @param imageData defines the array buffer views of image data [mipmap][face]
  90546. * @returns a promise
  90547. */
  90548. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  90549. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  90550. throw new Error("Texture size must be a power of two");
  90551. }
  90552. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  90553. // Gets everything ready.
  90554. var engine = texture.getEngine();
  90555. var expandTexture = false;
  90556. var generateNonLODTextures = false;
  90557. var rgbdPostProcess = null;
  90558. var cubeRtt = null;
  90559. var lodTextures = null;
  90560. var caps = engine.getCaps();
  90561. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90562. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90563. texture.generateMipMaps = true;
  90564. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  90565. // Add extra process if texture lod is not supported
  90566. if (!caps.textureLOD) {
  90567. expandTexture = false;
  90568. generateNonLODTextures = true;
  90569. lodTextures = {};
  90570. }
  90571. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  90572. else if (engine.webGLVersion < 2) {
  90573. expandTexture = false;
  90574. }
  90575. // If half float available we can uncompress the texture
  90576. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  90577. expandTexture = true;
  90578. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90579. }
  90580. // If full float available we can uncompress the texture
  90581. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  90582. expandTexture = true;
  90583. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90584. }
  90585. // Expand the texture if possible
  90586. if (expandTexture) {
  90587. // Simply run through the decode PP
  90588. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  90589. texture._isRGBD = false;
  90590. texture.invertY = false;
  90591. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  90592. generateDepthBuffer: false,
  90593. generateMipMaps: true,
  90594. generateStencilBuffer: false,
  90595. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  90596. type: texture.type,
  90597. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  90598. });
  90599. }
  90600. else {
  90601. texture._isRGBD = true;
  90602. texture.invertY = true;
  90603. // In case of missing support, applies the same patch than DDS files.
  90604. if (generateNonLODTextures) {
  90605. var mipSlices = 3;
  90606. var scale = texture._lodGenerationScale;
  90607. var offset = texture._lodGenerationOffset;
  90608. for (var i = 0; i < mipSlices; i++) {
  90609. //compute LOD from even spacing in smoothness (matching shader calculation)
  90610. var smoothness = i / (mipSlices - 1);
  90611. var roughness = 1 - smoothness;
  90612. var minLODIndex = offset; // roughness = 0
  90613. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  90614. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  90615. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  90616. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  90617. glTextureFromLod.isCube = true;
  90618. glTextureFromLod.invertY = true;
  90619. glTextureFromLod.generateMipMaps = false;
  90620. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  90621. // Wrap in a base texture for easy binding.
  90622. var lodTexture = new BABYLON.BaseTexture(null);
  90623. lodTexture.isCube = true;
  90624. lodTexture._texture = glTextureFromLod;
  90625. lodTextures[mipmapIndex] = lodTexture;
  90626. switch (i) {
  90627. case 0:
  90628. texture._lodTextureLow = lodTexture;
  90629. break;
  90630. case 1:
  90631. texture._lodTextureMid = lodTexture;
  90632. break;
  90633. case 2:
  90634. texture._lodTextureHigh = lodTexture;
  90635. break;
  90636. }
  90637. }
  90638. }
  90639. }
  90640. var promises = [];
  90641. var _loop_3 = function (i) {
  90642. var _loop_4 = function (face) {
  90643. // Constructs an image element from image data
  90644. var bytes = imageData[i][face];
  90645. var blob = new Blob([bytes], { type: 'image/png' });
  90646. var url = URL.createObjectURL(blob);
  90647. var image = new Image();
  90648. image.src = url;
  90649. // Enqueue promise to upload to the texture.
  90650. var promise = new Promise(function (resolve, reject) {
  90651. image.onload = function () {
  90652. if (expandTexture) {
  90653. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  90654. reject(message);
  90655. }, image);
  90656. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90657. // Uncompress the data to a RTT
  90658. rgbdPostProcess.onApply = function (effect) {
  90659. effect._bindTexture("textureSampler", tempTexture_1);
  90660. effect.setFloat2("scale", 1, 1);
  90661. };
  90662. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  90663. // Cleanup
  90664. engine.restoreDefaultFramebuffer();
  90665. tempTexture_1.dispose();
  90666. window.URL.revokeObjectURL(url);
  90667. resolve();
  90668. });
  90669. }
  90670. else {
  90671. engine._uploadImageToTexture(texture, image, face, i);
  90672. // Upload the face to the non lod texture support
  90673. if (generateNonLODTextures) {
  90674. var lodTexture = lodTextures[i];
  90675. if (lodTexture) {
  90676. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  90677. }
  90678. }
  90679. resolve();
  90680. }
  90681. };
  90682. image.onerror = function (error) {
  90683. reject(error);
  90684. };
  90685. });
  90686. promises.push(promise);
  90687. };
  90688. // All faces
  90689. for (var face = 0; face < 6; face++) {
  90690. _loop_4(face);
  90691. }
  90692. };
  90693. // All mipmaps up to provided number of images
  90694. for (var i = 0; i < imageData.length; i++) {
  90695. _loop_3(i);
  90696. }
  90697. // Fill remaining mipmaps with black textures.
  90698. if (imageData.length < mipmapsCount) {
  90699. var data = void 0;
  90700. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  90701. var dataLength = size * size * 4;
  90702. switch (texture.type) {
  90703. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  90704. data = new Uint8Array(dataLength);
  90705. break;
  90706. }
  90707. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  90708. data = new Uint16Array(dataLength);
  90709. break;
  90710. }
  90711. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  90712. data = new Float32Array(dataLength);
  90713. break;
  90714. }
  90715. }
  90716. for (var i = imageData.length; i < mipmapsCount; i++) {
  90717. for (var face = 0; face < 6; face++) {
  90718. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  90719. }
  90720. }
  90721. }
  90722. // Once all done, finishes the cleanup and return
  90723. return Promise.all(promises).then(function () {
  90724. // Release temp RTT.
  90725. if (cubeRtt) {
  90726. engine._releaseFramebufferObjects(cubeRtt);
  90727. cubeRtt._swapAndDie(texture);
  90728. }
  90729. // Release temp Post Process.
  90730. if (rgbdPostProcess) {
  90731. rgbdPostProcess.dispose();
  90732. }
  90733. // Flag internal texture as ready in case they are in use.
  90734. if (generateNonLODTextures) {
  90735. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  90736. texture._lodTextureHigh._texture.isReady = true;
  90737. }
  90738. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  90739. texture._lodTextureMid._texture.isReady = true;
  90740. }
  90741. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  90742. texture._lodTextureLow._texture.isReady = true;
  90743. }
  90744. }
  90745. });
  90746. };
  90747. /**
  90748. * Uploads spherical polynomials information to the texture.
  90749. * @param texture defines the texture we are trying to upload the information to
  90750. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  90751. */
  90752. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  90753. if (info.version !== 1) {
  90754. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  90755. }
  90756. var irradianceInfo = info.irradiance;
  90757. if (!irradianceInfo) {
  90758. return;
  90759. }
  90760. var sp = new BABYLON.SphericalPolynomial();
  90761. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  90762. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  90763. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  90764. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  90765. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  90766. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  90767. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  90768. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  90769. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  90770. texture._sphericalPolynomial = sp;
  90771. };
  90772. /**
  90773. * Magic number identifying the env file.
  90774. */
  90775. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  90776. return EnvironmentTextureTools;
  90777. }());
  90778. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  90779. })(BABYLON || (BABYLON = {}));
  90780. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  90781. var BABYLON;
  90782. (function (BABYLON) {
  90783. /**
  90784. * Implementation of the ENV Texture Loader.
  90785. */
  90786. var ENVTextureLoader = /** @class */ (function () {
  90787. function ENVTextureLoader() {
  90788. /**
  90789. * Defines wether the loader supports cascade loading the different faces.
  90790. */
  90791. this.supportCascades = false;
  90792. }
  90793. /**
  90794. * This returns if the loader support the current file information.
  90795. * @param extension defines the file extension of the file being loaded
  90796. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90797. * @param fallback defines the fallback internal texture if any
  90798. * @param isBase64 defines whether the texture is encoded as a base64
  90799. * @param isBuffer defines whether the texture data are stored as a buffer
  90800. * @returns true if the loader can load the specified file
  90801. */
  90802. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90803. return extension.indexOf(".env") === 0;
  90804. };
  90805. /**
  90806. * Transform the url before loading if required.
  90807. * @param rootUrl the url of the texture
  90808. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90809. * @returns the transformed texture
  90810. */
  90811. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90812. return rootUrl;
  90813. };
  90814. /**
  90815. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90816. * @param rootUrl the url of the texture
  90817. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90818. * @returns the fallback texture
  90819. */
  90820. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90821. return null;
  90822. };
  90823. /**
  90824. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90825. * @param data contains the texture data
  90826. * @param texture defines the BabylonJS internal texture
  90827. * @param createPolynomials will be true if polynomials have been requested
  90828. * @param onLoad defines the callback to trigger once the texture is ready
  90829. * @param onError defines the callback to trigger in case of error
  90830. */
  90831. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90832. if (Array.isArray(data)) {
  90833. return;
  90834. }
  90835. data = data;
  90836. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  90837. if (info) {
  90838. texture.width = info.width;
  90839. texture.height = info.width;
  90840. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  90841. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  90842. texture.isReady = true;
  90843. if (onLoad) {
  90844. onLoad();
  90845. }
  90846. });
  90847. }
  90848. else if (onError) {
  90849. onError("Can not parse the environment file", null);
  90850. }
  90851. };
  90852. /**
  90853. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90854. * @param data contains the texture data
  90855. * @param texture defines the BabylonJS internal texture
  90856. * @param callback defines the method to call once ready to upload
  90857. */
  90858. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  90859. throw ".env not supported in 2d.";
  90860. };
  90861. return ENVTextureLoader;
  90862. }());
  90863. // Register the loader.
  90864. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  90865. })(BABYLON || (BABYLON = {}));
  90866. //# sourceMappingURL=babylon.envTextureLoader.js.map
  90867. var BABYLON;
  90868. (function (BABYLON) {
  90869. /**
  90870. * Renders a layer on top of an existing scene
  90871. */
  90872. var UtilityLayerRenderer = /** @class */ (function () {
  90873. /**
  90874. * Instantiates a UtilityLayerRenderer
  90875. * @param originalScene the original scene that will be rendered on top of
  90876. */
  90877. function UtilityLayerRenderer(
  90878. /** the original scene that will be rendered on top of */
  90879. originalScene) {
  90880. var _this = this;
  90881. this.originalScene = originalScene;
  90882. this._pointerCaptures = {};
  90883. this._lastPointerEvents = {};
  90884. /**
  90885. * If the utility layer should automatically be rendered on top of existing scene
  90886. */
  90887. this.shouldRender = true;
  90888. /**
  90889. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  90890. */
  90891. this.onlyCheckPointerDownEvents = true;
  90892. /**
  90893. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  90894. */
  90895. this.processAllEvents = false;
  90896. /**
  90897. * Observable raised when the pointer move from the utility layer scene to the main scene
  90898. */
  90899. this.onPointerOutObservable = new BABYLON.Observable();
  90900. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  90901. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  90902. this.utilityLayerScene._allowPostProcessClear = false;
  90903. originalScene.getEngine().scenes.pop();
  90904. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  90905. this.utilityLayerScene.detachControl();
  90906. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  90907. if (!_this.processAllEvents) {
  90908. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  90909. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  90910. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  90911. return;
  90912. }
  90913. }
  90914. var pointerEvent = (prePointerInfo.event);
  90915. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  90916. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90917. return;
  90918. }
  90919. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  90920. if (!prePointerInfo.ray && utilityScenePick) {
  90921. prePointerInfo.ray = utilityScenePick.ray;
  90922. }
  90923. // always fire the prepointer oversvable
  90924. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  90925. // allow every non pointer down event to flow to the utility layer
  90926. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  90927. if (!prePointerInfo.skipOnPointerObservable) {
  90928. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90929. }
  90930. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  90931. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90932. }
  90933. return;
  90934. }
  90935. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  90936. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  90937. if (utilityScenePick && utilityScenePick.hit) {
  90938. if (!prePointerInfo.skipOnPointerObservable) {
  90939. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90940. }
  90941. prePointerInfo.skipOnPointerObservable = true;
  90942. }
  90943. }
  90944. else {
  90945. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  90946. var pointerEvent_1 = (prePointerInfo.event);
  90947. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  90948. if (originalScenePick && utilityScenePick) {
  90949. // No pick in utility scene
  90950. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  90951. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90952. // We touched an utility mesh present in the main scene
  90953. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90954. prePointerInfo.skipOnPointerObservable = true;
  90955. }
  90956. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90957. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  90958. }
  90959. }
  90960. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  90961. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  90962. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  90963. // If a previous utility layer set this, do not unset this
  90964. if (!prePointerInfo.skipOnPointerObservable) {
  90965. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  90966. }
  90967. }
  90968. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  90969. // We have a pick in both scenes but main is closer than utility
  90970. // We touched an utility mesh present in the main scene
  90971. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90972. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90973. prePointerInfo.skipOnPointerObservable = true;
  90974. }
  90975. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  90976. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  90977. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  90978. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  90979. }
  90980. }
  90981. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  90982. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  90983. }
  90984. }
  90985. }
  90986. });
  90987. // Render directly on top of existing scene without clearing
  90988. this.utilityLayerScene.autoClear = false;
  90989. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  90990. if (_this.shouldRender) {
  90991. _this.render();
  90992. }
  90993. });
  90994. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  90995. _this.dispose();
  90996. });
  90997. this._updateCamera();
  90998. }
  90999. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  91000. /**
  91001. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  91002. */
  91003. get: function () {
  91004. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  91005. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91006. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91007. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91008. });
  91009. }
  91010. return UtilityLayerRenderer._DefaultUtilityLayer;
  91011. },
  91012. enumerable: true,
  91013. configurable: true
  91014. });
  91015. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  91016. /**
  91017. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  91018. */
  91019. get: function () {
  91020. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  91021. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91022. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  91023. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91024. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91025. });
  91026. }
  91027. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  91028. },
  91029. enumerable: true,
  91030. configurable: true
  91031. });
  91032. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  91033. if (!prePointerInfo.skipOnPointerObservable) {
  91034. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  91035. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  91036. }
  91037. };
  91038. /**
  91039. * Renders the utility layers scene on top of the original scene
  91040. */
  91041. UtilityLayerRenderer.prototype.render = function () {
  91042. this._updateCamera();
  91043. if (this.utilityLayerScene.activeCamera) {
  91044. // Set the camera's scene to utility layers scene
  91045. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  91046. var camera = this.utilityLayerScene.activeCamera;
  91047. camera._scene = this.utilityLayerScene;
  91048. if (camera.leftCamera) {
  91049. camera.leftCamera._scene = this.utilityLayerScene;
  91050. }
  91051. if (camera.rightCamera) {
  91052. camera.rightCamera._scene = this.utilityLayerScene;
  91053. }
  91054. this.utilityLayerScene.render(false);
  91055. // Reset camera's scene back to original
  91056. camera._scene = oldScene;
  91057. if (camera.leftCamera) {
  91058. camera.leftCamera._scene = oldScene;
  91059. }
  91060. if (camera.rightCamera) {
  91061. camera.rightCamera._scene = oldScene;
  91062. }
  91063. }
  91064. };
  91065. /**
  91066. * Disposes of the renderer
  91067. */
  91068. UtilityLayerRenderer.prototype.dispose = function () {
  91069. this.onPointerOutObservable.clear();
  91070. if (this._afterRenderObserver) {
  91071. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  91072. }
  91073. if (this._sceneDisposeObserver) {
  91074. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91075. }
  91076. if (this._originalPointerObserver) {
  91077. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  91078. }
  91079. this.utilityLayerScene.dispose();
  91080. };
  91081. UtilityLayerRenderer.prototype._updateCamera = function () {
  91082. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  91083. };
  91084. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91085. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91086. return UtilityLayerRenderer;
  91087. }());
  91088. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  91089. })(BABYLON || (BABYLON = {}));
  91090. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  91091. //# sourceMappingURL=babylon.behavior.js.map
  91092. var BABYLON;
  91093. (function (BABYLON) {
  91094. /**
  91095. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  91096. */
  91097. var PointerDragBehavior = /** @class */ (function () {
  91098. /**
  91099. * Creates a pointer drag behavior that can be attached to a mesh
  91100. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  91101. */
  91102. function PointerDragBehavior(options) {
  91103. /**
  91104. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  91105. */
  91106. this.maxDragAngle = 0;
  91107. /**
  91108. * @hidden
  91109. */
  91110. this._useAlternatePickedPointAboveMaxDragAngle = false;
  91111. /**
  91112. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91113. */
  91114. this.currentDraggingPointerID = -1;
  91115. /**
  91116. * If the behavior is currently in a dragging state
  91117. */
  91118. this.dragging = false;
  91119. /**
  91120. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  91121. */
  91122. this.dragDeltaRatio = 0.2;
  91123. /**
  91124. * If the drag plane orientation should be updated during the dragging (Default: true)
  91125. */
  91126. this.updateDragPlane = true;
  91127. // Debug mode will display drag planes to help visualize behavior
  91128. this._debugMode = false;
  91129. this._moving = false;
  91130. /**
  91131. * Fires each time the attached mesh is dragged with the pointer
  91132. * * delta between last drag position and current drag position in world space
  91133. * * dragDistance along the drag axis
  91134. * * dragPlaneNormal normal of the current drag plane used during the drag
  91135. * * dragPlanePoint in world space where the drag intersects the drag plane
  91136. */
  91137. this.onDragObservable = new BABYLON.Observable();
  91138. /**
  91139. * Fires each time a drag begins (eg. mouse down on mesh)
  91140. */
  91141. this.onDragStartObservable = new BABYLON.Observable();
  91142. /**
  91143. * Fires each time a drag ends (eg. mouse release after drag)
  91144. */
  91145. this.onDragEndObservable = new BABYLON.Observable();
  91146. /**
  91147. * If the attached mesh should be moved when dragged
  91148. */
  91149. this.moveAttached = true;
  91150. /**
  91151. * If the drag behavior will react to drag events (Default: true)
  91152. */
  91153. this.enabled = true;
  91154. /**
  91155. * If camera controls should be detached during the drag
  91156. */
  91157. this.detachCameraControls = true;
  91158. /**
  91159. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  91160. */
  91161. this.useObjectOrienationForDragging = true;
  91162. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91163. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  91164. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  91165. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91166. this._attachedElement = null;
  91167. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91168. this._lastPointerRay = {};
  91169. this._dragDelta = new BABYLON.Vector3();
  91170. // Variables to avoid instantiation in the below method
  91171. this._pointA = new BABYLON.Vector3(0, 0, 0);
  91172. this._pointB = new BABYLON.Vector3(0, 0, 0);
  91173. this._pointC = new BABYLON.Vector3(0, 0, 0);
  91174. this._lineA = new BABYLON.Vector3(0, 0, 0);
  91175. this._lineB = new BABYLON.Vector3(0, 0, 0);
  91176. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  91177. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  91178. this._options = options ? options : {};
  91179. var optionCount = 0;
  91180. if (this._options.dragAxis) {
  91181. optionCount++;
  91182. }
  91183. if (this._options.dragPlaneNormal) {
  91184. optionCount++;
  91185. }
  91186. if (optionCount > 1) {
  91187. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  91188. }
  91189. }
  91190. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  91191. /**
  91192. * The name of the behavior
  91193. */
  91194. get: function () {
  91195. return "PointerDrag";
  91196. },
  91197. enumerable: true,
  91198. configurable: true
  91199. });
  91200. /**
  91201. * Initializes the behavior
  91202. */
  91203. PointerDragBehavior.prototype.init = function () { };
  91204. /**
  91205. * Attaches the drag behavior the passed in mesh
  91206. * @param ownerNode The mesh that will be dragged around once attached
  91207. */
  91208. PointerDragBehavior.prototype.attach = function (ownerNode) {
  91209. var _this = this;
  91210. this._scene = ownerNode.getScene();
  91211. this._attachedNode = ownerNode;
  91212. // Initialize drag plane to not interfere with existing scene
  91213. if (!PointerDragBehavior._planeScene) {
  91214. if (this._debugMode) {
  91215. PointerDragBehavior._planeScene = this._scene;
  91216. }
  91217. else {
  91218. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  91219. PointerDragBehavior._planeScene.detachControl();
  91220. this._scene.getEngine().scenes.pop();
  91221. this._scene.onDisposeObservable.addOnce(function () {
  91222. PointerDragBehavior._planeScene.dispose();
  91223. PointerDragBehavior._planeScene = null;
  91224. });
  91225. }
  91226. }
  91227. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  91228. // State of the drag
  91229. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  91230. var pickPredicate = function (m) {
  91231. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  91232. };
  91233. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91234. if (!_this.enabled) {
  91235. return;
  91236. }
  91237. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91238. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91239. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  91240. }
  91241. }
  91242. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91243. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91244. _this.releaseDrag();
  91245. }
  91246. }
  91247. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91248. var pointerId = pointerInfo.event.pointerId;
  91249. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  91250. if (!_this._lastPointerRay[pointerId]) {
  91251. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91252. }
  91253. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  91254. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  91255. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  91256. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  91257. _this._moveDrag(pointerInfo.pickInfo.ray);
  91258. }
  91259. }
  91260. }
  91261. });
  91262. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91263. if (_this._moving && _this.moveAttached) {
  91264. // Slowly move mesh to avoid jitter
  91265. _this._targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  91266. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  91267. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  91268. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  91269. }
  91270. });
  91271. };
  91272. PointerDragBehavior.prototype.releaseDrag = function () {
  91273. this.dragging = false;
  91274. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  91275. this.currentDraggingPointerID = -1;
  91276. this._moving = false;
  91277. // Reattach camera controls
  91278. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91279. this._scene.activeCamera.attachControl(this._attachedElement, true);
  91280. }
  91281. };
  91282. /**
  91283. * Simulates the start of a pointer drag event on the behavior
  91284. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  91285. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  91286. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  91287. */
  91288. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  91289. if (pointerId === void 0) { pointerId = 1; }
  91290. this._startDrag(pointerId, fromRay, startPickedPoint);
  91291. if (this._lastPointerRay[pointerId]) {
  91292. // if there was a last pointer ray drag the object there
  91293. this._moveDrag(this._lastPointerRay[pointerId]);
  91294. }
  91295. };
  91296. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  91297. if (pointerId === void 0) { pointerId = 1; }
  91298. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  91299. return;
  91300. }
  91301. // Create start ray from the camera to the object
  91302. if (fromRay) {
  91303. this._startDragRay.direction.copyFrom(fromRay.direction);
  91304. this._startDragRay.origin.copyFrom(fromRay.origin);
  91305. }
  91306. else {
  91307. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  91308. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  91309. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  91310. }
  91311. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  91312. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  91313. if (pickedPoint) {
  91314. this.dragging = true;
  91315. this.currentDraggingPointerID = 1;
  91316. this.lastDragPosition.copyFrom(pickedPoint);
  91317. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  91318. this._targetPosition.copyFrom(this._attachedNode.absolutePosition);
  91319. // Detatch camera controls
  91320. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91321. if (this._scene.activeCamera.inputs.attachedElement) {
  91322. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  91323. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  91324. }
  91325. else {
  91326. this._attachedElement = null;
  91327. }
  91328. }
  91329. }
  91330. };
  91331. PointerDragBehavior.prototype._moveDrag = function (ray) {
  91332. this._moving = true;
  91333. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  91334. if (pickedPoint) {
  91335. if (this.updateDragPlane) {
  91336. this._updateDragPlanePosition(ray, pickedPoint);
  91337. }
  91338. var dragLength = 0;
  91339. // depending on the drag mode option drag accordingly
  91340. if (this._options.dragAxis) {
  91341. // Convert local drag axis to world
  91342. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  91343. // Project delta drag from the drag plane onto the drag axis
  91344. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  91345. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  91346. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  91347. }
  91348. else {
  91349. dragLength = this._dragDelta.length();
  91350. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  91351. }
  91352. this._targetPosition.addInPlace(this._dragDelta);
  91353. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  91354. this.lastDragPosition.copyFrom(pickedPoint);
  91355. }
  91356. };
  91357. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  91358. var _this = this;
  91359. if (!ray) {
  91360. return null;
  91361. }
  91362. // Calculate angle between plane normal and ray
  91363. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  91364. // Correct if ray is casted from oposite side
  91365. if (angle > Math.PI / 2) {
  91366. angle = Math.PI - angle;
  91367. }
  91368. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  91369. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  91370. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  91371. // Invert ray direction along the towards object axis
  91372. this._tmpVector.copyFrom(ray.direction);
  91373. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  91374. this._alternatePickedPoint.normalize();
  91375. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  91376. this._tmpVector.addInPlace(this._alternatePickedPoint);
  91377. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  91378. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  91379. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  91380. this._alternatePickedPoint.addInPlace(this._tmpVector);
  91381. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  91382. return this._alternatePickedPoint;
  91383. }
  91384. else {
  91385. return null;
  91386. }
  91387. }
  91388. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  91389. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  91390. return pickResult.pickedPoint;
  91391. }
  91392. else {
  91393. return null;
  91394. }
  91395. };
  91396. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  91397. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  91398. this._pointA.copyFrom(dragPlanePosition);
  91399. if (this._options.dragAxis) {
  91400. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  91401. // Calculate plane normal in direction of camera but perpendicular to drag axis
  91402. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  91403. ray.origin.subtractToRef(this._pointA, this._pointC);
  91404. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  91405. // Get perpendicular line from direction to camera and drag axis
  91406. this._pointB.subtractToRef(this._pointA, this._lineA);
  91407. this._pointC.subtractToRef(this._pointA, this._lineB);
  91408. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  91409. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  91410. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  91411. this._lookAt.normalize();
  91412. this._dragPlane.position.copyFrom(this._pointA);
  91413. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  91414. this._dragPlane.lookAt(this._lookAt);
  91415. }
  91416. else if (this._options.dragPlaneNormal) {
  91417. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  91418. this._dragPlane.position.copyFrom(this._pointA);
  91419. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  91420. this._dragPlane.lookAt(this._lookAt);
  91421. }
  91422. else {
  91423. this._dragPlane.position.copyFrom(this._pointA);
  91424. this._dragPlane.lookAt(ray.origin);
  91425. }
  91426. this._dragPlane.computeWorldMatrix(true);
  91427. };
  91428. /**
  91429. * Detaches the behavior from the mesh
  91430. */
  91431. PointerDragBehavior.prototype.detach = function () {
  91432. if (this._pointerObserver) {
  91433. this._scene.onPointerObservable.remove(this._pointerObserver);
  91434. }
  91435. if (this._beforeRenderObserver) {
  91436. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91437. }
  91438. };
  91439. return PointerDragBehavior;
  91440. }());
  91441. BABYLON.PointerDragBehavior = PointerDragBehavior;
  91442. })(BABYLON || (BABYLON = {}));
  91443. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  91444. var BABYLON;
  91445. (function (BABYLON) {
  91446. /**
  91447. * A behavior that when attached to a mesh will allow the mesh to be scaled
  91448. */
  91449. var MultiPointerScaleBehavior = /** @class */ (function () {
  91450. function MultiPointerScaleBehavior() {
  91451. this._startDistance = 0;
  91452. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  91453. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  91454. this._sceneRenderObserver = null;
  91455. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  91456. this._dragBehaviorA.moveAttached = false;
  91457. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  91458. this._dragBehaviorB.moveAttached = false;
  91459. }
  91460. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  91461. /**
  91462. * The name of the behavior
  91463. */
  91464. get: function () {
  91465. return "MultiPointerScale";
  91466. },
  91467. enumerable: true,
  91468. configurable: true
  91469. });
  91470. /**
  91471. * Initializes the behavior
  91472. */
  91473. MultiPointerScaleBehavior.prototype.init = function () { };
  91474. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  91475. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  91476. };
  91477. /**
  91478. * Attaches the scale behavior the passed in mesh
  91479. * @param ownerNode The mesh that will be scaled around once attached
  91480. */
  91481. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  91482. var _this = this;
  91483. this._ownerNode = ownerNode;
  91484. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  91485. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  91486. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91487. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91488. _this._dragBehaviorA.releaseDrag();
  91489. }
  91490. else {
  91491. _this._initialScale.copyFrom(ownerNode.scaling);
  91492. _this._startDistance = _this._getCurrentDistance();
  91493. }
  91494. }
  91495. });
  91496. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  91497. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91498. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91499. _this._dragBehaviorB.releaseDrag();
  91500. }
  91501. else {
  91502. _this._initialScale.copyFrom(ownerNode.scaling);
  91503. _this._startDistance = _this._getCurrentDistance();
  91504. }
  91505. }
  91506. });
  91507. // Once both drag behaviors are active scale based on the distance between the two pointers
  91508. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91509. behavior.onDragObservable.add(function () {
  91510. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91511. var ratio = _this._getCurrentDistance() / _this._startDistance;
  91512. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  91513. }
  91514. });
  91515. });
  91516. ownerNode.addBehavior(this._dragBehaviorA);
  91517. ownerNode.addBehavior(this._dragBehaviorB);
  91518. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91519. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91520. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91521. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  91522. if (change.length() > 0.01) {
  91523. ownerNode.scaling.addInPlace(change);
  91524. }
  91525. }
  91526. });
  91527. };
  91528. /**
  91529. * Detaches the behavior from the mesh
  91530. */
  91531. MultiPointerScaleBehavior.prototype.detach = function () {
  91532. var _this = this;
  91533. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91534. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91535. behavior.onDragStartObservable.clear();
  91536. behavior.onDragObservable.clear();
  91537. _this._ownerNode.removeBehavior(behavior);
  91538. });
  91539. };
  91540. return MultiPointerScaleBehavior;
  91541. }());
  91542. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  91543. })(BABYLON || (BABYLON = {}));
  91544. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  91545. var BABYLON;
  91546. (function (BABYLON) {
  91547. /**
  91548. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  91549. */
  91550. var SixDofDragBehavior = /** @class */ (function () {
  91551. function SixDofDragBehavior() {
  91552. this._sceneRenderObserver = null;
  91553. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91554. this._moving = false;
  91555. this._startingOrientation = new BABYLON.Quaternion();
  91556. /**
  91557. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  91558. */
  91559. this.zDragFactor = 3;
  91560. /**
  91561. * If the behavior is currently in a dragging state
  91562. */
  91563. this.dragging = false;
  91564. /**
  91565. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  91566. */
  91567. this.dragDeltaRatio = 0.2;
  91568. /**
  91569. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91570. */
  91571. this.currentDraggingPointerID = -1;
  91572. /**
  91573. * If camera controls should be detached during the drag
  91574. */
  91575. this.detachCameraControls = true;
  91576. }
  91577. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  91578. /**
  91579. * The name of the behavior
  91580. */
  91581. get: function () {
  91582. return "SixDofDrag";
  91583. },
  91584. enumerable: true,
  91585. configurable: true
  91586. });
  91587. /**
  91588. * Initializes the behavior
  91589. */
  91590. SixDofDragBehavior.prototype.init = function () { };
  91591. /**
  91592. * Attaches the scale behavior the passed in mesh
  91593. * @param ownerNode The mesh that will be scaled around once attached
  91594. */
  91595. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  91596. var _this = this;
  91597. this._ownerNode = ownerNode;
  91598. this._scene = this._ownerNode.getScene();
  91599. if (!SixDofDragBehavior._virtualScene) {
  91600. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  91601. this._scene.getEngine().scenes.pop();
  91602. }
  91603. var pickedMesh = null;
  91604. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  91605. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  91606. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91607. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  91608. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91609. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  91610. var pickPredicate = function (m) {
  91611. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  91612. };
  91613. var attachedElement = null;
  91614. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91615. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91616. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91617. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91618. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91619. }
  91620. pickedMesh = _this._ownerNode;
  91621. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91622. // Set position and orientation of the controller
  91623. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91624. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91625. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  91626. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91627. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  91628. if (!pickedMesh.rotationQuaternion) {
  91629. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  91630. }
  91631. var oldParent = pickedMesh.parent;
  91632. pickedMesh.setParent(null);
  91633. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  91634. pickedMesh.setParent(oldParent);
  91635. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91636. // Update state
  91637. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91638. _this.dragging = true;
  91639. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  91640. // Detatch camera controls
  91641. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91642. if (_this._scene.activeCamera.inputs.attachedElement) {
  91643. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  91644. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  91645. }
  91646. else {
  91647. attachedElement = null;
  91648. }
  91649. }
  91650. }
  91651. }
  91652. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91653. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91654. _this.dragging = false;
  91655. _this._moving = false;
  91656. _this.currentDraggingPointerID = -1;
  91657. pickedMesh = null;
  91658. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91659. // Reattach camera controls
  91660. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91661. _this._scene.activeCamera.attachControl(attachedElement, true);
  91662. }
  91663. }
  91664. }
  91665. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91666. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  91667. var zDragFactor = _this.zDragFactor;
  91668. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91669. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91670. zDragFactor = 0;
  91671. }
  91672. // Calculate controller drag distance in controller space
  91673. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  91674. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91675. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  91676. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91677. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  91678. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  91679. if (_this._virtualDragMesh.position.z < 0) {
  91680. _this._virtualDragMesh.position.z = 0;
  91681. }
  91682. // Update the controller position
  91683. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91684. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91685. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91686. // Move the virtualObjectsPosition into the picked mesh's space if needed
  91687. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91688. if (pickedMesh.parent) {
  91689. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  91690. }
  91691. if (!_this._moving) {
  91692. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  91693. }
  91694. _this._moving = true;
  91695. }
  91696. }
  91697. });
  91698. var tmpQuaternion = new BABYLON.Quaternion();
  91699. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91700. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91701. if (_this.dragging && _this._moving && pickedMesh) {
  91702. // Slowly move mesh to avoid jitter
  91703. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  91704. // Get change in rotation
  91705. tmpQuaternion.copyFrom(_this._startingOrientation);
  91706. tmpQuaternion.x = -tmpQuaternion.x;
  91707. tmpQuaternion.y = -tmpQuaternion.y;
  91708. tmpQuaternion.z = -tmpQuaternion.z;
  91709. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  91710. // Convert change in rotation to only y axis rotation
  91711. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  91712. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  91713. // Slowly move mesh to avoid jitter
  91714. var oldParent = pickedMesh.parent;
  91715. pickedMesh.setParent(null);
  91716. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  91717. pickedMesh.setParent(oldParent);
  91718. }
  91719. });
  91720. };
  91721. /**
  91722. * Detaches the behavior from the mesh
  91723. */
  91724. SixDofDragBehavior.prototype.detach = function () {
  91725. if (this._scene) {
  91726. this._scene.onPointerObservable.remove(this._pointerObserver);
  91727. }
  91728. if (this._ownerNode) {
  91729. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91730. }
  91731. if (this._virtualOriginMesh) {
  91732. this._virtualOriginMesh.dispose();
  91733. }
  91734. if (this._virtualDragMesh) {
  91735. this._virtualDragMesh.dispose();
  91736. }
  91737. };
  91738. return SixDofDragBehavior;
  91739. }());
  91740. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  91741. })(BABYLON || (BABYLON = {}));
  91742. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  91743. var BABYLON;
  91744. (function (BABYLON) {
  91745. /**
  91746. * @hidden
  91747. */
  91748. var FaceDirectionInfo = /** @class */ (function () {
  91749. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  91750. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  91751. if (diff === void 0) { diff = 0; }
  91752. if (ignore === void 0) { ignore = false; }
  91753. this.direction = direction;
  91754. this.rotatedDirection = rotatedDirection;
  91755. this.diff = diff;
  91756. this.ignore = ignore;
  91757. }
  91758. return FaceDirectionInfo;
  91759. }());
  91760. /**
  91761. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  91762. */
  91763. var AttachToBoxBehavior = /** @class */ (function () {
  91764. /**
  91765. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  91766. * @param ui The transform node that should be attched to the mesh
  91767. */
  91768. function AttachToBoxBehavior(ui) {
  91769. this.ui = ui;
  91770. /**
  91771. * The name of the behavior
  91772. */
  91773. this.name = "AttachToBoxBehavior";
  91774. /**
  91775. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  91776. */
  91777. this.distanceAwayFromFace = 0.15;
  91778. /**
  91779. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  91780. */
  91781. this.distanceAwayFromBottomOfFace = 0.15;
  91782. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  91783. this._tmpMatrix = new BABYLON.Matrix();
  91784. this._tmpVector = new BABYLON.Vector3();
  91785. this._zeroVector = BABYLON.Vector3.Zero();
  91786. this._lookAtTmpMatrix = new BABYLON.Matrix();
  91787. /* Does nothing */
  91788. }
  91789. /**
  91790. * Initializes the behavior
  91791. */
  91792. AttachToBoxBehavior.prototype.init = function () {
  91793. /* Does nothing */
  91794. };
  91795. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  91796. var _this = this;
  91797. // Go over each face and calculate the angle between the face's normal and targetDirection
  91798. this._faceVectors.forEach(function (v) {
  91799. if (!_this._target.rotationQuaternion) {
  91800. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  91801. }
  91802. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  91803. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  91804. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  91805. });
  91806. // Return the face information of the one with the normal closeset to target direction
  91807. return this._faceVectors.reduce(function (min, p) {
  91808. if (min.ignore) {
  91809. return p;
  91810. }
  91811. else if (p.ignore) {
  91812. return min;
  91813. }
  91814. else {
  91815. return min.diff < p.diff ? min : p;
  91816. }
  91817. }, this._faceVectors[0]);
  91818. };
  91819. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  91820. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  91821. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  91822. this._lookAtTmpMatrix.invert();
  91823. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  91824. };
  91825. /**
  91826. * Attaches the AttachToBoxBehavior to the passed in mesh
  91827. * @param target The mesh that the specified node will be attached to
  91828. */
  91829. AttachToBoxBehavior.prototype.attach = function (target) {
  91830. var _this = this;
  91831. this._target = target;
  91832. this._scene = this._target.getScene();
  91833. // Every frame, update the app bars position
  91834. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91835. if (!_this._scene.activeCamera) {
  91836. return;
  91837. }
  91838. // Find the face closest to the cameras position
  91839. var cameraPos = _this._scene.activeCamera.position;
  91840. if (_this._scene.activeCamera.devicePosition) {
  91841. cameraPos = _this._scene.activeCamera.devicePosition;
  91842. }
  91843. var facing = _this._closestFace(cameraPos.subtract(target.position));
  91844. if (_this._scene.activeCamera.leftCamera) {
  91845. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91846. }
  91847. else {
  91848. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91849. }
  91850. // Get camera up direction
  91851. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  91852. // Ignore faces to not select a parrelel face for the up vector of the UI
  91853. _this._faceVectors.forEach(function (v) {
  91854. if (facing.direction.x && v.direction.x) {
  91855. v.ignore = true;
  91856. }
  91857. if (facing.direction.y && v.direction.y) {
  91858. v.ignore = true;
  91859. }
  91860. if (facing.direction.z && v.direction.z) {
  91861. v.ignore = true;
  91862. }
  91863. });
  91864. var facingUp = _this._closestFace(_this._tmpVector);
  91865. // Unignore faces
  91866. _this._faceVectors.forEach(function (v) {
  91867. v.ignore = false;
  91868. });
  91869. // Position the app bar on that face
  91870. _this.ui.position.copyFrom(target.position);
  91871. if (facing.direction.x) {
  91872. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91873. _this.ui.position.addInPlace(_this._tmpVector);
  91874. }
  91875. if (facing.direction.y) {
  91876. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91877. _this.ui.position.addInPlace(_this._tmpVector);
  91878. }
  91879. if (facing.direction.z) {
  91880. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91881. _this.ui.position.addInPlace(_this._tmpVector);
  91882. }
  91883. // Rotate to be oriented properly to the camera
  91884. if (!_this.ui.rotationQuaternion) {
  91885. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  91886. }
  91887. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  91888. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  91889. // Place ui the correct distance from the bottom of the mesh
  91890. if (facingUp.direction.x) {
  91891. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  91892. }
  91893. if (facingUp.direction.y) {
  91894. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  91895. }
  91896. if (facingUp.direction.z) {
  91897. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  91898. }
  91899. _this.ui.position.addInPlace(_this._tmpVector);
  91900. });
  91901. };
  91902. /**
  91903. * Detaches the behavior from the mesh
  91904. */
  91905. AttachToBoxBehavior.prototype.detach = function () {
  91906. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  91907. };
  91908. return AttachToBoxBehavior;
  91909. }());
  91910. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  91911. })(BABYLON || (BABYLON = {}));
  91912. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  91913. var BABYLON;
  91914. (function (BABYLON) {
  91915. /**
  91916. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  91917. */
  91918. var FadeInOutBehavior = /** @class */ (function () {
  91919. /**
  91920. * Instatiates the FadeInOutBehavior
  91921. */
  91922. function FadeInOutBehavior() {
  91923. var _this = this;
  91924. /**
  91925. * Time in milliseconds to delay before fading in (Default: 0)
  91926. */
  91927. this.delay = 0;
  91928. /**
  91929. * Time in milliseconds for the mesh to fade in (Default: 300)
  91930. */
  91931. this.fadeInTime = 300;
  91932. this._millisecondsPerFrame = 1000 / 60;
  91933. this._hovered = false;
  91934. this._hoverValue = 0;
  91935. this._ownerNode = null;
  91936. this._update = function () {
  91937. if (_this._ownerNode) {
  91938. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  91939. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  91940. if (_this._ownerNode.visibility > 1) {
  91941. _this._setAllVisibility(_this._ownerNode, 1);
  91942. _this._hoverValue = _this.fadeInTime + _this.delay;
  91943. return;
  91944. }
  91945. else if (_this._ownerNode.visibility < 0) {
  91946. _this._setAllVisibility(_this._ownerNode, 0);
  91947. if (_this._hoverValue < 0) {
  91948. _this._hoverValue = 0;
  91949. return;
  91950. }
  91951. }
  91952. setTimeout(_this._update, _this._millisecondsPerFrame);
  91953. }
  91954. };
  91955. }
  91956. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  91957. /**
  91958. * The name of the behavior
  91959. */
  91960. get: function () {
  91961. return "FadeInOut";
  91962. },
  91963. enumerable: true,
  91964. configurable: true
  91965. });
  91966. /**
  91967. * Initializes the behavior
  91968. */
  91969. FadeInOutBehavior.prototype.init = function () {
  91970. };
  91971. /**
  91972. * Attaches the fade behavior on the passed in mesh
  91973. * @param ownerNode The mesh that will be faded in/out once attached
  91974. */
  91975. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  91976. this._ownerNode = ownerNode;
  91977. this._setAllVisibility(this._ownerNode, 0);
  91978. };
  91979. /**
  91980. * Detaches the behavior from the mesh
  91981. */
  91982. FadeInOutBehavior.prototype.detach = function () {
  91983. this._ownerNode = null;
  91984. };
  91985. /**
  91986. * Triggers the mesh to begin fading in or out
  91987. * @param value if the object should fade in or out (true to fade in)
  91988. */
  91989. FadeInOutBehavior.prototype.fadeIn = function (value) {
  91990. this._hovered = value;
  91991. this._update();
  91992. };
  91993. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  91994. var _this = this;
  91995. mesh.visibility = value;
  91996. mesh.getChildMeshes().forEach(function (c) {
  91997. _this._setAllVisibility(c, value);
  91998. });
  91999. };
  92000. return FadeInOutBehavior;
  92001. }());
  92002. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  92003. })(BABYLON || (BABYLON = {}));
  92004. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  92005. var BABYLON;
  92006. (function (BABYLON) {
  92007. /**
  92008. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  92009. */
  92010. var Gizmo = /** @class */ (function () {
  92011. /**
  92012. * Creates a gizmo
  92013. * @param gizmoLayer The utility layer the gizmo will be added to
  92014. */
  92015. function Gizmo(
  92016. /** The utility layer the gizmo will be added to */
  92017. gizmoLayer) {
  92018. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92019. var _this = this;
  92020. this.gizmoLayer = gizmoLayer;
  92021. /**
  92022. * Ratio for the scale of the gizmo (Default: 1)
  92023. */
  92024. this.scaleRatio = 1;
  92025. this._tmpMatrix = new BABYLON.Matrix();
  92026. /**
  92027. * If a custom mesh has been set (Default: false)
  92028. */
  92029. this._customMeshSet = false;
  92030. /**
  92031. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  92032. */
  92033. this.updateGizmoRotationToMatchAttachedMesh = true;
  92034. /**
  92035. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  92036. */
  92037. this.updateGizmoPositionToMatchAttachedMesh = true;
  92038. /**
  92039. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  92040. */
  92041. this._updateScale = true;
  92042. this._interactionsEnabled = true;
  92043. this._tempVector = new BABYLON.Vector3();
  92044. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  92045. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  92046. _this._update();
  92047. });
  92048. this.attachedMesh = null;
  92049. }
  92050. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  92051. /**
  92052. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  92053. * * When set, interactions will be enabled
  92054. */
  92055. get: function () {
  92056. return this._attachedMesh;
  92057. },
  92058. set: function (value) {
  92059. this._attachedMesh = value;
  92060. this._rootMesh.setEnabled(value ? true : false);
  92061. this._attachedMeshChanged(value);
  92062. },
  92063. enumerable: true,
  92064. configurable: true
  92065. });
  92066. /**
  92067. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92068. * @param mesh The mesh to replace the default mesh of the gizmo
  92069. */
  92070. Gizmo.prototype.setCustomMesh = function (mesh) {
  92071. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  92072. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  92073. }
  92074. this._rootMesh.getChildMeshes().forEach(function (c) {
  92075. c.dispose();
  92076. });
  92077. mesh.parent = this._rootMesh;
  92078. this._customMeshSet = true;
  92079. };
  92080. Gizmo.prototype._attachedMeshChanged = function (value) {
  92081. };
  92082. /**
  92083. * @hidden
  92084. * Updates the gizmo to match the attached mesh's position/rotation
  92085. */
  92086. Gizmo.prototype._update = function () {
  92087. if (this.attachedMesh) {
  92088. if (this.updateGizmoRotationToMatchAttachedMesh) {
  92089. if (!this._rootMesh.rotationQuaternion) {
  92090. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  92091. }
  92092. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  92093. this._tempVector.copyFrom(this.attachedMesh.scaling);
  92094. if (this.attachedMesh.scaling.x < 0) {
  92095. this.attachedMesh.scaling.x *= -1;
  92096. }
  92097. if (this.attachedMesh.scaling.y < 0) {
  92098. this.attachedMesh.scaling.y *= -1;
  92099. }
  92100. if (this.attachedMesh.scaling.z < 0) {
  92101. this.attachedMesh.scaling.z *= -1;
  92102. }
  92103. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  92104. this.attachedMesh.scaling.copyFrom(this._tempVector);
  92105. this.attachedMesh.computeWorldMatrix();
  92106. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  92107. }
  92108. else if (this._rootMesh.rotationQuaternion) {
  92109. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  92110. }
  92111. if (this.updateGizmoPositionToMatchAttachedMesh) {
  92112. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  92113. }
  92114. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  92115. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  92116. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  92117. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  92118. }
  92119. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  92120. var dist = this._tempVector.length() * this.scaleRatio;
  92121. this._rootMesh.scaling.set(dist, dist, dist);
  92122. }
  92123. }
  92124. };
  92125. /**
  92126. * Disposes of the gizmo
  92127. */
  92128. Gizmo.prototype.dispose = function () {
  92129. this._rootMesh.dispose();
  92130. if (this._beforeRenderObserver) {
  92131. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92132. }
  92133. };
  92134. return Gizmo;
  92135. }());
  92136. BABYLON.Gizmo = Gizmo;
  92137. })(BABYLON || (BABYLON = {}));
  92138. //# sourceMappingURL=babylon.gizmo.js.map
  92139. var BABYLON;
  92140. (function (BABYLON) {
  92141. /**
  92142. * Single axis drag gizmo
  92143. */
  92144. var AxisDragGizmo = /** @class */ (function (_super) {
  92145. __extends(AxisDragGizmo, _super);
  92146. /**
  92147. * Creates an AxisDragGizmo
  92148. * @param gizmoLayer The utility layer the gizmo will be added to
  92149. * @param dragAxis The axis which the gizmo will be able to drag on
  92150. * @param color The color of the gizmo
  92151. */
  92152. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  92153. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92154. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92155. var _this = _super.call(this, gizmoLayer) || this;
  92156. _this._pointerObserver = null;
  92157. /**
  92158. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92159. */
  92160. _this.snapDistance = 0;
  92161. /**
  92162. * Event that fires each time the gizmo snaps to a new location.
  92163. * * snapDistance is the the change in distance
  92164. */
  92165. _this.onSnapObservable = new BABYLON.Observable();
  92166. // Create Material
  92167. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92168. coloredMaterial.disableLighting = true;
  92169. coloredMaterial.emissiveColor = color;
  92170. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92171. hoverMaterial.disableLighting = true;
  92172. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92173. // Build mesh on root node
  92174. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92175. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  92176. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92177. arrowTail.color = coloredMaterial.emissiveColor;
  92178. arrow.addChild(arrowMesh);
  92179. arrow.addChild(arrowTail);
  92180. // Position arrow pointing in its drag axis
  92181. arrowMesh.scaling.scaleInPlace(0.05);
  92182. arrowMesh.material = coloredMaterial;
  92183. arrowMesh.rotation.x = Math.PI / 2;
  92184. arrowMesh.position.z += 0.3;
  92185. arrowTail.scaling.scaleInPlace(0.26);
  92186. arrowTail.rotation.x = Math.PI / 2;
  92187. arrowTail.material = coloredMaterial;
  92188. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92189. arrow.scaling.scaleInPlace(1 / 3);
  92190. _this._rootMesh.addChild(arrow);
  92191. var currentSnapDragDistance = 0;
  92192. var tmpVector = new BABYLON.Vector3();
  92193. var tmpSnapEvent = { snapDistance: 0 };
  92194. // Add drag behavior to handle events when the gizmo is dragged
  92195. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92196. _this.dragBehavior.moveAttached = false;
  92197. _this._rootMesh.addBehavior(_this.dragBehavior);
  92198. var localDelta = new BABYLON.Vector3();
  92199. var tmpMatrix = new BABYLON.Matrix();
  92200. _this.dragBehavior.onDragObservable.add(function (event) {
  92201. if (_this.attachedMesh) {
  92202. // Convert delta to local translation if it has a parent
  92203. if (_this.attachedMesh.parent) {
  92204. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92205. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  92206. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  92207. }
  92208. else {
  92209. localDelta.copyFrom(event.delta);
  92210. }
  92211. // Snapping logic
  92212. if (_this.snapDistance == 0) {
  92213. _this.attachedMesh.position.addInPlace(localDelta);
  92214. }
  92215. else {
  92216. currentSnapDragDistance += event.dragDistance;
  92217. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92218. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  92219. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92220. localDelta.normalizeToRef(tmpVector);
  92221. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  92222. _this.attachedMesh.position.addInPlace(tmpVector);
  92223. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92224. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92225. }
  92226. }
  92227. }
  92228. });
  92229. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92230. if (_this._customMeshSet) {
  92231. return;
  92232. }
  92233. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92234. var material = isHovered ? hoverMaterial : coloredMaterial;
  92235. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92236. m.material = material;
  92237. if (m.color) {
  92238. m.color = material.emissiveColor;
  92239. }
  92240. });
  92241. });
  92242. return _this;
  92243. }
  92244. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  92245. if (this.dragBehavior) {
  92246. this.dragBehavior.enabled = value ? true : false;
  92247. }
  92248. };
  92249. /**
  92250. * Disposes of the gizmo
  92251. */
  92252. AxisDragGizmo.prototype.dispose = function () {
  92253. this.onSnapObservable.clear();
  92254. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92255. this.dragBehavior.detach();
  92256. _super.prototype.dispose.call(this);
  92257. };
  92258. return AxisDragGizmo;
  92259. }(BABYLON.Gizmo));
  92260. BABYLON.AxisDragGizmo = AxisDragGizmo;
  92261. })(BABYLON || (BABYLON = {}));
  92262. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  92263. var BABYLON;
  92264. (function (BABYLON) {
  92265. /**
  92266. * Single axis scale gizmo
  92267. */
  92268. var AxisScaleGizmo = /** @class */ (function (_super) {
  92269. __extends(AxisScaleGizmo, _super);
  92270. /**
  92271. * Creates an AxisScaleGizmo
  92272. * @param gizmoLayer The utility layer the gizmo will be added to
  92273. * @param dragAxis The axis which the gizmo will be able to scale on
  92274. * @param color The color of the gizmo
  92275. */
  92276. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  92277. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92278. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92279. var _this = _super.call(this, gizmoLayer) || this;
  92280. _this._pointerObserver = null;
  92281. /**
  92282. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92283. */
  92284. _this.snapDistance = 0;
  92285. /**
  92286. * Event that fires each time the gizmo snaps to a new location.
  92287. * * snapDistance is the the change in distance
  92288. */
  92289. _this.onSnapObservable = new BABYLON.Observable();
  92290. /**
  92291. * If the scaling operation should be done on all axis (default: false)
  92292. */
  92293. _this.uniformScaling = false;
  92294. // Create Material
  92295. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92296. _this._coloredMaterial.disableLighting = true;
  92297. _this._coloredMaterial.emissiveColor = color;
  92298. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92299. hoverMaterial.disableLighting = true;
  92300. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92301. // Build mesh on root node
  92302. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92303. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  92304. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92305. arrowTail.color = _this._coloredMaterial.emissiveColor;
  92306. arrow.addChild(arrowMesh);
  92307. arrow.addChild(arrowTail);
  92308. // Position arrow pointing in its drag axis
  92309. arrowMesh.scaling.scaleInPlace(0.1);
  92310. arrowMesh.material = _this._coloredMaterial;
  92311. arrowMesh.rotation.x = Math.PI / 2;
  92312. arrowMesh.position.z += 0.3;
  92313. arrowTail.scaling.scaleInPlace(0.26);
  92314. arrowTail.rotation.x = Math.PI / 2;
  92315. arrowTail.material = _this._coloredMaterial;
  92316. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92317. _this._rootMesh.addChild(arrow);
  92318. arrow.scaling.scaleInPlace(1 / 3);
  92319. // Add drag behavior to handle events when the gizmo is dragged
  92320. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92321. _this.dragBehavior.moveAttached = false;
  92322. _this._rootMesh.addBehavior(_this.dragBehavior);
  92323. var currentSnapDragDistance = 0;
  92324. var tmpVector = new BABYLON.Vector3();
  92325. var tmpSnapEvent = { snapDistance: 0 };
  92326. _this.dragBehavior.onDragObservable.add(function (event) {
  92327. if (_this.attachedMesh) {
  92328. // Snapping logic
  92329. var snapped = false;
  92330. var dragSteps = 0;
  92331. if (_this.uniformScaling) {
  92332. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  92333. if (tmpVector.y < 0) {
  92334. tmpVector.scaleInPlace(-1);
  92335. }
  92336. }
  92337. else {
  92338. tmpVector.copyFrom(dragAxis);
  92339. }
  92340. if (_this.snapDistance == 0) {
  92341. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  92342. }
  92343. else {
  92344. currentSnapDragDistance += event.dragDistance;
  92345. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92346. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92347. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92348. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  92349. snapped = true;
  92350. }
  92351. else {
  92352. tmpVector.scaleInPlace(0);
  92353. }
  92354. }
  92355. _this.attachedMesh.scaling.addInPlace(tmpVector);
  92356. if (snapped) {
  92357. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92358. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92359. }
  92360. }
  92361. });
  92362. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92363. if (_this._customMeshSet) {
  92364. return;
  92365. }
  92366. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92367. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  92368. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92369. m.material = material;
  92370. if (m.color) {
  92371. m.color = material.emissiveColor;
  92372. }
  92373. });
  92374. });
  92375. return _this;
  92376. }
  92377. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  92378. if (this.dragBehavior) {
  92379. this.dragBehavior.enabled = value ? true : false;
  92380. }
  92381. };
  92382. /**
  92383. * Disposes of the gizmo
  92384. */
  92385. AxisScaleGizmo.prototype.dispose = function () {
  92386. this.onSnapObservable.clear();
  92387. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92388. this.dragBehavior.detach();
  92389. _super.prototype.dispose.call(this);
  92390. };
  92391. /**
  92392. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92393. * @param mesh The mesh to replace the default mesh of the gizmo
  92394. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  92395. */
  92396. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  92397. var _this = this;
  92398. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  92399. _super.prototype.setCustomMesh.call(this, mesh);
  92400. if (useGizmoMaterial) {
  92401. this._rootMesh.getChildMeshes().forEach(function (m) {
  92402. m.material = _this._coloredMaterial;
  92403. if (m.color) {
  92404. m.color = _this._coloredMaterial.emissiveColor;
  92405. }
  92406. });
  92407. this._customMeshSet = false;
  92408. }
  92409. };
  92410. return AxisScaleGizmo;
  92411. }(BABYLON.Gizmo));
  92412. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  92413. })(BABYLON || (BABYLON = {}));
  92414. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  92415. var BABYLON;
  92416. (function (BABYLON) {
  92417. /**
  92418. * Single plane rotation gizmo
  92419. */
  92420. var PlaneRotationGizmo = /** @class */ (function (_super) {
  92421. __extends(PlaneRotationGizmo, _super);
  92422. /**
  92423. * Creates a PlaneRotationGizmo
  92424. * @param gizmoLayer The utility layer the gizmo will be added to
  92425. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  92426. * @param color The color of the gizmo
  92427. */
  92428. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  92429. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92430. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92431. var _this = _super.call(this, gizmoLayer) || this;
  92432. _this._pointerObserver = null;
  92433. /**
  92434. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  92435. */
  92436. _this.snapDistance = 0;
  92437. /**
  92438. * Event that fires each time the gizmo snaps to a new location.
  92439. * * snapDistance is the the change in distance
  92440. */
  92441. _this.onSnapObservable = new BABYLON.Observable();
  92442. // Create Material
  92443. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92444. coloredMaterial.disableLighting = true;
  92445. coloredMaterial.emissiveColor = color;
  92446. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92447. hoverMaterial.disableLighting = true;
  92448. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92449. // Build mesh on root node
  92450. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92451. // Create circle out of lines
  92452. var tessellation = 20;
  92453. var radius = 0.8;
  92454. var points = new Array();
  92455. for (var i = 0; i < tessellation; i++) {
  92456. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  92457. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  92458. }
  92459. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  92460. rotationMesh.color = coloredMaterial.emissiveColor;
  92461. // Position arrow pointing in its drag axis
  92462. rotationMesh.scaling.scaleInPlace(0.26);
  92463. rotationMesh.material = coloredMaterial;
  92464. rotationMesh.rotation.x = Math.PI / 2;
  92465. parentMesh.addChild(rotationMesh);
  92466. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  92467. _this._rootMesh.addChild(parentMesh);
  92468. parentMesh.scaling.scaleInPlace(1 / 3);
  92469. // Add drag behavior to handle events when the gizmo is dragged
  92470. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  92471. _this.dragBehavior.moveAttached = false;
  92472. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  92473. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  92474. _this._rootMesh.addBehavior(_this.dragBehavior);
  92475. var lastDragPosition = new BABYLON.Vector3();
  92476. _this.dragBehavior.onDragStartObservable.add(function (e) {
  92477. if (_this.attachedMesh) {
  92478. lastDragPosition.copyFrom(e.dragPlanePoint);
  92479. }
  92480. });
  92481. var rotationMatrix = new BABYLON.Matrix();
  92482. var planeNormalTowardsCamera = new BABYLON.Vector3();
  92483. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  92484. var tmpSnapEvent = { snapDistance: 0 };
  92485. var currentSnapDragDistance = 0;
  92486. var tmpMatrix = new BABYLON.Matrix();
  92487. var tmpVector = new BABYLON.Vector3();
  92488. var amountToRotate = new BABYLON.Quaternion();
  92489. _this.dragBehavior.onDragObservable.add(function (event) {
  92490. if (_this.attachedMesh) {
  92491. if (!_this.attachedMesh.rotationQuaternion) {
  92492. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92493. }
  92494. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  92495. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  92496. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  92497. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  92498. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  92499. var angle = Math.atan2(cross.length(), dot);
  92500. planeNormalTowardsCamera.copyFrom(planeNormal);
  92501. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  92502. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92503. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  92504. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  92505. }
  92506. // Flip up vector depending on which side the camera is on
  92507. if (gizmoLayer.utilityLayerScene.activeCamera) {
  92508. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  92509. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  92510. planeNormalTowardsCamera.scaleInPlace(-1);
  92511. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  92512. }
  92513. }
  92514. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  92515. if (halfCircleSide)
  92516. angle = -angle;
  92517. // Snapping logic
  92518. var snapped = false;
  92519. if (_this.snapDistance != 0) {
  92520. currentSnapDragDistance += angle;
  92521. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92522. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92523. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92524. angle = _this.snapDistance * dragSteps;
  92525. snapped = true;
  92526. }
  92527. else {
  92528. angle = 0;
  92529. }
  92530. }
  92531. // If the mesh has a parent, convert needed world rotation to local rotation
  92532. tmpMatrix.reset();
  92533. if (_this.attachedMesh.parent) {
  92534. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92535. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  92536. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  92537. }
  92538. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  92539. var quaternionCoefficient = Math.sin(angle / 2);
  92540. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  92541. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  92542. if (tmpMatrix.determinant() > 0) {
  92543. amountToRotate.toEulerAnglesToRef(tmpVector);
  92544. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  92545. }
  92546. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92547. // Rotate selected mesh quaternion over fixed axis
  92548. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  92549. }
  92550. else {
  92551. // Rotate selected mesh quaternion over rotated axis
  92552. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  92553. }
  92554. lastDragPosition.copyFrom(event.dragPlanePoint);
  92555. if (snapped) {
  92556. tmpSnapEvent.snapDistance = angle;
  92557. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92558. }
  92559. }
  92560. });
  92561. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92562. if (_this._customMeshSet) {
  92563. return;
  92564. }
  92565. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92566. var material = isHovered ? hoverMaterial : coloredMaterial;
  92567. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92568. m.material = material;
  92569. if (m.color) {
  92570. m.color = material.emissiveColor;
  92571. }
  92572. });
  92573. });
  92574. return _this;
  92575. }
  92576. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  92577. if (this.dragBehavior) {
  92578. this.dragBehavior.enabled = value ? true : false;
  92579. }
  92580. };
  92581. /**
  92582. * Disposes of the gizmo
  92583. */
  92584. PlaneRotationGizmo.prototype.dispose = function () {
  92585. this.onSnapObservable.clear();
  92586. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92587. this.dragBehavior.detach();
  92588. _super.prototype.dispose.call(this);
  92589. };
  92590. return PlaneRotationGizmo;
  92591. }(BABYLON.Gizmo));
  92592. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  92593. })(BABYLON || (BABYLON = {}));
  92594. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  92595. var BABYLON;
  92596. (function (BABYLON) {
  92597. /**
  92598. * Gizmo that enables dragging a mesh along 3 axis
  92599. */
  92600. var PositionGizmo = /** @class */ (function (_super) {
  92601. __extends(PositionGizmo, _super);
  92602. /**
  92603. * Creates a PositionGizmo
  92604. * @param gizmoLayer The utility layer the gizmo will be added to
  92605. */
  92606. function PositionGizmo(gizmoLayer) {
  92607. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92608. var _this = _super.call(this, gizmoLayer) || this;
  92609. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92610. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92611. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92612. _this.attachedMesh = null;
  92613. return _this;
  92614. }
  92615. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  92616. set: function (mesh) {
  92617. if (this.xGizmo) {
  92618. this.xGizmo.attachedMesh = mesh;
  92619. this.yGizmo.attachedMesh = mesh;
  92620. this.zGizmo.attachedMesh = mesh;
  92621. }
  92622. },
  92623. enumerable: true,
  92624. configurable: true
  92625. });
  92626. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92627. get: function () {
  92628. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92629. },
  92630. set: function (value) {
  92631. if (this.xGizmo) {
  92632. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92633. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92634. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92635. }
  92636. },
  92637. enumerable: true,
  92638. configurable: true
  92639. });
  92640. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  92641. get: function () {
  92642. return this.xGizmo.snapDistance;
  92643. },
  92644. /**
  92645. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92646. */
  92647. set: function (value) {
  92648. if (this.xGizmo) {
  92649. this.xGizmo.snapDistance = value;
  92650. this.yGizmo.snapDistance = value;
  92651. this.zGizmo.snapDistance = value;
  92652. }
  92653. },
  92654. enumerable: true,
  92655. configurable: true
  92656. });
  92657. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  92658. get: function () {
  92659. return this.xGizmo.scaleRatio;
  92660. },
  92661. /**
  92662. * Ratio for the scale of the gizmo (Default: 1)
  92663. */
  92664. set: function (value) {
  92665. if (this.xGizmo) {
  92666. this.xGizmo.scaleRatio = value;
  92667. this.yGizmo.scaleRatio = value;
  92668. this.zGizmo.scaleRatio = value;
  92669. }
  92670. },
  92671. enumerable: true,
  92672. configurable: true
  92673. });
  92674. /**
  92675. * Disposes of the gizmo
  92676. */
  92677. PositionGizmo.prototype.dispose = function () {
  92678. this.xGizmo.dispose();
  92679. this.yGizmo.dispose();
  92680. this.zGizmo.dispose();
  92681. };
  92682. /**
  92683. * CustomMeshes are not supported by this gizmo
  92684. * @param mesh The mesh to replace the default mesh of the gizmo
  92685. */
  92686. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  92687. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  92688. };
  92689. return PositionGizmo;
  92690. }(BABYLON.Gizmo));
  92691. BABYLON.PositionGizmo = PositionGizmo;
  92692. })(BABYLON || (BABYLON = {}));
  92693. //# sourceMappingURL=babylon.positionGizmo.js.map
  92694. var BABYLON;
  92695. (function (BABYLON) {
  92696. /**
  92697. * Gizmo that enables rotating a mesh along 3 axis
  92698. */
  92699. var RotationGizmo = /** @class */ (function (_super) {
  92700. __extends(RotationGizmo, _super);
  92701. /**
  92702. * Creates a RotationGizmo
  92703. * @param gizmoLayer The utility layer the gizmo will be added to
  92704. */
  92705. function RotationGizmo(gizmoLayer) {
  92706. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92707. var _this = _super.call(this, gizmoLayer) || this;
  92708. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92709. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92710. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92711. _this.attachedMesh = null;
  92712. return _this;
  92713. }
  92714. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  92715. set: function (mesh) {
  92716. if (this.xGizmo) {
  92717. this.xGizmo.attachedMesh = mesh;
  92718. this.yGizmo.attachedMesh = mesh;
  92719. this.zGizmo.attachedMesh = mesh;
  92720. }
  92721. },
  92722. enumerable: true,
  92723. configurable: true
  92724. });
  92725. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92726. get: function () {
  92727. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92728. },
  92729. set: function (value) {
  92730. if (this.xGizmo) {
  92731. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92732. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92733. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92734. }
  92735. },
  92736. enumerable: true,
  92737. configurable: true
  92738. });
  92739. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  92740. get: function () {
  92741. return this.xGizmo.snapDistance;
  92742. },
  92743. /**
  92744. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92745. */
  92746. set: function (value) {
  92747. if (this.xGizmo) {
  92748. this.xGizmo.snapDistance = value;
  92749. this.yGizmo.snapDistance = value;
  92750. this.zGizmo.snapDistance = value;
  92751. }
  92752. },
  92753. enumerable: true,
  92754. configurable: true
  92755. });
  92756. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  92757. get: function () {
  92758. return this.xGizmo.scaleRatio;
  92759. },
  92760. /**
  92761. * Ratio for the scale of the gizmo (Default: 1)
  92762. */
  92763. set: function (value) {
  92764. if (this.xGizmo) {
  92765. this.xGizmo.scaleRatio = value;
  92766. this.yGizmo.scaleRatio = value;
  92767. this.zGizmo.scaleRatio = value;
  92768. }
  92769. },
  92770. enumerable: true,
  92771. configurable: true
  92772. });
  92773. /**
  92774. * Disposes of the gizmo
  92775. */
  92776. RotationGizmo.prototype.dispose = function () {
  92777. this.xGizmo.dispose();
  92778. this.yGizmo.dispose();
  92779. this.zGizmo.dispose();
  92780. };
  92781. /**
  92782. * CustomMeshes are not supported by this gizmo
  92783. * @param mesh The mesh to replace the default mesh of the gizmo
  92784. */
  92785. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  92786. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  92787. };
  92788. return RotationGizmo;
  92789. }(BABYLON.Gizmo));
  92790. BABYLON.RotationGizmo = RotationGizmo;
  92791. })(BABYLON || (BABYLON = {}));
  92792. //# sourceMappingURL=babylon.rotationGizmo.js.map
  92793. var BABYLON;
  92794. (function (BABYLON) {
  92795. /**
  92796. * Gizmo that enables scaling a mesh along 3 axis
  92797. */
  92798. var ScaleGizmo = /** @class */ (function (_super) {
  92799. __extends(ScaleGizmo, _super);
  92800. /**
  92801. * Creates a ScaleGizmo
  92802. * @param gizmoLayer The utility layer the gizmo will be added to
  92803. */
  92804. function ScaleGizmo(gizmoLayer) {
  92805. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92806. var _this = _super.call(this, gizmoLayer) || this;
  92807. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92808. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92809. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92810. // Create uniform scale gizmo
  92811. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  92812. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92813. _this._uniformGizmo.uniformScaling = true;
  92814. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  92815. octahedron.scaling.scaleInPlace(0.007);
  92816. _this._uniformGizmo.setCustomMesh(octahedron, true);
  92817. _this.attachedMesh = null;
  92818. return _this;
  92819. }
  92820. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  92821. set: function (mesh) {
  92822. if (this.xGizmo) {
  92823. this.xGizmo.attachedMesh = mesh;
  92824. this.yGizmo.attachedMesh = mesh;
  92825. this.zGizmo.attachedMesh = mesh;
  92826. this._uniformGizmo.attachedMesh = mesh;
  92827. }
  92828. },
  92829. enumerable: true,
  92830. configurable: true
  92831. });
  92832. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92833. get: function () {
  92834. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92835. },
  92836. set: function (value) {
  92837. if (this.xGizmo) {
  92838. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92839. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92840. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92841. }
  92842. },
  92843. enumerable: true,
  92844. configurable: true
  92845. });
  92846. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  92847. get: function () {
  92848. return this.xGizmo.snapDistance;
  92849. },
  92850. /**
  92851. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92852. */
  92853. set: function (value) {
  92854. if (this.xGizmo) {
  92855. this.xGizmo.snapDistance = value;
  92856. this.yGizmo.snapDistance = value;
  92857. this.zGizmo.snapDistance = value;
  92858. this._uniformGizmo.snapDistance = value;
  92859. }
  92860. },
  92861. enumerable: true,
  92862. configurable: true
  92863. });
  92864. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  92865. get: function () {
  92866. return this.xGizmo.scaleRatio;
  92867. },
  92868. /**
  92869. * Ratio for the scale of the gizmo (Default: 1)
  92870. */
  92871. set: function (value) {
  92872. if (this.xGizmo) {
  92873. this.xGizmo.scaleRatio = value;
  92874. this.yGizmo.scaleRatio = value;
  92875. this.zGizmo.scaleRatio = value;
  92876. this._uniformGizmo.scaleRatio = value;
  92877. }
  92878. },
  92879. enumerable: true,
  92880. configurable: true
  92881. });
  92882. /**
  92883. * Disposes of the gizmo
  92884. */
  92885. ScaleGizmo.prototype.dispose = function () {
  92886. this.xGizmo.dispose();
  92887. this.yGizmo.dispose();
  92888. this.zGizmo.dispose();
  92889. this._uniformGizmo.dispose();
  92890. };
  92891. return ScaleGizmo;
  92892. }(BABYLON.Gizmo));
  92893. BABYLON.ScaleGizmo = ScaleGizmo;
  92894. })(BABYLON || (BABYLON = {}));
  92895. //# sourceMappingURL=babylon.scaleGizmo.js.map
  92896. var BABYLON;
  92897. (function (BABYLON) {
  92898. /**
  92899. * Bounding box gizmo
  92900. */
  92901. var BoundingBoxGizmo = /** @class */ (function (_super) {
  92902. __extends(BoundingBoxGizmo, _super);
  92903. /**
  92904. * Creates an BoundingBoxGizmo
  92905. * @param gizmoLayer The utility layer the gizmo will be added to
  92906. * @param color The color of the gizmo
  92907. */
  92908. function BoundingBoxGizmo(color, gizmoLayer) {
  92909. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92910. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  92911. var _this = _super.call(this, gizmoLayer) || this;
  92912. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  92913. _this._renderObserver = null;
  92914. _this._pointerObserver = null;
  92915. _this._scaleDragSpeed = 0.2;
  92916. _this._tmpQuaternion = new BABYLON.Quaternion();
  92917. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92918. _this._tmpRotationMatrix = new BABYLON.Matrix();
  92919. /**
  92920. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  92921. */
  92922. _this.ignoreChildren = false;
  92923. /**
  92924. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  92925. */
  92926. _this.rotationSphereSize = 0.1;
  92927. /**
  92928. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  92929. */
  92930. _this.scaleBoxSize = 0.1;
  92931. /**
  92932. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  92933. */
  92934. _this.fixedDragMeshScreenSize = false;
  92935. /**
  92936. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  92937. */
  92938. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  92939. /**
  92940. * Fired when a rotation sphere or scale box is dragged
  92941. */
  92942. _this.onDragStartObservable = new BABYLON.Observable();
  92943. /**
  92944. * Fired when a scale box is dragged
  92945. */
  92946. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  92947. /**
  92948. * Fired when a scale box drag is ended
  92949. */
  92950. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  92951. /**
  92952. * Fired when a rotation sphere is dragged
  92953. */
  92954. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  92955. /**
  92956. * Fired when a rotation sphere drag is ended
  92957. */
  92958. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  92959. /**
  92960. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  92961. */
  92962. _this.scalePivot = null;
  92963. _this._existingMeshScale = new BABYLON.Vector3();
  92964. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  92965. // store/remove pivot point should only be applied during their outermost calls
  92966. _this._pivotCached = 0;
  92967. _this._oldPivotPoint = new BABYLON.Vector3();
  92968. _this._pivotTranslation = new BABYLON.Vector3();
  92969. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  92970. _this._updateScale = false;
  92971. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  92972. // Create Materials
  92973. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92974. coloredMaterial.disableLighting = true;
  92975. coloredMaterial.emissiveColor = color;
  92976. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92977. hoverColoredMaterial.disableLighting = true;
  92978. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92979. // Build bounding box out of lines
  92980. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92981. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  92982. var lines = [];
  92983. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  92984. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  92985. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92986. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  92987. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92988. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  92989. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92990. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92991. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92992. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92993. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92994. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  92995. lines.forEach(function (l) {
  92996. l.color = color;
  92997. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  92998. l.isPickable = false;
  92999. _this._lineBoundingBox.addChild(l);
  93000. });
  93001. _this._rootMesh.addChild(_this._lineBoundingBox);
  93002. // Create rotation spheres
  93003. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93004. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  93005. var _loop_1 = function (i_1) {
  93006. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  93007. sphere.rotationQuaternion = new BABYLON.Quaternion();
  93008. sphere.material = coloredMaterial;
  93009. // Drag behavior
  93010. _dragBehavior = new BABYLON.PointerDragBehavior({});
  93011. _dragBehavior.moveAttached = false;
  93012. _dragBehavior.updateDragPlane = false;
  93013. sphere.addBehavior(_dragBehavior);
  93014. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  93015. var totalTurnAmountOfDrag = 0;
  93016. _dragBehavior.onDragStartObservable.add(function (event) {
  93017. startingTurnDirection.copyFrom(sphere.forward);
  93018. totalTurnAmountOfDrag = 0;
  93019. });
  93020. _dragBehavior.onDragObservable.add(function (event) {
  93021. _this.onRotationSphereDragObservable.notifyObservers({});
  93022. if (_this.attachedMesh) {
  93023. _this._removeAndStorePivotPoint();
  93024. var worldDragDirection = startingTurnDirection;
  93025. // Project the world right on to the drag plane
  93026. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  93027. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  93028. // project drag delta on to the resulting drag axis and rotate based on that
  93029. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  93030. // Make rotation relative to size of mesh.
  93031. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93032. // Rotate based on axis
  93033. if (!_this.attachedMesh.rotationQuaternion) {
  93034. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93035. }
  93036. if (!_this._anchorMesh.rotationQuaternion) {
  93037. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  93038. }
  93039. // Do not allow the object to turn more than a full circle
  93040. totalTurnAmountOfDrag += projectDist;
  93041. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  93042. if (i_1 >= 8) {
  93043. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  93044. }
  93045. else if (i_1 >= 4) {
  93046. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  93047. }
  93048. else {
  93049. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  93050. }
  93051. // Rotate around center of bounding box
  93052. _this._anchorMesh.addChild(_this.attachedMesh);
  93053. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  93054. _this._anchorMesh.removeChild(_this.attachedMesh);
  93055. }
  93056. _this.updateBoundingBox();
  93057. _this._restorePivotPoint();
  93058. }
  93059. });
  93060. // Selection/deselection
  93061. _dragBehavior.onDragStartObservable.add(function () {
  93062. _this.onDragStartObservable.notifyObservers({});
  93063. _this._selectNode(sphere);
  93064. });
  93065. _dragBehavior.onDragEndObservable.add(function () {
  93066. _this.onRotationSphereDragEndObservable.notifyObservers({});
  93067. _this._selectNode(null);
  93068. });
  93069. this_1._rotateSpheresParent.addChild(sphere);
  93070. };
  93071. var this_1 = this, _dragBehavior;
  93072. for (var i_1 = 0; i_1 < 12; i_1++) {
  93073. _loop_1(i_1);
  93074. }
  93075. _this._rootMesh.addChild(_this._rotateSpheresParent);
  93076. // Create scale cubes
  93077. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93078. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  93079. for (var i = 0; i < 2; i++) {
  93080. for (var j = 0; j < 2; j++) {
  93081. var _loop_2 = function () {
  93082. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  93083. box.material = coloredMaterial;
  93084. // Dragging logic
  93085. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  93086. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93087. _dragBehavior.moveAttached = false;
  93088. box.addBehavior(_dragBehavior);
  93089. _dragBehavior.onDragObservable.add(function (event) {
  93090. _this.onScaleBoxDragObservable.notifyObservers({});
  93091. if (_this.attachedMesh) {
  93092. _this._removeAndStorePivotPoint();
  93093. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93094. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  93095. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  93096. _this.updateBoundingBox();
  93097. if (_this.scalePivot) {
  93098. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  93099. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  93100. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  93101. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93102. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93103. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  93104. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93105. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  93106. }
  93107. else {
  93108. // Scale from the position of the opposite corner
  93109. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  93110. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93111. }
  93112. _this._anchorMesh.addChild(_this.attachedMesh);
  93113. _this._anchorMesh.scaling.addInPlace(deltaScale);
  93114. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  93115. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  93116. }
  93117. _this._anchorMesh.removeChild(_this.attachedMesh);
  93118. _this._restorePivotPoint();
  93119. }
  93120. });
  93121. // Selection/deselection
  93122. _dragBehavior.onDragStartObservable.add(function () {
  93123. _this.onDragStartObservable.notifyObservers({});
  93124. _this._selectNode(box);
  93125. });
  93126. _dragBehavior.onDragEndObservable.add(function () {
  93127. _this.onScaleBoxDragEndObservable.notifyObservers({});
  93128. _this._selectNode(null);
  93129. });
  93130. this_2._scaleBoxesParent.addChild(box);
  93131. };
  93132. var this_2 = this, _dragBehavior;
  93133. for (var k = 0; k < 2; k++) {
  93134. _loop_2();
  93135. }
  93136. }
  93137. }
  93138. _this._rootMesh.addChild(_this._scaleBoxesParent);
  93139. // Hover color change
  93140. var pointerIds = new Array();
  93141. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93142. if (!pointerIds[pointerInfo.event.pointerId]) {
  93143. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  93144. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  93145. pointerIds[pointerInfo.event.pointerId] = mesh;
  93146. mesh.material = hoverColoredMaterial;
  93147. }
  93148. });
  93149. }
  93150. else {
  93151. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  93152. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  93153. delete pointerIds[pointerInfo.event.pointerId];
  93154. }
  93155. }
  93156. });
  93157. // Update bounding box positions
  93158. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  93159. // Only update the bouding box if scaling has changed
  93160. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  93161. _this.updateBoundingBox();
  93162. }
  93163. });
  93164. _this.updateBoundingBox();
  93165. return _this;
  93166. }
  93167. BoundingBoxGizmo.prototype._removeAndStorePivotPoint = function () {
  93168. if (this.attachedMesh && this._pivotCached === 0) {
  93169. // Save old pivot and set pivot to 0,0,0
  93170. this.attachedMesh.getPivotPointToRef(this._oldPivotPoint);
  93171. if (this._oldPivotPoint.equalsToFloats(0, 0, 0)) {
  93172. return;
  93173. }
  93174. this.attachedMesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  93175. this._oldPivotPoint.subtractToRef(this.attachedMesh.getPivotPoint(), this._pivotTranslation);
  93176. this._tmpVector.copyFromFloats(1, 1, 1);
  93177. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93178. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93179. this.attachedMesh.position.addInPlace(this._tmpVector);
  93180. }
  93181. this._pivotCached++;
  93182. };
  93183. BoundingBoxGizmo.prototype._restorePivotPoint = function () {
  93184. if (this.attachedMesh && !this._oldPivotPoint.equalsToFloats(0, 0, 0) && this._pivotCached === 1) {
  93185. this.attachedMesh.setPivotPoint(this._oldPivotPoint);
  93186. this._tmpVector.copyFromFloats(1, 1, 1);
  93187. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93188. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93189. this.attachedMesh.position.subtractInPlace(this._tmpVector);
  93190. }
  93191. this._pivotCached--;
  93192. };
  93193. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  93194. if (value) {
  93195. // Reset anchor mesh to match attached mesh's scale
  93196. // This is needed to avoid invalid box/sphere position on first drag
  93197. this._removeAndStorePivotPoint();
  93198. this._anchorMesh.addChild(value);
  93199. this._anchorMesh.removeChild(value);
  93200. this._restorePivotPoint();
  93201. this.updateBoundingBox();
  93202. }
  93203. };
  93204. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  93205. this._rotateSpheresParent.getChildMeshes()
  93206. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  93207. m.isVisible = (!selectedMesh || m == selectedMesh);
  93208. });
  93209. };
  93210. BoundingBoxGizmo.prototype._recurseComputeWorld = function (node) {
  93211. var _this = this;
  93212. node.computeWorldMatrix(true);
  93213. if (!this.ignoreChildren) {
  93214. node.getDescendants().forEach(function (n) {
  93215. _this._recurseComputeWorld(n);
  93216. });
  93217. }
  93218. };
  93219. /**
  93220. * Updates the bounding box information for the Gizmo
  93221. */
  93222. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  93223. if (this.attachedMesh) {
  93224. this._removeAndStorePivotPoint();
  93225. this._update();
  93226. // Rotate based on axis
  93227. if (!this.attachedMesh.rotationQuaternion) {
  93228. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  93229. }
  93230. if (!this._anchorMesh.rotationQuaternion) {
  93231. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  93232. }
  93233. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93234. // Store original position and reset mesh to origin before computing the bounding box
  93235. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93236. this._tmpVector.copyFrom(this.attachedMesh.position);
  93237. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  93238. this.attachedMesh.position.set(0, 0, 0);
  93239. // Update bounding dimensions/positions
  93240. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  93241. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  93242. // Update gizmo to match bounding box scaling and rotation
  93243. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  93244. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93245. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  93246. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  93247. this._lineBoundingBox.computeWorldMatrix();
  93248. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  93249. // restore position/rotation values
  93250. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  93251. this.attachedMesh.position.copyFrom(this._tmpVector);
  93252. this._recurseComputeWorld(this.attachedMesh);
  93253. }
  93254. // Update rotation sphere locations
  93255. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  93256. for (var i = 0; i < 3; i++) {
  93257. for (var j = 0; j < 2; j++) {
  93258. for (var k = 0; k < 2; k++) {
  93259. var index = ((i * 4) + (j * 2)) + k;
  93260. if (i == 0) {
  93261. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93262. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93263. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93264. }
  93265. if (i == 1) {
  93266. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  93267. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93268. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93269. }
  93270. if (i == 2) {
  93271. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  93272. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93273. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93274. }
  93275. if (this.fixedDragMeshScreenSize) {
  93276. this._rootMesh.computeWorldMatrix();
  93277. this._rotateSpheresParent.computeWorldMatrix();
  93278. rotateSpheres[index].computeWorldMatrix();
  93279. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93280. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93281. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93282. }
  93283. else {
  93284. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  93285. }
  93286. }
  93287. }
  93288. }
  93289. // Update scale box locations
  93290. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  93291. for (var i = 0; i < 2; i++) {
  93292. for (var j = 0; j < 2; j++) {
  93293. for (var k = 0; k < 2; k++) {
  93294. var index = ((i * 4) + (j * 2)) + k;
  93295. if (scaleBoxes[index]) {
  93296. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93297. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93298. if (this.fixedDragMeshScreenSize) {
  93299. this._rootMesh.computeWorldMatrix();
  93300. this._scaleBoxesParent.computeWorldMatrix();
  93301. scaleBoxes[index].computeWorldMatrix();
  93302. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93303. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93304. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93305. }
  93306. else {
  93307. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  93308. }
  93309. }
  93310. }
  93311. }
  93312. }
  93313. if (this.attachedMesh) {
  93314. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  93315. this._restorePivotPoint();
  93316. }
  93317. };
  93318. /**
  93319. * Enables rotation on the specified axis and disables rotation on the others
  93320. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  93321. */
  93322. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  93323. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  93324. if (i < 4) {
  93325. m.setEnabled(axis.indexOf("x") != -1);
  93326. }
  93327. else if (i < 8) {
  93328. m.setEnabled(axis.indexOf("y") != -1);
  93329. }
  93330. else {
  93331. m.setEnabled(axis.indexOf("z") != -1);
  93332. }
  93333. });
  93334. };
  93335. /**
  93336. * Disposes of the gizmo
  93337. */
  93338. BoundingBoxGizmo.prototype.dispose = function () {
  93339. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93340. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  93341. this._lineBoundingBox.dispose();
  93342. this._rotateSpheresParent.dispose();
  93343. this._scaleBoxesParent.dispose();
  93344. _super.prototype.dispose.call(this);
  93345. };
  93346. /**
  93347. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  93348. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  93349. * @returns the bounding box mesh with the passed in mesh as a child
  93350. */
  93351. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  93352. var makeNotPickable = function (root) {
  93353. root.isPickable = false;
  93354. root.getChildMeshes().forEach(function (c) {
  93355. makeNotPickable(c);
  93356. });
  93357. };
  93358. makeNotPickable(mesh);
  93359. // Reset position to get boudning box from origin with no rotation
  93360. if (!mesh.rotationQuaternion) {
  93361. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  93362. }
  93363. var oldPos = mesh.position.clone();
  93364. var oldRot = mesh.rotationQuaternion.clone();
  93365. mesh.rotationQuaternion.set(0, 0, 0, 1);
  93366. mesh.position.set(0, 0, 0);
  93367. // Update bounding dimensions/positions
  93368. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  93369. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  93370. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  93371. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93372. // Restore original positions
  93373. mesh.addChild(box);
  93374. mesh.rotationQuaternion.copyFrom(oldRot);
  93375. mesh.position.copyFrom(oldPos);
  93376. // Reverse parenting
  93377. mesh.removeChild(box);
  93378. box.addChild(mesh);
  93379. box.visibility = 0;
  93380. return box;
  93381. };
  93382. /**
  93383. * CustomMeshes are not supported by this gizmo
  93384. * @param mesh The mesh to replace the default mesh of the gizmo
  93385. */
  93386. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  93387. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  93388. };
  93389. return BoundingBoxGizmo;
  93390. }(BABYLON.Gizmo));
  93391. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  93392. })(BABYLON || (BABYLON = {}));
  93393. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  93394. var BABYLON;
  93395. (function (BABYLON) {
  93396. /**
  93397. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  93398. */
  93399. var GizmoManager = /** @class */ (function () {
  93400. /**
  93401. * Instatiates a gizmo manager
  93402. * @param scene the scene to overlay the gizmos on top of
  93403. */
  93404. function GizmoManager(scene) {
  93405. var _this = this;
  93406. this.scene = scene;
  93407. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  93408. this._pointerObserver = null;
  93409. this._attachedMesh = null;
  93410. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  93411. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  93412. /**
  93413. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  93414. */
  93415. this.attachableMeshes = null;
  93416. /**
  93417. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  93418. */
  93419. this.usePointerToAttachGizmos = true;
  93420. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  93421. // Instatiate/dispose gizmos based on pointer actions
  93422. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  93423. if (!_this.usePointerToAttachGizmos) {
  93424. return;
  93425. }
  93426. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93427. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  93428. var node = pointerInfo.pickInfo.pickedMesh;
  93429. if (_this.attachableMeshes == null) {
  93430. // Attach to the most parent node
  93431. while (node && node.parent != null) {
  93432. node = node.parent;
  93433. }
  93434. }
  93435. else {
  93436. // Attach to the parent node that is an attachableMesh
  93437. var found = false;
  93438. _this.attachableMeshes.forEach(function (mesh) {
  93439. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  93440. node = mesh;
  93441. found = true;
  93442. }
  93443. });
  93444. if (!found) {
  93445. node = null;
  93446. }
  93447. }
  93448. if (node instanceof BABYLON.AbstractMesh) {
  93449. _this.attachToMesh(node);
  93450. }
  93451. else {
  93452. _this.attachToMesh(null);
  93453. }
  93454. }
  93455. else {
  93456. _this.attachToMesh(null);
  93457. }
  93458. }
  93459. });
  93460. }
  93461. /**
  93462. * Attaches a set of gizmos to the specified mesh
  93463. * @param mesh The mesh the gizmo's should be attached to
  93464. */
  93465. GizmoManager.prototype.attachToMesh = function (mesh) {
  93466. if (this._attachedMesh) {
  93467. this._attachedMesh.removeBehavior(this._dragBehavior);
  93468. }
  93469. this._attachedMesh = mesh;
  93470. for (var key in this.gizmos) {
  93471. var gizmo = (this.gizmos[key]);
  93472. if (gizmo && this._gizmosEnabled[key]) {
  93473. gizmo.attachedMesh = mesh;
  93474. }
  93475. }
  93476. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  93477. this._attachedMesh.addBehavior(this._dragBehavior);
  93478. }
  93479. };
  93480. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  93481. get: function () {
  93482. return this._gizmosEnabled.positionGizmo;
  93483. },
  93484. /**
  93485. * If the position gizmo is enabled
  93486. */
  93487. set: function (value) {
  93488. if (value) {
  93489. if (!this.gizmos.positionGizmo) {
  93490. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  93491. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93492. }
  93493. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  93494. }
  93495. else if (this.gizmos.positionGizmo) {
  93496. this.gizmos.positionGizmo.attachedMesh = null;
  93497. }
  93498. this._gizmosEnabled.positionGizmo = value;
  93499. },
  93500. enumerable: true,
  93501. configurable: true
  93502. });
  93503. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  93504. get: function () {
  93505. return this._gizmosEnabled.rotationGizmo;
  93506. },
  93507. /**
  93508. * If the rotation gizmo is enabled
  93509. */
  93510. set: function (value) {
  93511. if (value) {
  93512. if (!this.gizmos.rotationGizmo) {
  93513. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  93514. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93515. }
  93516. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  93517. }
  93518. else if (this.gizmos.rotationGizmo) {
  93519. this.gizmos.rotationGizmo.attachedMesh = null;
  93520. }
  93521. this._gizmosEnabled.rotationGizmo = value;
  93522. },
  93523. enumerable: true,
  93524. configurable: true
  93525. });
  93526. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  93527. get: function () {
  93528. return this._gizmosEnabled.scaleGizmo;
  93529. },
  93530. /**
  93531. * If the scale gizmo is enabled
  93532. */
  93533. set: function (value) {
  93534. if (value) {
  93535. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  93536. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  93537. }
  93538. else if (this.gizmos.scaleGizmo) {
  93539. this.gizmos.scaleGizmo.attachedMesh = null;
  93540. }
  93541. this._gizmosEnabled.scaleGizmo = value;
  93542. },
  93543. enumerable: true,
  93544. configurable: true
  93545. });
  93546. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  93547. get: function () {
  93548. return this._gizmosEnabled.boundingBoxGizmo;
  93549. },
  93550. /**
  93551. * If the boundingBox gizmo is enabled
  93552. */
  93553. set: function (value) {
  93554. if (value) {
  93555. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  93556. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  93557. if (this._attachedMesh) {
  93558. this._attachedMesh.removeBehavior(this._dragBehavior);
  93559. this._attachedMesh.addBehavior(this._dragBehavior);
  93560. }
  93561. }
  93562. else if (this.gizmos.boundingBoxGizmo) {
  93563. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  93564. }
  93565. this._gizmosEnabled.boundingBoxGizmo = value;
  93566. },
  93567. enumerable: true,
  93568. configurable: true
  93569. });
  93570. /**
  93571. * Disposes of the gizmo manager
  93572. */
  93573. GizmoManager.prototype.dispose = function () {
  93574. this.scene.onPointerObservable.remove(this._pointerObserver);
  93575. for (var key in this.gizmos) {
  93576. var gizmo = (this.gizmos[key]);
  93577. if (gizmo) {
  93578. gizmo.dispose();
  93579. }
  93580. }
  93581. this._dragBehavior.detach();
  93582. };
  93583. return GizmoManager;
  93584. }());
  93585. BABYLON.GizmoManager = GizmoManager;
  93586. })(BABYLON || (BABYLON = {}));
  93587. //# sourceMappingURL=babylon.gizmoManager.js.map
  93588. var BABYLON;
  93589. (function (BABYLON) {
  93590. /**
  93591. * Defines a target to use with MorphTargetManager
  93592. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93593. */
  93594. var MorphTarget = /** @class */ (function () {
  93595. /**
  93596. * Creates a new MorphTarget
  93597. * @param name defines the name of the target
  93598. * @param influence defines the influence to use
  93599. */
  93600. function MorphTarget(
  93601. /** defines the name of the target */
  93602. name, influence, scene) {
  93603. if (influence === void 0) { influence = 0; }
  93604. if (scene === void 0) { scene = null; }
  93605. this.name = name;
  93606. /**
  93607. * Gets or sets the list of animations
  93608. */
  93609. this.animations = new Array();
  93610. this._positions = null;
  93611. this._normals = null;
  93612. this._tangents = null;
  93613. /**
  93614. * Observable raised when the influence changes
  93615. */
  93616. this.onInfluenceChanged = new BABYLON.Observable();
  93617. this._animationPropertiesOverride = null;
  93618. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93619. this.influence = influence;
  93620. }
  93621. Object.defineProperty(MorphTarget.prototype, "influence", {
  93622. /**
  93623. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  93624. */
  93625. get: function () {
  93626. return this._influence;
  93627. },
  93628. set: function (influence) {
  93629. if (this._influence === influence) {
  93630. return;
  93631. }
  93632. var previous = this._influence;
  93633. this._influence = influence;
  93634. if (this.onInfluenceChanged.hasObservers) {
  93635. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  93636. }
  93637. },
  93638. enumerable: true,
  93639. configurable: true
  93640. });
  93641. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  93642. /**
  93643. * Gets or sets the animation properties override
  93644. */
  93645. get: function () {
  93646. if (!this._animationPropertiesOverride && this._scene) {
  93647. return this._scene.animationPropertiesOverride;
  93648. }
  93649. return this._animationPropertiesOverride;
  93650. },
  93651. set: function (value) {
  93652. this._animationPropertiesOverride = value;
  93653. },
  93654. enumerable: true,
  93655. configurable: true
  93656. });
  93657. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  93658. /**
  93659. * Gets a boolean defining if the target contains position data
  93660. */
  93661. get: function () {
  93662. return !!this._positions;
  93663. },
  93664. enumerable: true,
  93665. configurable: true
  93666. });
  93667. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  93668. /**
  93669. * Gets a boolean defining if the target contains normal data
  93670. */
  93671. get: function () {
  93672. return !!this._normals;
  93673. },
  93674. enumerable: true,
  93675. configurable: true
  93676. });
  93677. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  93678. /**
  93679. * Gets a boolean defining if the target contains tangent data
  93680. */
  93681. get: function () {
  93682. return !!this._tangents;
  93683. },
  93684. enumerable: true,
  93685. configurable: true
  93686. });
  93687. /**
  93688. * Affects position data to this target
  93689. * @param data defines the position data to use
  93690. */
  93691. MorphTarget.prototype.setPositions = function (data) {
  93692. this._positions = data;
  93693. };
  93694. /**
  93695. * Gets the position data stored in this target
  93696. * @returns a FloatArray containing the position data (or null if not present)
  93697. */
  93698. MorphTarget.prototype.getPositions = function () {
  93699. return this._positions;
  93700. };
  93701. /**
  93702. * Affects normal data to this target
  93703. * @param data defines the normal data to use
  93704. */
  93705. MorphTarget.prototype.setNormals = function (data) {
  93706. this._normals = data;
  93707. };
  93708. /**
  93709. * Gets the normal data stored in this target
  93710. * @returns a FloatArray containing the normal data (or null if not present)
  93711. */
  93712. MorphTarget.prototype.getNormals = function () {
  93713. return this._normals;
  93714. };
  93715. /**
  93716. * Affects tangent data to this target
  93717. * @param data defines the tangent data to use
  93718. */
  93719. MorphTarget.prototype.setTangents = function (data) {
  93720. this._tangents = data;
  93721. };
  93722. /**
  93723. * Gets the tangent data stored in this target
  93724. * @returns a FloatArray containing the tangent data (or null if not present)
  93725. */
  93726. MorphTarget.prototype.getTangents = function () {
  93727. return this._tangents;
  93728. };
  93729. /**
  93730. * Serializes the current target into a Serialization object
  93731. * @returns the serialized object
  93732. */
  93733. MorphTarget.prototype.serialize = function () {
  93734. var serializationObject = {};
  93735. serializationObject.name = this.name;
  93736. serializationObject.influence = this.influence;
  93737. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  93738. if (this.hasNormals) {
  93739. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  93740. }
  93741. if (this.hasTangents) {
  93742. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  93743. }
  93744. // Animations
  93745. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  93746. return serializationObject;
  93747. };
  93748. // Statics
  93749. /**
  93750. * Creates a new target from serialized data
  93751. * @param serializationObject defines the serialized data to use
  93752. * @returns a new MorphTarget
  93753. */
  93754. MorphTarget.Parse = function (serializationObject) {
  93755. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  93756. result.setPositions(serializationObject.positions);
  93757. if (serializationObject.normals) {
  93758. result.setNormals(serializationObject.normals);
  93759. }
  93760. if (serializationObject.tangents) {
  93761. result.setTangents(serializationObject.tangents);
  93762. }
  93763. // Animations
  93764. if (serializationObject.animations) {
  93765. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  93766. var parsedAnimation = serializationObject.animations[animationIndex];
  93767. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  93768. }
  93769. }
  93770. return result;
  93771. };
  93772. /**
  93773. * Creates a MorphTarget from mesh data
  93774. * @param mesh defines the source mesh
  93775. * @param name defines the name to use for the new target
  93776. * @param influence defines the influence to attach to the target
  93777. * @returns a new MorphTarget
  93778. */
  93779. MorphTarget.FromMesh = function (mesh, name, influence) {
  93780. if (!name) {
  93781. name = mesh.name;
  93782. }
  93783. var result = new MorphTarget(name, influence, mesh.getScene());
  93784. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93786. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  93787. }
  93788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  93789. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  93790. }
  93791. return result;
  93792. };
  93793. return MorphTarget;
  93794. }());
  93795. BABYLON.MorphTarget = MorphTarget;
  93796. })(BABYLON || (BABYLON = {}));
  93797. //# sourceMappingURL=babylon.morphTarget.js.map
  93798. var BABYLON;
  93799. (function (BABYLON) {
  93800. /**
  93801. * This class is used to deform meshes using morphing between different targets
  93802. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93803. */
  93804. var MorphTargetManager = /** @class */ (function () {
  93805. /**
  93806. * Creates a new MorphTargetManager
  93807. * @param scene defines the current scene
  93808. */
  93809. function MorphTargetManager(scene) {
  93810. if (scene === void 0) { scene = null; }
  93811. this._targets = new Array();
  93812. this._targetObservable = new Array();
  93813. this._activeTargets = new BABYLON.SmartArray(16);
  93814. this._supportsNormals = false;
  93815. this._supportsTangents = false;
  93816. this._vertexCount = 0;
  93817. this._uniqueId = 0;
  93818. this._tempInfluences = new Array();
  93819. if (!scene) {
  93820. scene = BABYLON.Engine.LastCreatedScene;
  93821. }
  93822. this._scene = scene;
  93823. if (this._scene) {
  93824. this._scene.morphTargetManagers.push(this);
  93825. this._uniqueId = this._scene.getUniqueId();
  93826. }
  93827. }
  93828. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  93829. /**
  93830. * Gets the unique ID of this manager
  93831. */
  93832. get: function () {
  93833. return this._uniqueId;
  93834. },
  93835. enumerable: true,
  93836. configurable: true
  93837. });
  93838. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  93839. /**
  93840. * Gets the number of vertices handled by this manager
  93841. */
  93842. get: function () {
  93843. return this._vertexCount;
  93844. },
  93845. enumerable: true,
  93846. configurable: true
  93847. });
  93848. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  93849. /**
  93850. * Gets a boolean indicating if this manager supports morphing of normals
  93851. */
  93852. get: function () {
  93853. return this._supportsNormals;
  93854. },
  93855. enumerable: true,
  93856. configurable: true
  93857. });
  93858. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  93859. /**
  93860. * Gets a boolean indicating if this manager supports morphing of tangents
  93861. */
  93862. get: function () {
  93863. return this._supportsTangents;
  93864. },
  93865. enumerable: true,
  93866. configurable: true
  93867. });
  93868. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  93869. /**
  93870. * Gets the number of targets stored in this manager
  93871. */
  93872. get: function () {
  93873. return this._targets.length;
  93874. },
  93875. enumerable: true,
  93876. configurable: true
  93877. });
  93878. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  93879. /**
  93880. * Gets the number of influencers (ie. the number of targets with influences > 0)
  93881. */
  93882. get: function () {
  93883. return this._activeTargets.length;
  93884. },
  93885. enumerable: true,
  93886. configurable: true
  93887. });
  93888. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  93889. /**
  93890. * Gets the list of influences (one per target)
  93891. */
  93892. get: function () {
  93893. return this._influences;
  93894. },
  93895. enumerable: true,
  93896. configurable: true
  93897. });
  93898. /**
  93899. * Gets the active target at specified index. An active target is a target with an influence > 0
  93900. * @param index defines the index to check
  93901. * @returns the requested target
  93902. */
  93903. MorphTargetManager.prototype.getActiveTarget = function (index) {
  93904. return this._activeTargets.data[index];
  93905. };
  93906. /**
  93907. * Gets the target at specified index
  93908. * @param index defines the index to check
  93909. * @returns the requested target
  93910. */
  93911. MorphTargetManager.prototype.getTarget = function (index) {
  93912. return this._targets[index];
  93913. };
  93914. /**
  93915. * Add a new target to this manager
  93916. * @param target defines the target to add
  93917. */
  93918. MorphTargetManager.prototype.addTarget = function (target) {
  93919. var _this = this;
  93920. this._targets.push(target);
  93921. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  93922. _this._syncActiveTargets(needUpdate);
  93923. }));
  93924. this._syncActiveTargets(true);
  93925. };
  93926. /**
  93927. * Removes a target from the manager
  93928. * @param target defines the target to remove
  93929. */
  93930. MorphTargetManager.prototype.removeTarget = function (target) {
  93931. var index = this._targets.indexOf(target);
  93932. if (index >= 0) {
  93933. this._targets.splice(index, 1);
  93934. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  93935. this._syncActiveTargets(true);
  93936. }
  93937. };
  93938. /**
  93939. * Serializes the current manager into a Serialization object
  93940. * @returns the serialized object
  93941. */
  93942. MorphTargetManager.prototype.serialize = function () {
  93943. var serializationObject = {};
  93944. serializationObject.id = this.uniqueId;
  93945. serializationObject.targets = [];
  93946. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93947. var target = _a[_i];
  93948. serializationObject.targets.push(target.serialize());
  93949. }
  93950. return serializationObject;
  93951. };
  93952. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  93953. var influenceCount = 0;
  93954. this._activeTargets.reset();
  93955. this._supportsNormals = true;
  93956. this._supportsTangents = true;
  93957. this._vertexCount = 0;
  93958. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93959. var target = _a[_i];
  93960. this._activeTargets.push(target);
  93961. this._tempInfluences[influenceCount++] = target.influence;
  93962. var positions = target.getPositions();
  93963. if (positions) {
  93964. this._supportsNormals = this._supportsNormals && target.hasNormals;
  93965. this._supportsTangents = this._supportsTangents && target.hasTangents;
  93966. var vertexCount = positions.length / 3;
  93967. if (this._vertexCount === 0) {
  93968. this._vertexCount = vertexCount;
  93969. }
  93970. else if (this._vertexCount !== vertexCount) {
  93971. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  93972. return;
  93973. }
  93974. }
  93975. }
  93976. if (!this._influences || this._influences.length !== influenceCount) {
  93977. this._influences = new Float32Array(influenceCount);
  93978. }
  93979. for (var index = 0; index < influenceCount; index++) {
  93980. this._influences[index] = this._tempInfluences[index];
  93981. }
  93982. if (needUpdate) {
  93983. this.synchronize();
  93984. }
  93985. };
  93986. /**
  93987. * Syncrhonize the targets with all the meshes using this morph target manager
  93988. */
  93989. MorphTargetManager.prototype.synchronize = function () {
  93990. if (!this._scene) {
  93991. return;
  93992. }
  93993. // Flag meshes as dirty to resync with the active targets
  93994. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  93995. var mesh = _a[_i];
  93996. if (mesh.morphTargetManager === this) {
  93997. mesh._syncGeometryWithMorphTargetManager();
  93998. }
  93999. }
  94000. };
  94001. // Statics
  94002. /**
  94003. * Creates a new MorphTargetManager from serialized data
  94004. * @param serializationObject defines the serialized data
  94005. * @param scene defines the hosting scene
  94006. * @returns the new MorphTargetManager
  94007. */
  94008. MorphTargetManager.Parse = function (serializationObject, scene) {
  94009. var result = new MorphTargetManager(scene);
  94010. result._uniqueId = serializationObject.id;
  94011. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  94012. var targetData = _a[_i];
  94013. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  94014. }
  94015. return result;
  94016. };
  94017. return MorphTargetManager;
  94018. }());
  94019. BABYLON.MorphTargetManager = MorphTargetManager;
  94020. })(BABYLON || (BABYLON = {}));
  94021. //# sourceMappingURL=babylon.morphTargetManager.js.map
  94022. var BABYLON;
  94023. (function (BABYLON) {
  94024. var Octree = /** @class */ (function () {
  94025. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  94026. if (maxDepth === void 0) { maxDepth = 2; }
  94027. this.maxDepth = maxDepth;
  94028. this.dynamicContent = new Array();
  94029. this._maxBlockCapacity = maxBlockCapacity || 64;
  94030. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  94031. this._creationFunc = creationFunc;
  94032. }
  94033. // Methods
  94034. Octree.prototype.update = function (worldMin, worldMax, entries) {
  94035. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  94036. };
  94037. Octree.prototype.addMesh = function (entry) {
  94038. for (var index = 0; index < this.blocks.length; index++) {
  94039. var block = this.blocks[index];
  94040. block.addEntry(entry);
  94041. }
  94042. };
  94043. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  94044. this._selectionContent.reset();
  94045. for (var index = 0; index < this.blocks.length; index++) {
  94046. var block = this.blocks[index];
  94047. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  94048. }
  94049. if (allowDuplicate) {
  94050. this._selectionContent.concat(this.dynamicContent);
  94051. }
  94052. else {
  94053. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94054. }
  94055. return this._selectionContent;
  94056. };
  94057. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  94058. this._selectionContent.reset();
  94059. for (var index = 0; index < this.blocks.length; index++) {
  94060. var block = this.blocks[index];
  94061. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  94062. }
  94063. if (allowDuplicate) {
  94064. this._selectionContent.concat(this.dynamicContent);
  94065. }
  94066. else {
  94067. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94068. }
  94069. return this._selectionContent;
  94070. };
  94071. Octree.prototype.intersectsRay = function (ray) {
  94072. this._selectionContent.reset();
  94073. for (var index = 0; index < this.blocks.length; index++) {
  94074. var block = this.blocks[index];
  94075. block.intersectsRay(ray, this._selectionContent);
  94076. }
  94077. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94078. return this._selectionContent;
  94079. };
  94080. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  94081. target.blocks = new Array();
  94082. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  94083. // Segmenting space
  94084. for (var x = 0; x < 2; x++) {
  94085. for (var y = 0; y < 2; y++) {
  94086. for (var z = 0; z < 2; z++) {
  94087. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  94088. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  94089. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  94090. block.addEntries(entries);
  94091. target.blocks.push(block);
  94092. }
  94093. }
  94094. }
  94095. };
  94096. Octree.CreationFuncForMeshes = function (entry, block) {
  94097. var boundingInfo = entry.getBoundingInfo();
  94098. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94099. block.entries.push(entry);
  94100. }
  94101. };
  94102. Octree.CreationFuncForSubMeshes = function (entry, block) {
  94103. var boundingInfo = entry.getBoundingInfo();
  94104. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94105. block.entries.push(entry);
  94106. }
  94107. };
  94108. return Octree;
  94109. }());
  94110. BABYLON.Octree = Octree;
  94111. })(BABYLON || (BABYLON = {}));
  94112. //# sourceMappingURL=babylon.octree.js.map
  94113. var BABYLON;
  94114. (function (BABYLON) {
  94115. var OctreeBlock = /** @class */ (function () {
  94116. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  94117. this.entries = new Array();
  94118. this._boundingVectors = new Array();
  94119. this._capacity = capacity;
  94120. this._depth = depth;
  94121. this._maxDepth = maxDepth;
  94122. this._creationFunc = creationFunc;
  94123. this._minPoint = minPoint;
  94124. this._maxPoint = maxPoint;
  94125. this._boundingVectors.push(minPoint.clone());
  94126. this._boundingVectors.push(maxPoint.clone());
  94127. this._boundingVectors.push(minPoint.clone());
  94128. this._boundingVectors[2].x = maxPoint.x;
  94129. this._boundingVectors.push(minPoint.clone());
  94130. this._boundingVectors[3].y = maxPoint.y;
  94131. this._boundingVectors.push(minPoint.clone());
  94132. this._boundingVectors[4].z = maxPoint.z;
  94133. this._boundingVectors.push(maxPoint.clone());
  94134. this._boundingVectors[5].z = minPoint.z;
  94135. this._boundingVectors.push(maxPoint.clone());
  94136. this._boundingVectors[6].x = minPoint.x;
  94137. this._boundingVectors.push(maxPoint.clone());
  94138. this._boundingVectors[7].y = minPoint.y;
  94139. }
  94140. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  94141. // Property
  94142. get: function () {
  94143. return this._capacity;
  94144. },
  94145. enumerable: true,
  94146. configurable: true
  94147. });
  94148. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  94149. get: function () {
  94150. return this._minPoint;
  94151. },
  94152. enumerable: true,
  94153. configurable: true
  94154. });
  94155. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  94156. get: function () {
  94157. return this._maxPoint;
  94158. },
  94159. enumerable: true,
  94160. configurable: true
  94161. });
  94162. // Methods
  94163. OctreeBlock.prototype.addEntry = function (entry) {
  94164. if (this.blocks) {
  94165. for (var index = 0; index < this.blocks.length; index++) {
  94166. var block = this.blocks[index];
  94167. block.addEntry(entry);
  94168. }
  94169. return;
  94170. }
  94171. this._creationFunc(entry, this);
  94172. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  94173. this.createInnerBlocks();
  94174. }
  94175. };
  94176. OctreeBlock.prototype.addEntries = function (entries) {
  94177. for (var index = 0; index < entries.length; index++) {
  94178. var mesh = entries[index];
  94179. this.addEntry(mesh);
  94180. }
  94181. };
  94182. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  94183. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  94184. if (this.blocks) {
  94185. for (var index = 0; index < this.blocks.length; index++) {
  94186. var block = this.blocks[index];
  94187. block.select(frustumPlanes, selection, allowDuplicate);
  94188. }
  94189. return;
  94190. }
  94191. if (allowDuplicate) {
  94192. selection.concat(this.entries);
  94193. }
  94194. else {
  94195. selection.concatWithNoDuplicate(this.entries);
  94196. }
  94197. }
  94198. };
  94199. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  94200. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  94201. if (this.blocks) {
  94202. for (var index = 0; index < this.blocks.length; index++) {
  94203. var block = this.blocks[index];
  94204. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  94205. }
  94206. return;
  94207. }
  94208. if (allowDuplicate) {
  94209. selection.concat(this.entries);
  94210. }
  94211. else {
  94212. selection.concatWithNoDuplicate(this.entries);
  94213. }
  94214. }
  94215. };
  94216. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  94217. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  94218. if (this.blocks) {
  94219. for (var index = 0; index < this.blocks.length; index++) {
  94220. var block = this.blocks[index];
  94221. block.intersectsRay(ray, selection);
  94222. }
  94223. return;
  94224. }
  94225. selection.concatWithNoDuplicate(this.entries);
  94226. }
  94227. };
  94228. OctreeBlock.prototype.createInnerBlocks = function () {
  94229. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  94230. };
  94231. return OctreeBlock;
  94232. }());
  94233. BABYLON.OctreeBlock = OctreeBlock;
  94234. })(BABYLON || (BABYLON = {}));
  94235. //# sourceMappingURL=babylon.octreeBlock.js.map
  94236. var BABYLON;
  94237. (function (BABYLON) {
  94238. /**
  94239. * Postprocess used to generate anaglyphic rendering
  94240. */
  94241. var AnaglyphPostProcess = /** @class */ (function (_super) {
  94242. __extends(AnaglyphPostProcess, _super);
  94243. /**
  94244. * Creates a new AnaglyphPostProcess
  94245. * @param name defines postprocess name
  94246. * @param options defines creation options or target ratio scale
  94247. * @param rigCameras defines cameras using this postprocess
  94248. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  94249. * @param engine defines hosting engine
  94250. * @param reusable defines if the postprocess will be reused multiple times per frame
  94251. */
  94252. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  94253. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  94254. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94255. _this.onApplyObservable.add(function (effect) {
  94256. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  94257. });
  94258. return _this;
  94259. }
  94260. return AnaglyphPostProcess;
  94261. }(BABYLON.PostProcess));
  94262. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  94263. })(BABYLON || (BABYLON = {}));
  94264. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  94265. var BABYLON;
  94266. (function (BABYLON) {
  94267. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  94268. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94269. });
  94270. /**
  94271. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  94272. */
  94273. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  94274. __extends(AnaglyphArcRotateCamera, _super);
  94275. /**
  94276. * Creates a new AnaglyphArcRotateCamera
  94277. * @param name defines camera name
  94278. * @param alpha defines alpha angle (in radians)
  94279. * @param beta defines beta angle (in radians)
  94280. * @param radius defines radius
  94281. * @param target defines camera target
  94282. * @param interaxialDistance defines distance between each color axis
  94283. * @param scene defines the hosting scene
  94284. */
  94285. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  94286. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94287. _this.interaxialDistance = interaxialDistance;
  94288. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94289. return _this;
  94290. }
  94291. /**
  94292. * Gets camera class name
  94293. * @returns AnaglyphArcRotateCamera
  94294. */
  94295. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  94296. return "AnaglyphArcRotateCamera";
  94297. };
  94298. return AnaglyphArcRotateCamera;
  94299. }(BABYLON.ArcRotateCamera));
  94300. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  94301. })(BABYLON || (BABYLON = {}));
  94302. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  94303. var BABYLON;
  94304. (function (BABYLON) {
  94305. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  94306. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94307. });
  94308. /**
  94309. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  94310. */
  94311. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  94312. __extends(AnaglyphFreeCamera, _super);
  94313. /**
  94314. * Creates a new AnaglyphFreeCamera
  94315. * @param name defines camera name
  94316. * @param position defines initial position
  94317. * @param interaxialDistance defines distance between each color axis
  94318. * @param scene defines the hosting scene
  94319. */
  94320. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  94321. var _this = _super.call(this, name, position, scene) || this;
  94322. _this.interaxialDistance = interaxialDistance;
  94323. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94324. return _this;
  94325. }
  94326. /**
  94327. * Gets camera class name
  94328. * @returns AnaglyphFreeCamera
  94329. */
  94330. AnaglyphFreeCamera.prototype.getClassName = function () {
  94331. return "AnaglyphFreeCamera";
  94332. };
  94333. return AnaglyphFreeCamera;
  94334. }(BABYLON.FreeCamera));
  94335. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  94336. })(BABYLON || (BABYLON = {}));
  94337. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  94338. var BABYLON;
  94339. (function (BABYLON) {
  94340. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  94341. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94342. });
  94343. /**
  94344. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  94345. */
  94346. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  94347. __extends(AnaglyphGamepadCamera, _super);
  94348. /**
  94349. * Creates a new AnaglyphGamepadCamera
  94350. * @param name defines camera name
  94351. * @param position defines initial position
  94352. * @param interaxialDistance defines distance between each color axis
  94353. * @param scene defines the hosting scene
  94354. */
  94355. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  94356. var _this = _super.call(this, name, position, scene) || this;
  94357. _this.interaxialDistance = interaxialDistance;
  94358. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94359. return _this;
  94360. }
  94361. /**
  94362. * Gets camera class name
  94363. * @returns AnaglyphGamepadCamera
  94364. */
  94365. AnaglyphGamepadCamera.prototype.getClassName = function () {
  94366. return "AnaglyphGamepadCamera";
  94367. };
  94368. return AnaglyphGamepadCamera;
  94369. }(BABYLON.GamepadCamera));
  94370. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  94371. })(BABYLON || (BABYLON = {}));
  94372. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  94373. var BABYLON;
  94374. (function (BABYLON) {
  94375. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  94376. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94377. });
  94378. /**
  94379. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  94380. */
  94381. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  94382. __extends(AnaglyphUniversalCamera, _super);
  94383. /**
  94384. * Creates a new AnaglyphUniversalCamera
  94385. * @param name defines camera name
  94386. * @param position defines initial position
  94387. * @param interaxialDistance defines distance between each color axis
  94388. * @param scene defines the hosting scene
  94389. */
  94390. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  94391. var _this = _super.call(this, name, position, scene) || this;
  94392. _this.interaxialDistance = interaxialDistance;
  94393. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94394. return _this;
  94395. }
  94396. /**
  94397. * Gets camera class name
  94398. * @returns AnaglyphUniversalCamera
  94399. */
  94400. AnaglyphUniversalCamera.prototype.getClassName = function () {
  94401. return "AnaglyphUniversalCamera";
  94402. };
  94403. return AnaglyphUniversalCamera;
  94404. }(BABYLON.UniversalCamera));
  94405. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  94406. })(BABYLON || (BABYLON = {}));
  94407. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  94408. var BABYLON;
  94409. (function (BABYLON) {
  94410. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  94411. __extends(StereoscopicInterlacePostProcess, _super);
  94412. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  94413. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  94414. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94415. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94416. _this.onSizeChangedObservable.add(function () {
  94417. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94418. });
  94419. _this.onApplyObservable.add(function (effect) {
  94420. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  94421. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  94422. });
  94423. return _this;
  94424. }
  94425. return StereoscopicInterlacePostProcess;
  94426. }(BABYLON.PostProcess));
  94427. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  94428. })(BABYLON || (BABYLON = {}));
  94429. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  94430. var BABYLON;
  94431. (function (BABYLON) {
  94432. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  94433. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94434. });
  94435. /**
  94436. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  94437. */
  94438. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  94439. __extends(StereoscopicArcRotateCamera, _super);
  94440. /**
  94441. * Creates a new StereoscopicArcRotateCamera
  94442. * @param name defines camera name
  94443. * @param alpha defines alpha angle (in radians)
  94444. * @param beta defines beta angle (in radians)
  94445. * @param radius defines radius
  94446. * @param target defines camera target
  94447. * @param interaxialDistance defines distance between each color axis
  94448. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94449. * @param scene defines the hosting scene
  94450. */
  94451. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  94452. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94453. _this.interaxialDistance = interaxialDistance;
  94454. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94455. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94456. return _this;
  94457. }
  94458. /**
  94459. * Gets camera class name
  94460. * @returns StereoscopicArcRotateCamera
  94461. */
  94462. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  94463. return "StereoscopicArcRotateCamera";
  94464. };
  94465. return StereoscopicArcRotateCamera;
  94466. }(BABYLON.ArcRotateCamera));
  94467. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  94468. })(BABYLON || (BABYLON = {}));
  94469. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  94470. var BABYLON;
  94471. (function (BABYLON) {
  94472. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94473. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94474. });
  94475. /**
  94476. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  94477. */
  94478. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  94479. __extends(StereoscopicFreeCamera, _super);
  94480. /**
  94481. * Creates a new StereoscopicFreeCamera
  94482. * @param name defines camera name
  94483. * @param position defines initial position
  94484. * @param interaxialDistance defines distance between each color axis
  94485. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94486. * @param scene defines the hosting scene
  94487. */
  94488. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94489. var _this = _super.call(this, name, position, scene) || this;
  94490. _this.interaxialDistance = interaxialDistance;
  94491. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94492. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94493. return _this;
  94494. }
  94495. /**
  94496. * Gets camera class name
  94497. * @returns StereoscopicFreeCamera
  94498. */
  94499. StereoscopicFreeCamera.prototype.getClassName = function () {
  94500. return "StereoscopicFreeCamera";
  94501. };
  94502. return StereoscopicFreeCamera;
  94503. }(BABYLON.FreeCamera));
  94504. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  94505. })(BABYLON || (BABYLON = {}));
  94506. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  94507. var BABYLON;
  94508. (function (BABYLON) {
  94509. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  94510. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94511. });
  94512. /**
  94513. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  94514. */
  94515. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  94516. __extends(StereoscopicGamepadCamera, _super);
  94517. /**
  94518. * Creates a new StereoscopicGamepadCamera
  94519. * @param name defines camera name
  94520. * @param position defines initial position
  94521. * @param interaxialDistance defines distance between each color axis
  94522. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94523. * @param scene defines the hosting scene
  94524. */
  94525. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94526. var _this = _super.call(this, name, position, scene) || this;
  94527. _this.interaxialDistance = interaxialDistance;
  94528. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94529. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94530. return _this;
  94531. }
  94532. /**
  94533. * Gets camera class name
  94534. * @returns StereoscopicGamepadCamera
  94535. */
  94536. StereoscopicGamepadCamera.prototype.getClassName = function () {
  94537. return "StereoscopicGamepadCamera";
  94538. };
  94539. return StereoscopicGamepadCamera;
  94540. }(BABYLON.GamepadCamera));
  94541. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  94542. })(BABYLON || (BABYLON = {}));
  94543. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  94544. var BABYLON;
  94545. (function (BABYLON) {
  94546. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94547. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94548. });
  94549. /**
  94550. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  94551. */
  94552. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  94553. __extends(StereoscopicUniversalCamera, _super);
  94554. /**
  94555. * Creates a new StereoscopicUniversalCamera
  94556. * @param name defines camera name
  94557. * @param position defines initial position
  94558. * @param interaxialDistance defines distance between each color axis
  94559. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94560. * @param scene defines the hosting scene
  94561. */
  94562. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94563. var _this = _super.call(this, name, position, scene) || this;
  94564. _this.interaxialDistance = interaxialDistance;
  94565. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94566. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94567. return _this;
  94568. }
  94569. /**
  94570. * Gets camera class name
  94571. * @returns StereoscopicUniversalCamera
  94572. */
  94573. StereoscopicUniversalCamera.prototype.getClassName = function () {
  94574. return "StereoscopicUniversalCamera";
  94575. };
  94576. return StereoscopicUniversalCamera;
  94577. }(BABYLON.UniversalCamera));
  94578. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  94579. })(BABYLON || (BABYLON = {}));
  94580. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  94581. var BABYLON;
  94582. (function (BABYLON) {
  94583. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  94584. __extends(VRDistortionCorrectionPostProcess, _super);
  94585. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  94586. var _this = _super.call(this, name, "vrDistortionCorrection", [
  94587. 'LensCenter',
  94588. 'Scale',
  94589. 'ScaleIn',
  94590. 'HmdWarpParam'
  94591. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  94592. _this._isRightEye = isRightEye;
  94593. _this._distortionFactors = vrMetrics.distortionK;
  94594. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  94595. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  94596. _this.adaptScaleToCurrentViewport = true;
  94597. _this.onSizeChangedObservable.add(function () {
  94598. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  94599. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  94600. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  94601. });
  94602. _this.onApplyObservable.add(function (effect) {
  94603. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  94604. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  94605. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  94606. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  94607. });
  94608. return _this;
  94609. }
  94610. return VRDistortionCorrectionPostProcess;
  94611. }(BABYLON.PostProcess));
  94612. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  94613. })(BABYLON || (BABYLON = {}));
  94614. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  94615. var BABYLON;
  94616. (function (BABYLON) {
  94617. /**
  94618. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  94619. * Screen rotation is taken into account.
  94620. */
  94621. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  94622. function FreeCameraDeviceOrientationInput() {
  94623. var _this = this;
  94624. this._screenOrientationAngle = 0;
  94625. this._screenQuaternion = new BABYLON.Quaternion();
  94626. this._alpha = 0;
  94627. this._beta = 0;
  94628. this._gamma = 0;
  94629. this._orientationChanged = function () {
  94630. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  94631. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  94632. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  94633. };
  94634. this._deviceOrientation = function (evt) {
  94635. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  94636. _this._beta = evt.beta !== null ? evt.beta : 0;
  94637. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  94638. };
  94639. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  94640. this._orientationChanged();
  94641. }
  94642. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  94643. get: function () {
  94644. return this._camera;
  94645. },
  94646. set: function (camera) {
  94647. this._camera = camera;
  94648. if (this._camera != null && !this._camera.rotationQuaternion) {
  94649. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  94650. }
  94651. },
  94652. enumerable: true,
  94653. configurable: true
  94654. });
  94655. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94656. window.addEventListener("orientationchange", this._orientationChanged);
  94657. window.addEventListener("deviceorientation", this._deviceOrientation);
  94658. //In certain cases, the attach control is called AFTER orientation was changed,
  94659. //So this is needed.
  94660. this._orientationChanged();
  94661. };
  94662. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  94663. window.removeEventListener("orientationchange", this._orientationChanged);
  94664. window.removeEventListener("deviceorientation", this._deviceOrientation);
  94665. };
  94666. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  94667. //if no device orientation provided, don't update the rotation.
  94668. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  94669. if (!this._alpha)
  94670. return;
  94671. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  94672. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  94673. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  94674. //Mirror on XY Plane
  94675. this._camera.rotationQuaternion.z *= -1;
  94676. this._camera.rotationQuaternion.w *= -1;
  94677. };
  94678. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  94679. return "FreeCameraDeviceOrientationInput";
  94680. };
  94681. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  94682. return "deviceOrientation";
  94683. };
  94684. return FreeCameraDeviceOrientationInput;
  94685. }());
  94686. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  94687. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  94688. })(BABYLON || (BABYLON = {}));
  94689. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  94690. var BABYLON;
  94691. (function (BABYLON) {
  94692. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  94693. function ArcRotateCameraVRDeviceOrientationInput() {
  94694. this.alphaCorrection = 1;
  94695. this.betaCorrection = 1;
  94696. this.gammaCorrection = 1;
  94697. this._alpha = 0;
  94698. this._gamma = 0;
  94699. this._dirty = false;
  94700. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  94701. }
  94702. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94703. this.camera.attachControl(element, noPreventDefault);
  94704. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  94705. };
  94706. /** @hidden */
  94707. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  94708. if (evt.alpha !== null) {
  94709. this._alpha = +evt.alpha | 0;
  94710. }
  94711. if (evt.gamma !== null) {
  94712. this._gamma = +evt.gamma | 0;
  94713. }
  94714. this._dirty = true;
  94715. };
  94716. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  94717. if (this._dirty) {
  94718. this._dirty = false;
  94719. if (this._gamma < 0) {
  94720. this._gamma = 180 + this._gamma;
  94721. }
  94722. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  94723. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  94724. }
  94725. };
  94726. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  94727. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  94728. };
  94729. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  94730. return "ArcRotateCameraVRDeviceOrientationInput";
  94731. };
  94732. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  94733. return "VRDeviceOrientation";
  94734. };
  94735. return ArcRotateCameraVRDeviceOrientationInput;
  94736. }());
  94737. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  94738. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  94739. })(BABYLON || (BABYLON = {}));
  94740. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  94741. var BABYLON;
  94742. (function (BABYLON) {
  94743. var VRCameraMetrics = /** @class */ (function () {
  94744. function VRCameraMetrics() {
  94745. this.compensateDistortion = true;
  94746. }
  94747. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  94748. get: function () {
  94749. return this.hResolution / (2 * this.vResolution);
  94750. },
  94751. enumerable: true,
  94752. configurable: true
  94753. });
  94754. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  94755. get: function () {
  94756. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  94757. },
  94758. enumerable: true,
  94759. configurable: true
  94760. });
  94761. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  94762. get: function () {
  94763. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94764. var h = (4 * meters) / this.hScreenSize;
  94765. return BABYLON.Matrix.Translation(h, 0, 0);
  94766. },
  94767. enumerable: true,
  94768. configurable: true
  94769. });
  94770. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  94771. get: function () {
  94772. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94773. var h = (4 * meters) / this.hScreenSize;
  94774. return BABYLON.Matrix.Translation(-h, 0, 0);
  94775. },
  94776. enumerable: true,
  94777. configurable: true
  94778. });
  94779. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  94780. get: function () {
  94781. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  94782. },
  94783. enumerable: true,
  94784. configurable: true
  94785. });
  94786. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  94787. get: function () {
  94788. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  94789. },
  94790. enumerable: true,
  94791. configurable: true
  94792. });
  94793. VRCameraMetrics.GetDefault = function () {
  94794. var result = new VRCameraMetrics();
  94795. result.hResolution = 1280;
  94796. result.vResolution = 800;
  94797. result.hScreenSize = 0.149759993;
  94798. result.vScreenSize = 0.0935999975;
  94799. result.vScreenCenter = 0.0467999987;
  94800. result.eyeToScreenDistance = 0.0410000011;
  94801. result.lensSeparationDistance = 0.0635000020;
  94802. result.interpupillaryDistance = 0.0640000030;
  94803. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  94804. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  94805. result.postProcessScaleFactor = 1.714605507808412;
  94806. result.lensCenterOffset = 0.151976421;
  94807. return result;
  94808. };
  94809. return VRCameraMetrics;
  94810. }());
  94811. BABYLON.VRCameraMetrics = VRCameraMetrics;
  94812. })(BABYLON || (BABYLON = {}));
  94813. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  94814. var BABYLON;
  94815. (function (BABYLON) {
  94816. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  94817. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94818. });
  94819. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  94820. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94821. });
  94822. /**
  94823. * This represents a WebVR camera.
  94824. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  94825. * @example http://doc.babylonjs.com/how_to/webvr_camera
  94826. */
  94827. var WebVRFreeCamera = /** @class */ (function (_super) {
  94828. __extends(WebVRFreeCamera, _super);
  94829. /**
  94830. * Instantiates a WebVRFreeCamera.
  94831. * @param name The name of the WebVRFreeCamera
  94832. * @param position The starting anchor position for the camera
  94833. * @param scene The scene the camera belongs to
  94834. * @param webVROptions a set of customizable options for the webVRCamera
  94835. */
  94836. function WebVRFreeCamera(name, position, scene, webVROptions) {
  94837. if (webVROptions === void 0) { webVROptions = {}; }
  94838. var _this = _super.call(this, name, position, scene) || this;
  94839. _this.webVROptions = webVROptions;
  94840. /**
  94841. * @hidden
  94842. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  94843. */
  94844. _this._vrDevice = null;
  94845. /**
  94846. * The rawPose of the vrDevice.
  94847. */
  94848. _this.rawPose = null;
  94849. _this._specsVersion = "1.1";
  94850. _this._attached = false;
  94851. _this._descendants = [];
  94852. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  94853. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  94854. /** @hidden */
  94855. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  94856. _this._standingMatrix = null;
  94857. /**
  94858. * Represents device position in babylon space.
  94859. */
  94860. _this.devicePosition = BABYLON.Vector3.Zero();
  94861. /**
  94862. * Represents device rotation in babylon space.
  94863. */
  94864. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  94865. /**
  94866. * The scale of the device to be used when translating from device space to babylon space.
  94867. */
  94868. _this.deviceScaleFactor = 1;
  94869. _this._deviceToWorld = BABYLON.Matrix.Identity();
  94870. _this._worldToDevice = BABYLON.Matrix.Identity();
  94871. /**
  94872. * References to the webVR controllers for the vrDevice.
  94873. */
  94874. _this.controllers = [];
  94875. /**
  94876. * Emits an event when a controller is attached.
  94877. */
  94878. _this.onControllersAttachedObservable = new BABYLON.Observable();
  94879. /**
  94880. * Emits an event when a controller's mesh has been loaded;
  94881. */
  94882. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94883. /**
  94884. * Emits an event when the HMD's pose has been updated.
  94885. */
  94886. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  94887. _this._poseSet = false;
  94888. /**
  94889. * If the rig cameras be used as parent instead of this camera.
  94890. */
  94891. _this.rigParenting = true;
  94892. _this._defaultHeight = undefined;
  94893. _this._htmlElementAttached = null;
  94894. _this._detachIfAttached = function () {
  94895. var vrDisplay = _this.getEngine().getVRDevice();
  94896. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  94897. _this.detachControl(_this._htmlElementAttached);
  94898. }
  94899. };
  94900. _this._workingVector = BABYLON.Vector3.Zero();
  94901. _this._oneVector = BABYLON.Vector3.One();
  94902. _this._workingMatrix = BABYLON.Matrix.Identity();
  94903. _this._cache.position = BABYLON.Vector3.Zero();
  94904. if (webVROptions.defaultHeight) {
  94905. _this._defaultHeight = webVROptions.defaultHeight;
  94906. _this.position.y = _this._defaultHeight;
  94907. }
  94908. _this.minZ = 0.1;
  94909. //legacy support - the compensation boolean was removed.
  94910. if (arguments.length === 5) {
  94911. _this.webVROptions = arguments[4];
  94912. }
  94913. // default webVR options
  94914. if (_this.webVROptions.trackPosition == undefined) {
  94915. _this.webVROptions.trackPosition = true;
  94916. }
  94917. if (_this.webVROptions.controllerMeshes == undefined) {
  94918. _this.webVROptions.controllerMeshes = true;
  94919. }
  94920. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  94921. _this.webVROptions.defaultLightingOnControllers = true;
  94922. }
  94923. _this.rotationQuaternion = new BABYLON.Quaternion();
  94924. if (_this.webVROptions && _this.webVROptions.positionScale) {
  94925. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  94926. }
  94927. //enable VR
  94928. var engine = _this.getEngine();
  94929. _this._onVREnabled = function (success) { if (success) {
  94930. _this.initControllers();
  94931. } };
  94932. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  94933. engine.initWebVR().add(function (event) {
  94934. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  94935. return;
  94936. }
  94937. _this._vrDevice = event.vrDisplay;
  94938. //reset the rig parameters.
  94939. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  94940. if (_this._attached) {
  94941. _this.getEngine().enableVR();
  94942. }
  94943. });
  94944. if (typeof (VRFrameData) !== "undefined")
  94945. _this._frameData = new VRFrameData();
  94946. /**
  94947. * The idea behind the following lines:
  94948. * objects that have the camera as parent should actually have the rig cameras as a parent.
  94949. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  94950. * the second will not show it correctly.
  94951. *
  94952. * To solve this - each object that has the camera as parent will be added to a protected array.
  94953. * When the rig camera renders, it will take this array and set all of those to be its children.
  94954. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  94955. * Amazing!
  94956. */
  94957. scene.onBeforeCameraRenderObservable.add(function (camera) {
  94958. if (camera.parent === _this && _this.rigParenting) {
  94959. _this._descendants = _this.getDescendants(true, function (n) {
  94960. // don't take the cameras or the controllers!
  94961. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  94962. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  94963. return !isController && !isRigCamera;
  94964. });
  94965. _this._descendants.forEach(function (node) {
  94966. node.parent = camera;
  94967. });
  94968. }
  94969. });
  94970. scene.onAfterCameraRenderObservable.add(function (camera) {
  94971. if (camera.parent === _this && _this.rigParenting) {
  94972. _this._descendants.forEach(function (node) {
  94973. node.parent = _this;
  94974. });
  94975. }
  94976. });
  94977. return _this;
  94978. }
  94979. /**
  94980. * Gets the device distance from the ground in meters.
  94981. * @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.
  94982. */
  94983. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  94984. if (this._standingMatrix) {
  94985. // Add standing matrix offset to get real offset from ground in room
  94986. this._standingMatrix.getTranslationToRef(this._workingVector);
  94987. return this._deviceRoomPosition.y + this._workingVector.y;
  94988. }
  94989. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  94990. return this._defaultHeight || 0;
  94991. };
  94992. /**
  94993. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  94994. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  94995. */
  94996. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  94997. var _this = this;
  94998. if (callback === void 0) { callback = function (bool) { }; }
  94999. // Use standing matrix if available
  95000. this.getEngine().initWebVRAsync().then(function (result) {
  95001. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  95002. callback(false);
  95003. }
  95004. else {
  95005. _this._standingMatrix = new BABYLON.Matrix();
  95006. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  95007. if (!_this.getScene().useRightHandedSystem) {
  95008. [2, 6, 8, 9, 14].forEach(function (num) {
  95009. if (_this._standingMatrix) {
  95010. _this._standingMatrix.m[num] *= -1;
  95011. }
  95012. });
  95013. }
  95014. callback(true);
  95015. }
  95016. });
  95017. };
  95018. /**
  95019. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95020. * @returns A promise with a boolean set to if the standing matrix is supported.
  95021. */
  95022. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  95023. var _this = this;
  95024. return new Promise(function (res, rej) {
  95025. _this.useStandingMatrix(function (supported) {
  95026. res(supported);
  95027. });
  95028. });
  95029. };
  95030. /**
  95031. * Disposes the camera
  95032. */
  95033. WebVRFreeCamera.prototype.dispose = function () {
  95034. this._detachIfAttached();
  95035. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  95036. _super.prototype.dispose.call(this);
  95037. };
  95038. /**
  95039. * Gets a vrController by name.
  95040. * @param name The name of the controller to retreive
  95041. * @returns the controller matching the name specified or null if not found
  95042. */
  95043. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  95044. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  95045. var gp = _a[_i];
  95046. if (gp.hand === name) {
  95047. return gp;
  95048. }
  95049. }
  95050. return null;
  95051. };
  95052. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  95053. /**
  95054. * The controller corrisponding to the users left hand.
  95055. */
  95056. get: function () {
  95057. if (!this._leftController) {
  95058. this._leftController = this.getControllerByName("left");
  95059. }
  95060. return this._leftController;
  95061. },
  95062. enumerable: true,
  95063. configurable: true
  95064. });
  95065. ;
  95066. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  95067. /**
  95068. * The controller corrisponding to the users right hand.
  95069. */
  95070. get: function () {
  95071. if (!this._rightController) {
  95072. this._rightController = this.getControllerByName("right");
  95073. }
  95074. return this._rightController;
  95075. },
  95076. enumerable: true,
  95077. configurable: true
  95078. });
  95079. ;
  95080. /**
  95081. * Casts a ray forward from the vrCamera's gaze.
  95082. * @param length Length of the ray (default: 100)
  95083. * @returns the ray corrisponding to the gaze
  95084. */
  95085. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  95086. if (length === void 0) { length = 100; }
  95087. if (this.leftCamera) {
  95088. // Use left eye to avoid computation to compute center on every call
  95089. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  95090. }
  95091. else {
  95092. return _super.prototype.getForwardRay.call(this, length);
  95093. }
  95094. };
  95095. /**
  95096. * @hidden
  95097. * Updates the camera based on device's frame data
  95098. */
  95099. WebVRFreeCamera.prototype._checkInputs = function () {
  95100. if (this._vrDevice && this._vrDevice.isPresenting) {
  95101. this._vrDevice.getFrameData(this._frameData);
  95102. this.updateFromDevice(this._frameData.pose);
  95103. }
  95104. _super.prototype._checkInputs.call(this);
  95105. };
  95106. /**
  95107. * Updates the poseControlled values based on the input device pose.
  95108. * @param poseData Pose coming from the device
  95109. */
  95110. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  95111. if (poseData && poseData.orientation) {
  95112. this.rawPose = poseData;
  95113. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  95114. if (this.getScene().useRightHandedSystem) {
  95115. this._deviceRoomRotationQuaternion.z *= -1;
  95116. this._deviceRoomRotationQuaternion.w *= -1;
  95117. }
  95118. if (this.webVROptions.trackPosition && this.rawPose.position) {
  95119. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  95120. if (this.getScene().useRightHandedSystem) {
  95121. this._deviceRoomPosition.z *= -1;
  95122. }
  95123. }
  95124. this._poseSet = true;
  95125. }
  95126. };
  95127. /**
  95128. * WebVR's attach control will start broadcasting frames to the device.
  95129. * Note that in certain browsers (chrome for example) this function must be called
  95130. * within a user-interaction callback. Example:
  95131. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  95132. *
  95133. * @param element html element to attach the vrDevice to
  95134. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  95135. */
  95136. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  95137. _super.prototype.attachControl.call(this, element, noPreventDefault);
  95138. this._attached = true;
  95139. this._htmlElementAttached = element;
  95140. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  95141. if (this._vrDevice) {
  95142. this.getEngine().enableVR();
  95143. }
  95144. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95145. };
  95146. /**
  95147. * Detaches the camera from the html element and disables VR
  95148. *
  95149. * @param element html element to detach from
  95150. */
  95151. WebVRFreeCamera.prototype.detachControl = function (element) {
  95152. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  95153. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  95154. _super.prototype.detachControl.call(this, element);
  95155. this._attached = false;
  95156. this.getEngine().disableVR();
  95157. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95158. };
  95159. /**
  95160. * @returns the name of this class
  95161. */
  95162. WebVRFreeCamera.prototype.getClassName = function () {
  95163. return "WebVRFreeCamera";
  95164. };
  95165. /**
  95166. * Calls resetPose on the vrDisplay
  95167. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  95168. */
  95169. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  95170. //uses the vrDisplay's "resetPose()".
  95171. //pitch and roll won't be affected.
  95172. this._vrDevice.resetPose();
  95173. };
  95174. /**
  95175. * @hidden
  95176. * Updates the rig cameras (left and right eye)
  95177. */
  95178. WebVRFreeCamera.prototype._updateRigCameras = function () {
  95179. var camLeft = this._rigCameras[0];
  95180. var camRight = this._rigCameras[1];
  95181. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95182. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95183. camLeft.position.copyFrom(this._deviceRoomPosition);
  95184. camRight.position.copyFrom(this._deviceRoomPosition);
  95185. };
  95186. /**
  95187. * @hidden
  95188. * Updates the cached values of the camera
  95189. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  95190. */
  95191. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  95192. var _this = this;
  95193. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  95194. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  95195. if (!this.updateCacheCalled) {
  95196. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  95197. this.updateCacheCalled = true;
  95198. this.update();
  95199. }
  95200. // Set working vector to the device position in room space rotated by the new rotation
  95201. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  95202. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  95203. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  95204. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  95205. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  95206. // Add translation from anchor position
  95207. this._deviceToWorld.getTranslationToRef(this._workingVector);
  95208. this._workingVector.addInPlace(this.position);
  95209. this._workingVector.subtractInPlace(this._cache.position);
  95210. this._deviceToWorld.setTranslation(this._workingVector);
  95211. // Set an inverted matrix to be used when updating the camera
  95212. this._deviceToWorld.invertToRef(this._worldToDevice);
  95213. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  95214. this.controllers.forEach(function (controller) {
  95215. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  95216. controller.update();
  95217. });
  95218. }
  95219. if (!ignoreParentClass) {
  95220. _super.prototype._updateCache.call(this);
  95221. }
  95222. this.updateCacheCalled = false;
  95223. };
  95224. /**
  95225. * Updates the current device position and rotation in the babylon world
  95226. */
  95227. WebVRFreeCamera.prototype.update = function () {
  95228. // Get current device position in babylon world
  95229. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  95230. // Get current device rotation in babylon world
  95231. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  95232. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  95233. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  95234. if (this._poseSet) {
  95235. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  95236. }
  95237. _super.prototype.update.call(this);
  95238. };
  95239. /**
  95240. * @hidden
  95241. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  95242. * @returns an identity matrix
  95243. */
  95244. WebVRFreeCamera.prototype._getViewMatrix = function () {
  95245. return BABYLON.Matrix.Identity();
  95246. };
  95247. /**
  95248. * This function is called by the two RIG cameras.
  95249. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  95250. */
  95251. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  95252. var _this = this;
  95253. // Update the parent camera prior to using a child camera to avoid desynchronization
  95254. var parentCamera = this._cameraRigParams["parentCamera"];
  95255. parentCamera._updateCache();
  95256. //WebVR 1.1
  95257. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  95258. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  95259. if (!this.getScene().useRightHandedSystem) {
  95260. [2, 6, 8, 9, 14].forEach(function (num) {
  95261. _this._webvrViewMatrix.m[num] *= -1;
  95262. });
  95263. }
  95264. // update the camera rotation matrix
  95265. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  95266. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  95267. // Computing target and final matrix
  95268. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  95269. // should the view matrix be updated with scale and position offset?
  95270. if (parentCamera.deviceScaleFactor !== 1) {
  95271. this._webvrViewMatrix.invert();
  95272. // scale the position, if set
  95273. if (parentCamera.deviceScaleFactor) {
  95274. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  95275. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  95276. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  95277. }
  95278. this._webvrViewMatrix.invert();
  95279. }
  95280. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95281. // Compute global position
  95282. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  95283. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  95284. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  95285. this._workingMatrix.getTranslationToRef(this._globalPosition);
  95286. this._markSyncedWithParent();
  95287. return this._webvrViewMatrix;
  95288. };
  95289. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  95290. var _this = this;
  95291. var parentCamera = this.parent;
  95292. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  95293. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  95294. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  95295. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  95296. //babylon compatible matrix
  95297. if (!this.getScene().useRightHandedSystem) {
  95298. [8, 9, 10, 11].forEach(function (num) {
  95299. _this._projectionMatrix.m[num] *= -1;
  95300. });
  95301. }
  95302. return this._projectionMatrix;
  95303. };
  95304. /**
  95305. * Initializes the controllers and their meshes
  95306. */
  95307. WebVRFreeCamera.prototype.initControllers = function () {
  95308. var _this = this;
  95309. this.controllers = [];
  95310. var manager = this.getScene().gamepadManager;
  95311. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  95312. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95313. var webVrController = gamepad;
  95314. if (webVrController.defaultModel) {
  95315. webVrController.defaultModel.setEnabled(false);
  95316. }
  95317. if (webVrController.hand === "right") {
  95318. _this._rightController = null;
  95319. }
  95320. if (webVrController.hand === "left") {
  95321. _this._leftController = null;
  95322. }
  95323. var controllerIndex = _this.controllers.indexOf(webVrController);
  95324. if (controllerIndex !== -1) {
  95325. _this.controllers.splice(controllerIndex, 1);
  95326. }
  95327. }
  95328. });
  95329. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  95330. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95331. var webVrController_1 = gamepad;
  95332. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  95333. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  95334. if (_this.webVROptions.controllerMeshes) {
  95335. if (webVrController_1.defaultModel) {
  95336. webVrController_1.defaultModel.setEnabled(true);
  95337. }
  95338. else {
  95339. // Load the meshes
  95340. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  95341. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  95342. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  95343. if (_this.webVROptions.defaultLightingOnControllers) {
  95344. if (!_this._lightOnControllers) {
  95345. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  95346. }
  95347. var activateLightOnSubMeshes_1 = function (mesh, light) {
  95348. var children = mesh.getChildren();
  95349. if (children.length !== 0) {
  95350. children.forEach(function (mesh) {
  95351. light.includedOnlyMeshes.push(mesh);
  95352. activateLightOnSubMeshes_1(mesh, light);
  95353. });
  95354. }
  95355. };
  95356. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  95357. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  95358. }
  95359. });
  95360. }
  95361. }
  95362. webVrController_1.attachToPoseControlledCamera(_this);
  95363. // since this is async - sanity check. Is the controller already stored?
  95364. if (_this.controllers.indexOf(webVrController_1) === -1) {
  95365. //add to the controllers array
  95366. _this.controllers.push(webVrController_1);
  95367. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  95368. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  95369. // So we're overriding setting left & right manually to be sure
  95370. var firstViveWandDetected = false;
  95371. for (var i = 0; i < _this.controllers.length; i++) {
  95372. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95373. if (!firstViveWandDetected) {
  95374. firstViveWandDetected = true;
  95375. _this.controllers[i].hand = "left";
  95376. }
  95377. else {
  95378. _this.controllers[i].hand = "right";
  95379. }
  95380. }
  95381. }
  95382. //did we find enough controllers? Great! let the developer know.
  95383. if (_this.controllers.length >= 2) {
  95384. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  95385. }
  95386. }
  95387. }
  95388. });
  95389. };
  95390. return WebVRFreeCamera;
  95391. }(BABYLON.FreeCamera));
  95392. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  95393. })(BABYLON || (BABYLON = {}));
  95394. //# sourceMappingURL=babylon.webVRCamera.js.map
  95395. var BABYLON;
  95396. (function (BABYLON) {
  95397. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  95398. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  95399. });
  95400. // We're mainly based on the logic defined into the FreeCamera code
  95401. /**
  95402. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  95403. * being tilted forward or back and left or right.
  95404. */
  95405. var DeviceOrientationCamera = /** @class */ (function (_super) {
  95406. __extends(DeviceOrientationCamera, _super);
  95407. /**
  95408. * Creates a new device orientation camera
  95409. * @param name The name of the camera
  95410. * @param position The start position camera
  95411. * @param scene The scene the camera belongs to
  95412. */
  95413. function DeviceOrientationCamera(name, position, scene) {
  95414. var _this = _super.call(this, name, position, scene) || this;
  95415. _this._quaternionCache = new BABYLON.Quaternion();
  95416. _this.inputs.addDeviceOrientation();
  95417. return _this;
  95418. }
  95419. /**
  95420. * Gets the current instance class name ("DeviceOrientationCamera").
  95421. * This helps avoiding instanceof at run time.
  95422. * @returns the class name
  95423. */
  95424. DeviceOrientationCamera.prototype.getClassName = function () {
  95425. return "DeviceOrientationCamera";
  95426. };
  95427. /**
  95428. * @hidden
  95429. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  95430. */
  95431. DeviceOrientationCamera.prototype._checkInputs = function () {
  95432. _super.prototype._checkInputs.call(this);
  95433. this._quaternionCache.copyFrom(this.rotationQuaternion);
  95434. if (this._initialQuaternion) {
  95435. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95436. }
  95437. };
  95438. /**
  95439. * Reset the camera to its default orientation on the specified axis only.
  95440. * @param axis The axis to reset
  95441. */
  95442. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  95443. var _this = this;
  95444. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  95445. //can only work if this camera has a rotation quaternion already.
  95446. if (!this.rotationQuaternion)
  95447. return;
  95448. if (!this._initialQuaternion) {
  95449. this._initialQuaternion = new BABYLON.Quaternion();
  95450. }
  95451. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  95452. ['x', 'y', 'z'].forEach(function (axisName) {
  95453. if (!axis[axisName]) {
  95454. _this._initialQuaternion[axisName] = 0;
  95455. }
  95456. else {
  95457. _this._initialQuaternion[axisName] *= -1;
  95458. }
  95459. });
  95460. this._initialQuaternion.normalize();
  95461. //force rotation update
  95462. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95463. };
  95464. return DeviceOrientationCamera;
  95465. }(BABYLON.FreeCamera));
  95466. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  95467. })(BABYLON || (BABYLON = {}));
  95468. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  95469. var BABYLON;
  95470. (function (BABYLON) {
  95471. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95472. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95473. });
  95474. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  95475. __extends(VRDeviceOrientationFreeCamera, _super);
  95476. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95477. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95478. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95479. var _this = _super.call(this, name, position, scene) || this;
  95480. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95481. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95482. return _this;
  95483. }
  95484. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  95485. return "VRDeviceOrientationFreeCamera";
  95486. };
  95487. return VRDeviceOrientationFreeCamera;
  95488. }(BABYLON.DeviceOrientationCamera));
  95489. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  95490. })(BABYLON || (BABYLON = {}));
  95491. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  95492. var BABYLON;
  95493. (function (BABYLON) {
  95494. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95495. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  95496. });
  95497. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  95498. __extends(VRDeviceOrientationArcRotateCamera, _super);
  95499. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  95500. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95501. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95502. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95503. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95504. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95505. _this.inputs.addVRDeviceOrientation();
  95506. return _this;
  95507. }
  95508. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  95509. return "VRDeviceOrientationArcRotateCamera";
  95510. };
  95511. return VRDeviceOrientationArcRotateCamera;
  95512. }(BABYLON.ArcRotateCamera));
  95513. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  95514. })(BABYLON || (BABYLON = {}));
  95515. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  95516. var BABYLON;
  95517. (function (BABYLON) {
  95518. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  95519. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  95520. });
  95521. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  95522. __extends(VRDeviceOrientationGamepadCamera, _super);
  95523. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95524. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95525. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95526. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  95527. _this.inputs.addGamepad();
  95528. return _this;
  95529. }
  95530. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  95531. return "VRDeviceOrientationGamepadCamera";
  95532. };
  95533. return VRDeviceOrientationGamepadCamera;
  95534. }(BABYLON.VRDeviceOrientationFreeCamera));
  95535. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  95536. })(BABYLON || (BABYLON = {}));
  95537. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  95538. var BABYLON;
  95539. (function (BABYLON) {
  95540. var VRExperienceHelperGazer = /** @class */ (function () {
  95541. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  95542. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  95543. this.scene = scene;
  95544. /** @hidden */
  95545. this._pointerDownOnMeshAsked = false;
  95546. /** @hidden */
  95547. this._isActionableMesh = false;
  95548. /** @hidden */
  95549. this._teleportationRequestInitiated = false;
  95550. /** @hidden */
  95551. this._teleportationBackRequestInitiated = false;
  95552. /** @hidden */
  95553. this._rotationRightAsked = false;
  95554. /** @hidden */
  95555. this._rotationLeftAsked = false;
  95556. /** @hidden */
  95557. this._dpadPressed = true;
  95558. /** @hidden */
  95559. this._activePointer = false;
  95560. this._id = VRExperienceHelperGazer._idCounter++;
  95561. // Gaze tracker
  95562. if (!gazeTrackerToClone) {
  95563. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  95564. this._gazeTracker.bakeCurrentTransformIntoVertices();
  95565. this._gazeTracker.isPickable = false;
  95566. this._gazeTracker.isVisible = false;
  95567. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  95568. targetMat.specularColor = BABYLON.Color3.Black();
  95569. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95570. targetMat.backFaceCulling = false;
  95571. this._gazeTracker.material = targetMat;
  95572. }
  95573. else {
  95574. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  95575. }
  95576. }
  95577. /** @hidden */
  95578. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  95579. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  95580. };
  95581. /** @hidden */
  95582. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  95583. this._pointerDownOnMeshAsked = true;
  95584. if (this._currentHit) {
  95585. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  95586. }
  95587. };
  95588. /** @hidden */
  95589. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  95590. if (this._currentHit) {
  95591. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  95592. }
  95593. this._pointerDownOnMeshAsked = false;
  95594. };
  95595. /** @hidden */
  95596. VRExperienceHelperGazer.prototype._activatePointer = function () {
  95597. this._activePointer = true;
  95598. };
  95599. /** @hidden */
  95600. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  95601. this._activePointer = false;
  95602. };
  95603. /** @hidden */
  95604. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  95605. if (distance === void 0) { distance = 100; }
  95606. };
  95607. VRExperienceHelperGazer.prototype.dispose = function () {
  95608. this._interactionsEnabled = false;
  95609. this._teleportationEnabled = false;
  95610. if (this._gazeTracker) {
  95611. this._gazeTracker.dispose();
  95612. }
  95613. };
  95614. VRExperienceHelperGazer._idCounter = 0;
  95615. return VRExperienceHelperGazer;
  95616. }());
  95617. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  95618. __extends(VRExperienceHelperControllerGazer, _super);
  95619. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  95620. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  95621. _this.webVRController = webVRController;
  95622. // Laser pointer
  95623. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  95624. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  95625. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95626. laserPointerMaterial.alpha = 0.6;
  95627. _this._laserPointer.material = laserPointerMaterial;
  95628. _this._laserPointer.rotation.x = Math.PI / 2;
  95629. _this._laserPointer.position.z = -0.5;
  95630. _this._laserPointer.isVisible = false;
  95631. _this._laserPointer.isPickable = false;
  95632. if (!webVRController.mesh) {
  95633. // Create an empty mesh that is used prior to loading the high quality model
  95634. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  95635. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  95636. preloadPointerPose.rotation.x = -0.7;
  95637. preloadMesh.addChild(preloadPointerPose);
  95638. webVRController.attachToMesh(preloadMesh);
  95639. }
  95640. _this._setLaserPointerParent(webVRController.mesh);
  95641. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  95642. _this._setLaserPointerParent(mesh);
  95643. });
  95644. return _this;
  95645. }
  95646. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  95647. return this.webVRController.getForwardRay(length);
  95648. };
  95649. /** @hidden */
  95650. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  95651. _super.prototype._activatePointer.call(this);
  95652. this._laserPointer.isVisible = true;
  95653. };
  95654. /** @hidden */
  95655. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  95656. _super.prototype._deactivatePointer.call(this);
  95657. this._laserPointer.isVisible = false;
  95658. };
  95659. /** @hidden */
  95660. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  95661. this._laserPointer.material.emissiveColor = color;
  95662. };
  95663. /** @hidden */
  95664. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  95665. var makeNotPick = function (root) {
  95666. root.isPickable = false;
  95667. root.getChildMeshes().forEach(function (c) {
  95668. makeNotPick(c);
  95669. });
  95670. };
  95671. makeNotPick(mesh);
  95672. var childMeshes = mesh.getChildMeshes();
  95673. this.webVRController._pointingPoseNode = null;
  95674. for (var i = 0; i < childMeshes.length; i++) {
  95675. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  95676. mesh = childMeshes[i];
  95677. this.webVRController._pointingPoseNode = mesh;
  95678. break;
  95679. }
  95680. }
  95681. this._laserPointer.parent = mesh;
  95682. };
  95683. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  95684. if (distance === void 0) { distance = 100; }
  95685. this._laserPointer.scaling.y = distance;
  95686. this._laserPointer.position.z = -distance / 2;
  95687. };
  95688. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  95689. _super.prototype.dispose.call(this);
  95690. this._laserPointer.dispose();
  95691. if (this._meshAttachedObserver) {
  95692. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  95693. }
  95694. };
  95695. return VRExperienceHelperControllerGazer;
  95696. }(VRExperienceHelperGazer));
  95697. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  95698. __extends(VRExperienceHelperCameraGazer, _super);
  95699. function VRExperienceHelperCameraGazer(getCamera, scene) {
  95700. var _this = _super.call(this, scene) || this;
  95701. _this.getCamera = getCamera;
  95702. return _this;
  95703. }
  95704. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  95705. var camera = this.getCamera();
  95706. if (camera) {
  95707. return camera.getForwardRay(length);
  95708. }
  95709. else {
  95710. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  95711. }
  95712. };
  95713. return VRExperienceHelperCameraGazer;
  95714. }(VRExperienceHelperGazer));
  95715. /**
  95716. * Helps to quickly add VR support to an existing scene.
  95717. * See http://doc.babylonjs.com/how_to/webvr_helper
  95718. */
  95719. var VRExperienceHelper = /** @class */ (function () {
  95720. /**
  95721. * Instantiates a VRExperienceHelper.
  95722. * Helps to quickly add VR support to an existing scene.
  95723. * @param scene The scene the VRExperienceHelper belongs to.
  95724. * @param webVROptions Options to modify the vr experience helper's behavior.
  95725. */
  95726. function VRExperienceHelper(scene,
  95727. /** Options to modify the vr experience helper's behavior. */
  95728. webVROptions) {
  95729. if (webVROptions === void 0) { webVROptions = {}; }
  95730. var _this = this;
  95731. this.webVROptions = webVROptions;
  95732. // Can the system support WebVR, even if a headset isn't plugged in?
  95733. this._webVRsupported = false;
  95734. // If WebVR is supported, is a headset plugged in and are we ready to present?
  95735. this._webVRready = false;
  95736. // Are we waiting for the requestPresent callback to complete?
  95737. this._webVRrequesting = false;
  95738. // Are we presenting to the headset right now? (this is the vrDevice state)
  95739. this._webVRpresenting = false;
  95740. // Are we presenting in the fullscreen fallback?
  95741. this._fullscreenVRpresenting = false;
  95742. /**
  95743. * Observable raised when entering VR.
  95744. */
  95745. this.onEnteringVRObservable = new BABYLON.Observable();
  95746. /**
  95747. * Observable raised when exiting VR.
  95748. */
  95749. this.onExitingVRObservable = new BABYLON.Observable();
  95750. /**
  95751. * Observable raised when controller mesh is loaded.
  95752. */
  95753. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95754. this._useCustomVRButton = false;
  95755. this._teleportationRequested = false;
  95756. this._teleportActive = false;
  95757. this._floorMeshesCollection = [];
  95758. this._rotationAllowed = true;
  95759. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  95760. this._isDefaultTeleportationTarget = true;
  95761. this._teleportationFillColor = "#444444";
  95762. this._teleportationBorderColor = "#FFFFFF";
  95763. this._rotationAngle = 0;
  95764. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  95765. this._padSensibilityUp = 0.65;
  95766. this._padSensibilityDown = 0.35;
  95767. this._leftController = null;
  95768. this._rightController = null;
  95769. /**
  95770. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  95771. */
  95772. this.onNewMeshSelected = new BABYLON.Observable();
  95773. /**
  95774. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  95775. */
  95776. this.onNewMeshPicked = new BABYLON.Observable();
  95777. /**
  95778. * Observable raised before camera teleportation
  95779. */
  95780. this.onBeforeCameraTeleport = new BABYLON.Observable();
  95781. /**
  95782. * Observable raised after camera teleportation
  95783. */
  95784. this.onAfterCameraTeleport = new BABYLON.Observable();
  95785. /**
  95786. * Observable raised when current selected mesh gets unselected
  95787. */
  95788. this.onSelectedMeshUnselected = new BABYLON.Observable();
  95789. /**
  95790. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  95791. */
  95792. this.teleportationEnabled = true;
  95793. this._teleportationInitialized = false;
  95794. this._interactionsEnabled = false;
  95795. this._interactionsRequested = false;
  95796. this._displayGaze = true;
  95797. this._displayLaserPointer = true;
  95798. /**
  95799. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  95800. */
  95801. this.updateGazeTrackerScale = true;
  95802. this._onResize = function () {
  95803. _this.moveButtonToBottomRight();
  95804. if (_this._fullscreenVRpresenting && _this._webVRready) {
  95805. _this.exitVR();
  95806. }
  95807. };
  95808. this._onFullscreenChange = function () {
  95809. if (document.fullscreen !== undefined) {
  95810. _this._fullscreenVRpresenting = document.fullscreen;
  95811. }
  95812. else if (document.mozFullScreen !== undefined) {
  95813. _this._fullscreenVRpresenting = document.mozFullScreen;
  95814. }
  95815. else if (document.webkitIsFullScreen !== undefined) {
  95816. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  95817. }
  95818. else if (document.msIsFullScreen !== undefined) {
  95819. _this._fullscreenVRpresenting = document.msIsFullScreen;
  95820. }
  95821. else if (document.msFullscreenElement !== undefined) {
  95822. _this._fullscreenVRpresenting = document.msFullscreenElement;
  95823. }
  95824. if (!_this._fullscreenVRpresenting && _this._canvas) {
  95825. _this.exitVR();
  95826. if (!_this._useCustomVRButton) {
  95827. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  95828. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  95829. }
  95830. }
  95831. };
  95832. this.beforeRender = function () {
  95833. if (_this._leftController && _this._leftController._activePointer) {
  95834. _this._castRayAndSelectObject(_this._leftController);
  95835. }
  95836. if (_this._rightController && _this._rightController._activePointer) {
  95837. _this._castRayAndSelectObject(_this._rightController);
  95838. }
  95839. if (_this._noControllerIsActive) {
  95840. _this._castRayAndSelectObject(_this._cameraGazer);
  95841. }
  95842. else {
  95843. _this._cameraGazer._gazeTracker.isVisible = false;
  95844. }
  95845. };
  95846. this._onNewGamepadConnected = function (gamepad) {
  95847. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  95848. if (gamepad.leftStick) {
  95849. gamepad.onleftstickchanged(function (stickValues) {
  95850. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  95851. // Listening to classic/xbox gamepad only if no VR controller is active
  95852. if ((!_this._leftController && !_this._rightController) ||
  95853. ((_this._leftController && !_this._leftController._activePointer) &&
  95854. (_this._rightController && !_this._rightController._activePointer))) {
  95855. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  95856. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  95857. }
  95858. }
  95859. });
  95860. }
  95861. if (gamepad.rightStick) {
  95862. gamepad.onrightstickchanged(function (stickValues) {
  95863. if (_this._teleportationInitialized) {
  95864. _this._checkRotate(stickValues, _this._cameraGazer);
  95865. }
  95866. });
  95867. }
  95868. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  95869. gamepad.onbuttondown(function (buttonPressed) {
  95870. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95871. _this._cameraGazer._selectionPointerDown();
  95872. }
  95873. });
  95874. gamepad.onbuttonup(function (buttonPressed) {
  95875. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95876. _this._cameraGazer._selectionPointerUp();
  95877. }
  95878. });
  95879. }
  95880. }
  95881. else {
  95882. var webVRController = gamepad;
  95883. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  95884. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  95885. _this._rightController = controller;
  95886. }
  95887. else {
  95888. _this._leftController = controller;
  95889. }
  95890. _this._tryEnableInteractionOnController(controller);
  95891. }
  95892. };
  95893. // 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
  95894. this._tryEnableInteractionOnController = function (controller) {
  95895. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  95896. _this._enableInteractionOnController(controller);
  95897. }
  95898. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  95899. _this._enableTeleportationOnController(controller);
  95900. }
  95901. };
  95902. this._onNewGamepadDisconnected = function (gamepad) {
  95903. if (gamepad instanceof BABYLON.WebVRController) {
  95904. if (gamepad.hand === "left" && _this._leftController != null) {
  95905. _this._leftController.dispose();
  95906. _this._leftController = null;
  95907. }
  95908. if (gamepad.hand === "right" && _this._rightController != null) {
  95909. _this._rightController.dispose();
  95910. _this._rightController = null;
  95911. }
  95912. }
  95913. };
  95914. this._workingVector = BABYLON.Vector3.Zero();
  95915. this._workingQuaternion = BABYLON.Quaternion.Identity();
  95916. this._workingMatrix = BABYLON.Matrix.Identity();
  95917. this._scene = scene;
  95918. this._canvas = scene.getEngine().getRenderingCanvas();
  95919. // Parse options
  95920. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  95921. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  95922. }
  95923. if (webVROptions.createDeviceOrientationCamera === undefined) {
  95924. webVROptions.createDeviceOrientationCamera = true;
  95925. }
  95926. if (webVROptions.laserToggle === undefined) {
  95927. webVROptions.laserToggle = true;
  95928. }
  95929. if (webVROptions.defaultHeight === undefined) {
  95930. webVROptions.defaultHeight = 1.7;
  95931. }
  95932. if (webVROptions.useCustomVRButton) {
  95933. this._useCustomVRButton = true;
  95934. if (webVROptions.customVRButton) {
  95935. this._btnVR = webVROptions.customVRButton;
  95936. }
  95937. }
  95938. if (webVROptions.rayLength) {
  95939. this._rayLength = webVROptions.rayLength;
  95940. }
  95941. this._defaultHeight = webVROptions.defaultHeight;
  95942. if (webVROptions.positionScale) {
  95943. this._rayLength *= webVROptions.positionScale;
  95944. this._defaultHeight *= webVROptions.positionScale;
  95945. }
  95946. this._hasEnteredVR = false;
  95947. // Set position
  95948. if (this._scene.activeCamera) {
  95949. this._position = this._scene.activeCamera.position.clone();
  95950. }
  95951. else {
  95952. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  95953. }
  95954. // Set non-vr camera
  95955. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  95956. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  95957. // Copy data from existing camera
  95958. if (this._scene.activeCamera) {
  95959. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95960. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  95961. // Set rotation from previous camera
  95962. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  95963. var targetCamera = this._scene.activeCamera;
  95964. if (targetCamera.rotationQuaternion) {
  95965. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  95966. }
  95967. else {
  95968. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  95969. }
  95970. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  95971. }
  95972. }
  95973. this._scene.activeCamera = this._deviceOrientationCamera;
  95974. if (this._canvas) {
  95975. this._scene.activeCamera.attachControl(this._canvas);
  95976. }
  95977. }
  95978. else {
  95979. this._existingCamera = this._scene.activeCamera;
  95980. }
  95981. // Create VR cameras
  95982. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95983. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  95984. }
  95985. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  95986. this._webVRCamera.useStandingMatrix();
  95987. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  95988. // Create default button
  95989. if (!this._useCustomVRButton) {
  95990. this._btnVR = document.createElement("BUTTON");
  95991. this._btnVR.className = "babylonVRicon";
  95992. this._btnVR.id = "babylonVRiconbtn";
  95993. this._btnVR.title = "Click to switch to VR";
  95994. 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) }";
  95995. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  95996. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  95997. // css += ".babylonVRicon.vrdisplaysupported { }";
  95998. // css += ".babylonVRicon.vrdisplayready { }";
  95999. // css += ".babylonVRicon.vrdisplayrequesting { }";
  96000. var style = document.createElement('style');
  96001. style.appendChild(document.createTextNode(css));
  96002. document.getElementsByTagName('head')[0].appendChild(style);
  96003. this.moveButtonToBottomRight();
  96004. }
  96005. // VR button click event
  96006. if (this._btnVR) {
  96007. this._btnVR.addEventListener("click", function () {
  96008. if (!_this.isInVRMode) {
  96009. _this.enterVR();
  96010. }
  96011. else {
  96012. _this.exitVR();
  96013. }
  96014. });
  96015. }
  96016. // Window events
  96017. window.addEventListener("resize", this._onResize);
  96018. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  96019. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  96020. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  96021. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  96022. document.onmsfullscreenchange = this._onFullscreenChange;
  96023. // Display vr button when headset is connected
  96024. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96025. this.displayVRButton();
  96026. }
  96027. else {
  96028. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  96029. if (e.vrDisplay) {
  96030. _this.displayVRButton();
  96031. }
  96032. });
  96033. }
  96034. // Exiting VR mode using 'ESC' key on desktop
  96035. this._onKeyDown = function (event) {
  96036. if (event.keyCode === 27 && _this.isInVRMode) {
  96037. _this.exitVR();
  96038. }
  96039. };
  96040. document.addEventListener("keydown", this._onKeyDown);
  96041. // Exiting VR mode double tapping the touch screen
  96042. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  96043. if (_this.isInVRMode) {
  96044. _this.exitVR();
  96045. if (_this._fullscreenVRpresenting) {
  96046. _this._scene.getEngine().switchFullscreen(true);
  96047. }
  96048. }
  96049. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  96050. // Listen for WebVR display changes
  96051. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  96052. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  96053. this._onVRRequestPresentStart = function () {
  96054. _this._webVRrequesting = true;
  96055. _this.updateButtonVisibility();
  96056. };
  96057. this._onVRRequestPresentComplete = function (success) {
  96058. _this._webVRrequesting = false;
  96059. _this.updateButtonVisibility();
  96060. };
  96061. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  96062. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  96063. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  96064. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96065. scene.onDisposeObservable.add(function () {
  96066. _this.dispose();
  96067. });
  96068. // Gamepad connection events
  96069. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  96070. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  96071. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  96072. this.updateButtonVisibility();
  96073. //create easing functions
  96074. this._circleEase = new BABYLON.CircleEase();
  96075. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96076. if (this.webVROptions.floorMeshes) {
  96077. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  96078. }
  96079. }
  96080. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  96081. /** Return this.onEnteringVRObservable
  96082. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  96083. */
  96084. get: function () {
  96085. return this.onEnteringVRObservable;
  96086. },
  96087. enumerable: true,
  96088. configurable: true
  96089. });
  96090. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  96091. /** Return this.onExitingVRObservable
  96092. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  96093. */
  96094. get: function () {
  96095. return this.onExitingVRObservable;
  96096. },
  96097. enumerable: true,
  96098. configurable: true
  96099. });
  96100. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  96101. /** Return this.onControllerMeshLoadedObservable
  96102. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  96103. */
  96104. get: function () {
  96105. return this.onControllerMeshLoadedObservable;
  96106. },
  96107. enumerable: true,
  96108. configurable: true
  96109. });
  96110. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  96111. /**
  96112. * The mesh used to display where the user is going to teleport.
  96113. */
  96114. get: function () {
  96115. return this._teleportationTarget;
  96116. },
  96117. /**
  96118. * Sets the mesh to be used to display where the user is going to teleport.
  96119. */
  96120. set: function (value) {
  96121. if (value) {
  96122. value.name = "teleportationTarget";
  96123. this._isDefaultTeleportationTarget = false;
  96124. this._teleportationTarget = value;
  96125. }
  96126. },
  96127. enumerable: true,
  96128. configurable: true
  96129. });
  96130. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  96131. /**
  96132. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  96133. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  96134. * See http://doc.babylonjs.com/resources/baking_transformations
  96135. */
  96136. get: function () {
  96137. return this._cameraGazer._gazeTracker;
  96138. },
  96139. set: function (value) {
  96140. if (value) {
  96141. // Dispose of existing meshes
  96142. if (this._cameraGazer._gazeTracker) {
  96143. this._cameraGazer._gazeTracker.dispose();
  96144. }
  96145. if (this._leftController && this._leftController._gazeTracker) {
  96146. this._leftController._gazeTracker.dispose();
  96147. }
  96148. if (this._rightController && this._rightController._gazeTracker) {
  96149. this._rightController._gazeTracker.dispose();
  96150. }
  96151. // Set and create gaze trackers on head and controllers
  96152. this._cameraGazer._gazeTracker = value;
  96153. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  96154. this._cameraGazer._gazeTracker.isPickable = false;
  96155. this._cameraGazer._gazeTracker.isVisible = false;
  96156. this._cameraGazer._gazeTracker.name = "gazeTracker";
  96157. if (this._leftController) {
  96158. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96159. }
  96160. if (this._rightController) {
  96161. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96162. }
  96163. }
  96164. },
  96165. enumerable: true,
  96166. configurable: true
  96167. });
  96168. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  96169. /**
  96170. * The gaze tracking mesh corresponding to the left controller
  96171. */
  96172. get: function () {
  96173. if (this._leftController) {
  96174. return this._leftController._gazeTracker;
  96175. }
  96176. return null;
  96177. },
  96178. enumerable: true,
  96179. configurable: true
  96180. });
  96181. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  96182. /**
  96183. * The gaze tracking mesh corresponding to the right controller
  96184. */
  96185. get: function () {
  96186. if (this._rightController) {
  96187. return this._rightController._gazeTracker;
  96188. }
  96189. return null;
  96190. },
  96191. enumerable: true,
  96192. configurable: true
  96193. });
  96194. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  96195. /**
  96196. * If the ray of the gaze should be displayed.
  96197. */
  96198. get: function () {
  96199. return this._displayGaze;
  96200. },
  96201. /**
  96202. * Sets if the ray of the gaze should be displayed.
  96203. */
  96204. set: function (value) {
  96205. this._displayGaze = value;
  96206. if (!value) {
  96207. this._cameraGazer._gazeTracker.isVisible = false;
  96208. if (this._leftController) {
  96209. this._leftController._gazeTracker.isVisible = false;
  96210. }
  96211. if (this._rightController) {
  96212. this._rightController._gazeTracker.isVisible = false;
  96213. }
  96214. }
  96215. },
  96216. enumerable: true,
  96217. configurable: true
  96218. });
  96219. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  96220. /**
  96221. * If the ray of the LaserPointer should be displayed.
  96222. */
  96223. get: function () {
  96224. return this._displayLaserPointer;
  96225. },
  96226. /**
  96227. * Sets if the ray of the LaserPointer should be displayed.
  96228. */
  96229. set: function (value) {
  96230. this._displayLaserPointer = value;
  96231. if (!value) {
  96232. if (this._rightController) {
  96233. this._rightController._deactivatePointer();
  96234. this._rightController._gazeTracker.isVisible = false;
  96235. }
  96236. if (this._leftController) {
  96237. this._leftController._deactivatePointer();
  96238. this._leftController._gazeTracker.isVisible = false;
  96239. }
  96240. }
  96241. else {
  96242. if (this._rightController) {
  96243. this._rightController._activatePointer();
  96244. }
  96245. if (this._leftController) {
  96246. this._leftController._activatePointer();
  96247. }
  96248. }
  96249. },
  96250. enumerable: true,
  96251. configurable: true
  96252. });
  96253. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  96254. /**
  96255. * The deviceOrientationCamera used as the camera when not in VR.
  96256. */
  96257. get: function () {
  96258. return this._deviceOrientationCamera;
  96259. },
  96260. enumerable: true,
  96261. configurable: true
  96262. });
  96263. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  96264. /**
  96265. * Based on the current WebVR support, returns the current VR camera used.
  96266. */
  96267. get: function () {
  96268. if (this._webVRready) {
  96269. return this._webVRCamera;
  96270. }
  96271. else {
  96272. return this._scene.activeCamera;
  96273. }
  96274. },
  96275. enumerable: true,
  96276. configurable: true
  96277. });
  96278. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  96279. /**
  96280. * The webVRCamera which is used when in VR.
  96281. */
  96282. get: function () {
  96283. return this._webVRCamera;
  96284. },
  96285. enumerable: true,
  96286. configurable: true
  96287. });
  96288. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  96289. /**
  96290. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  96291. */
  96292. get: function () {
  96293. return this._vrDeviceOrientationCamera;
  96294. },
  96295. enumerable: true,
  96296. configurable: true
  96297. });
  96298. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  96299. get: function () {
  96300. var result = this._cameraGazer._teleportationRequestInitiated
  96301. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  96302. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  96303. return result;
  96304. },
  96305. enumerable: true,
  96306. configurable: true
  96307. });
  96308. // Raised when one of the controller has loaded successfully its associated default mesh
  96309. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  96310. if (this._leftController && this._leftController.webVRController == webVRController) {
  96311. if (webVRController.mesh) {
  96312. this._leftController._setLaserPointerParent(webVRController.mesh);
  96313. }
  96314. }
  96315. if (this._rightController && this._rightController.webVRController == webVRController) {
  96316. if (webVRController.mesh) {
  96317. this._rightController._setLaserPointerParent(webVRController.mesh);
  96318. }
  96319. }
  96320. try {
  96321. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  96322. }
  96323. catch (err) {
  96324. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  96325. }
  96326. };
  96327. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  96328. /**
  96329. * Gets a value indicating if we are currently in VR mode.
  96330. */
  96331. get: function () {
  96332. return this._webVRpresenting || this._fullscreenVRpresenting;
  96333. },
  96334. enumerable: true,
  96335. configurable: true
  96336. });
  96337. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  96338. var vrDisplay = this._scene.getEngine().getVRDevice();
  96339. if (vrDisplay) {
  96340. var wasPresenting = this._webVRpresenting;
  96341. this._webVRpresenting = vrDisplay.isPresenting;
  96342. if (wasPresenting && !this._webVRpresenting)
  96343. this.exitVR();
  96344. }
  96345. else {
  96346. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  96347. }
  96348. this.updateButtonVisibility();
  96349. };
  96350. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  96351. this._webVRsupported = eventArgs.vrSupported;
  96352. this._webVRready = !!eventArgs.vrDisplay;
  96353. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  96354. this.updateButtonVisibility();
  96355. };
  96356. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  96357. if (this._canvas && !this._useCustomVRButton) {
  96358. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  96359. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  96360. }
  96361. };
  96362. VRExperienceHelper.prototype.displayVRButton = function () {
  96363. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  96364. document.body.appendChild(this._btnVR);
  96365. this._btnVRDisplayed = true;
  96366. }
  96367. };
  96368. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  96369. if (!this._btnVR || this._useCustomVRButton) {
  96370. return;
  96371. }
  96372. this._btnVR.className = "babylonVRicon";
  96373. if (this.isInVRMode) {
  96374. this._btnVR.className += " vrdisplaypresenting";
  96375. }
  96376. else {
  96377. if (this._webVRready)
  96378. this._btnVR.className += " vrdisplayready";
  96379. if (this._webVRsupported)
  96380. this._btnVR.className += " vrdisplaysupported";
  96381. if (this._webVRrequesting)
  96382. this._btnVR.className += " vrdisplayrequesting";
  96383. }
  96384. };
  96385. /**
  96386. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  96387. * Otherwise, will use the fullscreen API.
  96388. */
  96389. VRExperienceHelper.prototype.enterVR = function () {
  96390. if (this.onEnteringVRObservable) {
  96391. try {
  96392. this.onEnteringVRObservable.notifyObservers(this);
  96393. }
  96394. catch (err) {
  96395. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  96396. }
  96397. }
  96398. if (this._scene.activeCamera) {
  96399. this._position = this._scene.activeCamera.position.clone();
  96400. // make sure that we return to the last active camera
  96401. this._existingCamera = this._scene.activeCamera;
  96402. }
  96403. if (this._webVRrequesting)
  96404. return;
  96405. // If WebVR is supported and a headset is connected
  96406. if (this._webVRready) {
  96407. if (!this._webVRpresenting) {
  96408. this._webVRCamera.position = this._position;
  96409. this._scene.activeCamera = this._webVRCamera;
  96410. }
  96411. }
  96412. else if (this._vrDeviceOrientationCamera) {
  96413. this._vrDeviceOrientationCamera.position = this._position;
  96414. if (this._scene.activeCamera) {
  96415. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96416. }
  96417. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  96418. this._scene.getEngine().switchFullscreen(true);
  96419. this.updateButtonVisibility();
  96420. }
  96421. if (this._scene.activeCamera && this._canvas) {
  96422. this._scene.activeCamera.attachControl(this._canvas);
  96423. }
  96424. if (this._interactionsEnabled) {
  96425. this._scene.registerBeforeRender(this.beforeRender);
  96426. }
  96427. this._hasEnteredVR = true;
  96428. };
  96429. /**
  96430. * Attempt to exit VR, or fullscreen.
  96431. */
  96432. VRExperienceHelper.prototype.exitVR = function () {
  96433. if (this._hasEnteredVR) {
  96434. if (this.onExitingVRObservable) {
  96435. try {
  96436. this.onExitingVRObservable.notifyObservers(this);
  96437. }
  96438. catch (err) {
  96439. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  96440. }
  96441. }
  96442. if (this._webVRpresenting) {
  96443. this._scene.getEngine().disableVR();
  96444. }
  96445. if (this._scene.activeCamera) {
  96446. this._position = this._scene.activeCamera.position.clone();
  96447. }
  96448. if (this._deviceOrientationCamera) {
  96449. this._deviceOrientationCamera.position = this._position;
  96450. this._scene.activeCamera = this._deviceOrientationCamera;
  96451. if (this._canvas) {
  96452. this._scene.activeCamera.attachControl(this._canvas);
  96453. }
  96454. }
  96455. else if (this._existingCamera) {
  96456. this._existingCamera.position = this._position;
  96457. this._scene.activeCamera = this._existingCamera;
  96458. }
  96459. this.updateButtonVisibility();
  96460. if (this._interactionsEnabled) {
  96461. this._scene.unregisterBeforeRender(this.beforeRender);
  96462. this._cameraGazer._gazeTracker.isVisible = false;
  96463. if (this._leftController) {
  96464. this._leftController._gazeTracker.isVisible = false;
  96465. }
  96466. if (this._rightController) {
  96467. this._rightController._gazeTracker.isVisible = false;
  96468. }
  96469. }
  96470. // resize to update width and height when exiting vr exits fullscreen
  96471. this._scene.getEngine().resize();
  96472. this._hasEnteredVR = false;
  96473. }
  96474. };
  96475. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  96476. /**
  96477. * The position of the vr experience helper.
  96478. */
  96479. get: function () {
  96480. return this._position;
  96481. },
  96482. /**
  96483. * Sets the position of the vr experience helper.
  96484. */
  96485. set: function (value) {
  96486. this._position = value;
  96487. if (this._scene.activeCamera) {
  96488. this._scene.activeCamera.position = value;
  96489. }
  96490. },
  96491. enumerable: true,
  96492. configurable: true
  96493. });
  96494. /**
  96495. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  96496. */
  96497. VRExperienceHelper.prototype.enableInteractions = function () {
  96498. var _this = this;
  96499. if (!this._interactionsEnabled) {
  96500. this._interactionsRequested = true;
  96501. if (this._leftController) {
  96502. this._enableInteractionOnController(this._leftController);
  96503. }
  96504. if (this._rightController) {
  96505. this._enableInteractionOnController(this._rightController);
  96506. }
  96507. this.raySelectionPredicate = function (mesh) {
  96508. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  96509. };
  96510. this.meshSelectionPredicate = function (mesh) {
  96511. return true;
  96512. };
  96513. this._raySelectionPredicate = function (mesh) {
  96514. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  96515. && mesh.name.indexOf("teleportationTarget") === -1
  96516. && mesh.name.indexOf("torusTeleportation") === -1)) {
  96517. return _this.raySelectionPredicate(mesh);
  96518. }
  96519. return false;
  96520. };
  96521. this._interactionsEnabled = true;
  96522. }
  96523. };
  96524. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  96525. get: function () {
  96526. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  96527. },
  96528. enumerable: true,
  96529. configurable: true
  96530. });
  96531. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  96532. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  96533. if (this._floorMeshesCollection[i].id === mesh.id) {
  96534. return true;
  96535. }
  96536. }
  96537. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  96538. return true;
  96539. }
  96540. return false;
  96541. };
  96542. /**
  96543. * Adds a floor mesh to be used for teleportation.
  96544. * @param floorMesh the mesh to be used for teleportation.
  96545. */
  96546. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  96547. if (!this._floorMeshesCollection) {
  96548. return;
  96549. }
  96550. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  96551. return;
  96552. }
  96553. this._floorMeshesCollection.push(floorMesh);
  96554. };
  96555. /**
  96556. * Removes a floor mesh from being used for teleportation.
  96557. * @param floorMesh the mesh to be removed.
  96558. */
  96559. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  96560. if (!this._floorMeshesCollection) {
  96561. return;
  96562. }
  96563. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  96564. if (meshIndex !== -1) {
  96565. this._floorMeshesCollection.splice(meshIndex, 1);
  96566. }
  96567. };
  96568. /**
  96569. * Enables interactions and teleportation using the VR controllers and gaze.
  96570. * @param vrTeleportationOptions options to modify teleportation behavior.
  96571. */
  96572. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  96573. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  96574. if (!this._teleportationInitialized) {
  96575. this._teleportationRequested = true;
  96576. this.enableInteractions();
  96577. if (vrTeleportationOptions.floorMeshName) {
  96578. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  96579. }
  96580. if (vrTeleportationOptions.floorMeshes) {
  96581. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  96582. }
  96583. if (this._leftController != null) {
  96584. this._enableTeleportationOnController(this._leftController);
  96585. }
  96586. if (this._rightController != null) {
  96587. this._enableTeleportationOnController(this._rightController);
  96588. }
  96589. // Creates an image processing post process for the vignette not relying
  96590. // on the main scene configuration for image processing to reduce setup and spaces
  96591. // (gamma/linear) conflicts.
  96592. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  96593. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  96594. imageProcessingConfiguration.vignetteEnabled = true;
  96595. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  96596. this._webVRCamera.detachPostProcess(this._postProcessMove);
  96597. this._teleportationInitialized = true;
  96598. if (this._isDefaultTeleportationTarget) {
  96599. this._createTeleportationCircles();
  96600. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  96601. }
  96602. }
  96603. };
  96604. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  96605. var _this = this;
  96606. var controllerMesh = controller.webVRController.mesh;
  96607. if (controllerMesh) {
  96608. controller._interactionsEnabled = true;
  96609. controller._activatePointer();
  96610. if (this.webVROptions.laserToggle) {
  96611. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  96612. // Enabling / disabling laserPointer
  96613. if (_this._displayLaserPointer && stateObject.value === 1) {
  96614. if (controller._activePointer) {
  96615. controller._deactivatePointer();
  96616. }
  96617. else {
  96618. controller._activatePointer();
  96619. }
  96620. if (_this.displayGaze) {
  96621. controller._gazeTracker.isVisible = controller._activePointer;
  96622. }
  96623. }
  96624. });
  96625. }
  96626. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  96627. var gazer = controller;
  96628. if (_this._noControllerIsActive) {
  96629. gazer = _this._cameraGazer;
  96630. }
  96631. if (!gazer._pointerDownOnMeshAsked) {
  96632. if (stateObject.value > _this._padSensibilityUp) {
  96633. gazer._selectionPointerDown();
  96634. }
  96635. }
  96636. else if (stateObject.value < _this._padSensibilityDown) {
  96637. gazer._selectionPointerUp();
  96638. }
  96639. });
  96640. }
  96641. };
  96642. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  96643. // Dont teleport if another gaze already requested teleportation
  96644. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  96645. return;
  96646. }
  96647. if (!gazer._teleportationRequestInitiated) {
  96648. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  96649. gazer._activatePointer();
  96650. gazer._teleportationRequestInitiated = true;
  96651. }
  96652. }
  96653. else {
  96654. // Listening to the proper controller values changes to confirm teleportation
  96655. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  96656. if (this._teleportActive) {
  96657. this._teleportCamera(this._haloCenter);
  96658. }
  96659. gazer._teleportationRequestInitiated = false;
  96660. }
  96661. }
  96662. };
  96663. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  96664. // Only rotate when user is not currently selecting a teleportation location
  96665. if (gazer._teleportationRequestInitiated) {
  96666. return;
  96667. }
  96668. if (!gazer._rotationLeftAsked) {
  96669. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  96670. gazer._rotationLeftAsked = true;
  96671. if (this._rotationAllowed) {
  96672. this._rotateCamera(false);
  96673. }
  96674. }
  96675. }
  96676. else {
  96677. if (stateObject.x > -this._padSensibilityDown) {
  96678. gazer._rotationLeftAsked = false;
  96679. }
  96680. }
  96681. if (!gazer._rotationRightAsked) {
  96682. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  96683. gazer._rotationRightAsked = true;
  96684. if (this._rotationAllowed) {
  96685. this._rotateCamera(true);
  96686. }
  96687. }
  96688. }
  96689. else {
  96690. if (stateObject.x < this._padSensibilityDown) {
  96691. gazer._rotationRightAsked = false;
  96692. }
  96693. }
  96694. };
  96695. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  96696. // Only teleport backwards when user is not currently selecting a teleportation location
  96697. if (gazer._teleportationRequestInitiated) {
  96698. return;
  96699. }
  96700. // Teleport backwards
  96701. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  96702. if (!gazer._teleportationBackRequestInitiated) {
  96703. if (!this.currentVRCamera) {
  96704. return;
  96705. }
  96706. // Get rotation and position of the current camera
  96707. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  96708. var position = this.currentVRCamera.position;
  96709. // If the camera has device position, use that instead
  96710. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  96711. rotation = this.currentVRCamera.deviceRotationQuaternion;
  96712. position = this.currentVRCamera.devicePosition;
  96713. }
  96714. // Get matrix with only the y rotation of the device rotation
  96715. rotation.toEulerAnglesToRef(this._workingVector);
  96716. this._workingVector.z = 0;
  96717. this._workingVector.x = 0;
  96718. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  96719. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  96720. // Rotate backwards ray by device rotation to cast at the ground behind the user
  96721. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  96722. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  96723. var ray = new BABYLON.Ray(position, this._workingVector);
  96724. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96725. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  96726. this._teleportCamera(hit.pickedPoint);
  96727. }
  96728. gazer._teleportationBackRequestInitiated = true;
  96729. }
  96730. }
  96731. else {
  96732. gazer._teleportationBackRequestInitiated = false;
  96733. }
  96734. };
  96735. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  96736. var _this = this;
  96737. var controllerMesh = controller.webVRController.mesh;
  96738. if (controllerMesh) {
  96739. if (!controller._interactionsEnabled) {
  96740. this._enableInteractionOnController(controller);
  96741. }
  96742. controller._interactionsEnabled = true;
  96743. controller._teleportationEnabled = true;
  96744. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96745. controller._dpadPressed = false;
  96746. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  96747. controller._dpadPressed = stateObject.pressed;
  96748. if (!controller._dpadPressed) {
  96749. controller._rotationLeftAsked = false;
  96750. controller._rotationRightAsked = false;
  96751. controller._teleportationBackRequestInitiated = false;
  96752. }
  96753. });
  96754. }
  96755. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  96756. if (_this.teleportationEnabled) {
  96757. _this._checkTeleportBackwards(stateObject, controller);
  96758. _this._checkTeleportWithRay(stateObject, controller);
  96759. }
  96760. _this._checkRotate(stateObject, controller);
  96761. });
  96762. }
  96763. };
  96764. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  96765. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  96766. this._teleportationTarget.isPickable = false;
  96767. var length = 512;
  96768. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  96769. dynamicTexture.hasAlpha = true;
  96770. var context = dynamicTexture.getContext();
  96771. var centerX = length / 2;
  96772. var centerY = length / 2;
  96773. var radius = 200;
  96774. context.beginPath();
  96775. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  96776. context.fillStyle = this._teleportationFillColor;
  96777. context.fill();
  96778. context.lineWidth = 10;
  96779. context.strokeStyle = this._teleportationBorderColor;
  96780. context.stroke();
  96781. context.closePath();
  96782. dynamicTexture.update();
  96783. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  96784. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  96785. this._teleportationTarget.material = teleportationCircleMaterial;
  96786. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  96787. torus.isPickable = false;
  96788. torus.parent = this._teleportationTarget;
  96789. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96790. var keys = [];
  96791. keys.push({
  96792. frame: 0,
  96793. value: 0
  96794. });
  96795. keys.push({
  96796. frame: 30,
  96797. value: 0.4
  96798. });
  96799. keys.push({
  96800. frame: 60,
  96801. value: 0
  96802. });
  96803. animationInnerCircle.setKeys(keys);
  96804. var easingFunction = new BABYLON.SineEase();
  96805. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96806. animationInnerCircle.setEasingFunction(easingFunction);
  96807. torus.animations = [];
  96808. torus.animations.push(animationInnerCircle);
  96809. this._scene.beginAnimation(torus, 0, 60, true);
  96810. this._hideTeleportationTarget();
  96811. };
  96812. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  96813. this._teleportActive = true;
  96814. if (this._teleportationInitialized) {
  96815. this._teleportationTarget.isVisible = true;
  96816. if (this._isDefaultTeleportationTarget) {
  96817. this._teleportationTarget.getChildren()[0].isVisible = true;
  96818. }
  96819. }
  96820. };
  96821. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  96822. this._teleportActive = false;
  96823. if (this._teleportationInitialized) {
  96824. this._teleportationTarget.isVisible = false;
  96825. if (this._isDefaultTeleportationTarget) {
  96826. this._teleportationTarget.getChildren()[0].isVisible = false;
  96827. }
  96828. }
  96829. };
  96830. VRExperienceHelper.prototype._rotateCamera = function (right) {
  96831. var _this = this;
  96832. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96833. return;
  96834. }
  96835. if (right) {
  96836. this._rotationAngle++;
  96837. }
  96838. else {
  96839. this._rotationAngle--;
  96840. }
  96841. this.currentVRCamera.animations = [];
  96842. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  96843. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96844. var animationRotationKeys = [];
  96845. animationRotationKeys.push({
  96846. frame: 0,
  96847. value: this.currentVRCamera.rotationQuaternion
  96848. });
  96849. animationRotationKeys.push({
  96850. frame: 6,
  96851. value: target
  96852. });
  96853. animationRotation.setKeys(animationRotationKeys);
  96854. animationRotation.setEasingFunction(this._circleEase);
  96855. this.currentVRCamera.animations.push(animationRotation);
  96856. this._postProcessMove.animations = [];
  96857. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96858. var vignetteWeightKeys = [];
  96859. vignetteWeightKeys.push({
  96860. frame: 0,
  96861. value: 0
  96862. });
  96863. vignetteWeightKeys.push({
  96864. frame: 3,
  96865. value: 4
  96866. });
  96867. vignetteWeightKeys.push({
  96868. frame: 6,
  96869. value: 0
  96870. });
  96871. animationPP.setKeys(vignetteWeightKeys);
  96872. animationPP.setEasingFunction(this._circleEase);
  96873. this._postProcessMove.animations.push(animationPP);
  96874. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96875. var vignetteStretchKeys = [];
  96876. vignetteStretchKeys.push({
  96877. frame: 0,
  96878. value: 0
  96879. });
  96880. vignetteStretchKeys.push({
  96881. frame: 3,
  96882. value: 10
  96883. });
  96884. vignetteStretchKeys.push({
  96885. frame: 6,
  96886. value: 0
  96887. });
  96888. animationPP2.setKeys(vignetteStretchKeys);
  96889. animationPP2.setEasingFunction(this._circleEase);
  96890. this._postProcessMove.animations.push(animationPP2);
  96891. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96892. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96893. this._postProcessMove.samples = 4;
  96894. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96895. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  96896. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96897. });
  96898. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  96899. };
  96900. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  96901. if (hit.pickedPoint) {
  96902. if (gazer._teleportationRequestInitiated) {
  96903. this._displayTeleportationTarget();
  96904. this._haloCenter.copyFrom(hit.pickedPoint);
  96905. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  96906. }
  96907. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  96908. if (pickNormal) {
  96909. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96910. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96911. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  96912. }
  96913. this._teleportationTarget.position.y += 0.1;
  96914. }
  96915. };
  96916. VRExperienceHelper.prototype._teleportCamera = function (location) {
  96917. var _this = this;
  96918. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96919. return;
  96920. }
  96921. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  96922. // offset of the headset from the anchor.
  96923. if (this.webVRCamera.leftCamera) {
  96924. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  96925. this._workingVector.subtractInPlace(this.webVRCamera.position);
  96926. location.subtractToRef(this._workingVector, this._workingVector);
  96927. }
  96928. else {
  96929. this._workingVector.copyFrom(location);
  96930. }
  96931. // Add height to account for user's height offset
  96932. if (this.isInVRMode) {
  96933. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  96934. }
  96935. else {
  96936. this._workingVector.y += this._defaultHeight;
  96937. }
  96938. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  96939. // Create animation from the camera's position to the new location
  96940. this.currentVRCamera.animations = [];
  96941. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96942. var animationCameraTeleportationKeys = [{
  96943. frame: 0,
  96944. value: this.currentVRCamera.position
  96945. },
  96946. {
  96947. frame: 11,
  96948. value: this._workingVector
  96949. }
  96950. ];
  96951. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  96952. animationCameraTeleportation.setEasingFunction(this._circleEase);
  96953. this.currentVRCamera.animations.push(animationCameraTeleportation);
  96954. this._postProcessMove.animations = [];
  96955. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96956. var vignetteWeightKeys = [];
  96957. vignetteWeightKeys.push({
  96958. frame: 0,
  96959. value: 0
  96960. });
  96961. vignetteWeightKeys.push({
  96962. frame: 5,
  96963. value: 8
  96964. });
  96965. vignetteWeightKeys.push({
  96966. frame: 11,
  96967. value: 0
  96968. });
  96969. animationPP.setKeys(vignetteWeightKeys);
  96970. this._postProcessMove.animations.push(animationPP);
  96971. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96972. var vignetteStretchKeys = [];
  96973. vignetteStretchKeys.push({
  96974. frame: 0,
  96975. value: 0
  96976. });
  96977. vignetteStretchKeys.push({
  96978. frame: 5,
  96979. value: 10
  96980. });
  96981. vignetteStretchKeys.push({
  96982. frame: 11,
  96983. value: 0
  96984. });
  96985. animationPP2.setKeys(vignetteStretchKeys);
  96986. this._postProcessMove.animations.push(animationPP2);
  96987. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96988. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96989. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96990. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  96991. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96992. });
  96993. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  96994. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  96995. });
  96996. this._hideTeleportationTarget();
  96997. };
  96998. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  96999. if (normal) {
  97000. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  97001. if (angle < Math.PI / 2) {
  97002. normal.scaleInPlace(-1);
  97003. }
  97004. }
  97005. return normal;
  97006. };
  97007. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  97008. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97009. return;
  97010. }
  97011. var ray = gazer._getForwardRay(this._rayLength);
  97012. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97013. if (hit) {
  97014. // Populate the contrllers mesh that can be used for drag/drop
  97015. if (gazer._laserPointer) {
  97016. hit.originMesh = gazer._laserPointer.parent;
  97017. }
  97018. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  97019. }
  97020. gazer._currentHit = hit;
  97021. // Moving the gazeTracker on the mesh face targetted
  97022. if (hit && hit.pickedPoint) {
  97023. if (this._displayGaze) {
  97024. var multiplier = 1;
  97025. gazer._gazeTracker.isVisible = true;
  97026. if (gazer._isActionableMesh) {
  97027. multiplier = 3;
  97028. }
  97029. if (this.updateGazeTrackerScale) {
  97030. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  97031. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  97032. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  97033. }
  97034. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  97035. // To avoid z-fighting
  97036. var deltaFighting = 0.002;
  97037. if (pickNormal) {
  97038. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97039. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97040. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  97041. }
  97042. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  97043. if (gazer._gazeTracker.position.x < 0) {
  97044. gazer._gazeTracker.position.x += deltaFighting;
  97045. }
  97046. else {
  97047. gazer._gazeTracker.position.x -= deltaFighting;
  97048. }
  97049. if (gazer._gazeTracker.position.y < 0) {
  97050. gazer._gazeTracker.position.y += deltaFighting;
  97051. }
  97052. else {
  97053. gazer._gazeTracker.position.y -= deltaFighting;
  97054. }
  97055. if (gazer._gazeTracker.position.z < 0) {
  97056. gazer._gazeTracker.position.z += deltaFighting;
  97057. }
  97058. else {
  97059. gazer._gazeTracker.position.z -= deltaFighting;
  97060. }
  97061. }
  97062. // Changing the size of the laser pointer based on the distance from the targetted point
  97063. gazer._updatePointerDistance(hit.distance);
  97064. }
  97065. else {
  97066. gazer._updatePointerDistance();
  97067. gazer._gazeTracker.isVisible = false;
  97068. }
  97069. if (hit && hit.pickedMesh) {
  97070. // The object selected is the floor, we're in a teleportation scenario
  97071. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  97072. // Moving the teleportation area to this targetted point
  97073. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  97074. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  97075. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97076. }
  97077. gazer._currentMeshSelected = null;
  97078. if (gazer._teleportationRequestInitiated) {
  97079. this._moveTeleportationSelectorTo(hit, gazer, ray);
  97080. }
  97081. return;
  97082. }
  97083. // If not, we're in a selection scenario
  97084. //this._teleportationAllowed = false;
  97085. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  97086. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  97087. this.onNewMeshPicked.notifyObservers(hit);
  97088. gazer._currentMeshSelected = hit.pickedMesh;
  97089. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  97090. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  97091. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  97092. gazer._isActionableMesh = true;
  97093. }
  97094. else {
  97095. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97096. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97097. gazer._isActionableMesh = false;
  97098. }
  97099. try {
  97100. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  97101. }
  97102. catch (err) {
  97103. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  97104. }
  97105. }
  97106. else {
  97107. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97108. gazer._currentMeshSelected = null;
  97109. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97110. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97111. }
  97112. }
  97113. }
  97114. else {
  97115. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97116. gazer._currentMeshSelected = null;
  97117. //this._teleportationAllowed = false;
  97118. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97119. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97120. }
  97121. };
  97122. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  97123. if (mesh) {
  97124. this.onSelectedMeshUnselected.notifyObservers(mesh);
  97125. }
  97126. };
  97127. /**
  97128. * Sets the color of the laser ray from the vr controllers.
  97129. * @param color new color for the ray.
  97130. */
  97131. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  97132. if (this._leftController) {
  97133. this._leftController._setLaserPointerColor(color);
  97134. }
  97135. if (this._rightController) {
  97136. this._rightController._setLaserPointerColor(color);
  97137. }
  97138. };
  97139. /**
  97140. * Sets the color of the ray from the vr headsets gaze.
  97141. * @param color new color for the ray.
  97142. */
  97143. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  97144. if (!this._cameraGazer._gazeTracker.material) {
  97145. return;
  97146. }
  97147. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  97148. if (this._leftController) {
  97149. this._leftController._gazeTracker.material.emissiveColor = color;
  97150. }
  97151. if (this._rightController) {
  97152. this._rightController._gazeTracker.material.emissiveColor = color;
  97153. }
  97154. };
  97155. /**
  97156. * Exits VR and disposes of the vr experience helper
  97157. */
  97158. VRExperienceHelper.prototype.dispose = function () {
  97159. if (this.isInVRMode) {
  97160. this.exitVR();
  97161. }
  97162. if (this._postProcessMove) {
  97163. this._postProcessMove.dispose();
  97164. }
  97165. if (this._webVRCamera) {
  97166. this._webVRCamera.dispose();
  97167. }
  97168. if (this._vrDeviceOrientationCamera) {
  97169. this._vrDeviceOrientationCamera.dispose();
  97170. }
  97171. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  97172. document.body.removeChild(this._btnVR);
  97173. }
  97174. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  97175. this._deviceOrientationCamera.dispose();
  97176. }
  97177. if (this._cameraGazer) {
  97178. this._cameraGazer.dispose();
  97179. }
  97180. if (this._leftController) {
  97181. this._leftController.dispose();
  97182. }
  97183. if (this._rightController) {
  97184. this._rightController.dispose();
  97185. }
  97186. if (this._teleportationTarget) {
  97187. this._teleportationTarget.dispose();
  97188. }
  97189. this._floorMeshesCollection = [];
  97190. document.removeEventListener("keydown", this._onKeyDown);
  97191. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97192. window.removeEventListener("resize", this._onResize);
  97193. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  97194. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  97195. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  97196. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  97197. document.onmsfullscreenchange = null;
  97198. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  97199. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  97200. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  97201. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97202. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  97203. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  97204. this._scene.unregisterBeforeRender(this.beforeRender);
  97205. };
  97206. /**
  97207. * Gets the name of the VRExperienceHelper class
  97208. * @returns "VRExperienceHelper"
  97209. */
  97210. VRExperienceHelper.prototype.getClassName = function () {
  97211. return "VRExperienceHelper";
  97212. };
  97213. return VRExperienceHelper;
  97214. }());
  97215. BABYLON.VRExperienceHelper = VRExperienceHelper;
  97216. })(BABYLON || (BABYLON = {}));
  97217. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  97218. // Mainly based on these 2 articles :
  97219. // 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
  97220. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  97221. var BABYLON;
  97222. (function (BABYLON) {
  97223. /**
  97224. * Defines the potential axis of a Joystick
  97225. */
  97226. var JoystickAxis;
  97227. (function (JoystickAxis) {
  97228. /** X axis */
  97229. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  97230. /** Y axis */
  97231. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  97232. /** Z axis */
  97233. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  97234. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  97235. /**
  97236. * Class used to define virtual joystick (used in touch mode)
  97237. */
  97238. var VirtualJoystick = /** @class */ (function () {
  97239. /**
  97240. * Creates a new virtual joystick
  97241. * @param leftJoystick defines that the joystick is for left hand (false by default)
  97242. */
  97243. function VirtualJoystick(leftJoystick) {
  97244. var _this = this;
  97245. if (leftJoystick) {
  97246. this._leftJoystick = true;
  97247. }
  97248. else {
  97249. this._leftJoystick = false;
  97250. }
  97251. VirtualJoystick._globalJoystickIndex++;
  97252. // By default left & right arrow keys are moving the X
  97253. // and up & down keys are moving the Y
  97254. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97255. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97256. this.reverseLeftRight = false;
  97257. this.reverseUpDown = false;
  97258. // collections of pointers
  97259. this._touches = new BABYLON.StringDictionary();
  97260. this.deltaPosition = BABYLON.Vector3.Zero();
  97261. this._joystickSensibility = 25;
  97262. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97263. this._onResize = function (evt) {
  97264. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97265. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97266. if (VirtualJoystick.vjCanvas) {
  97267. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  97268. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  97269. }
  97270. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  97271. };
  97272. // injecting a canvas element on top of the canvas 3D game
  97273. if (!VirtualJoystick.vjCanvas) {
  97274. window.addEventListener("resize", this._onResize, false);
  97275. VirtualJoystick.vjCanvas = document.createElement("canvas");
  97276. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97277. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97278. VirtualJoystick.vjCanvas.width = window.innerWidth;
  97279. VirtualJoystick.vjCanvas.height = window.innerHeight;
  97280. VirtualJoystick.vjCanvas.style.width = "100%";
  97281. VirtualJoystick.vjCanvas.style.height = "100%";
  97282. VirtualJoystick.vjCanvas.style.position = "absolute";
  97283. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  97284. VirtualJoystick.vjCanvas.style.top = "0px";
  97285. VirtualJoystick.vjCanvas.style.left = "0px";
  97286. VirtualJoystick.vjCanvas.style.zIndex = "5";
  97287. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  97288. // Support for jQuery PEP polyfill
  97289. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  97290. var context = VirtualJoystick.vjCanvas.getContext('2d');
  97291. if (!context) {
  97292. throw new Error("Unable to create canvas for virtual joystick");
  97293. }
  97294. VirtualJoystick.vjCanvasContext = context;
  97295. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  97296. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97297. document.body.appendChild(VirtualJoystick.vjCanvas);
  97298. }
  97299. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  97300. this.pressed = false;
  97301. // default joystick color
  97302. this._joystickColor = "cyan";
  97303. this._joystickPointerID = -1;
  97304. // current joystick position
  97305. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  97306. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  97307. // origin joystick position
  97308. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  97309. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  97310. this._onPointerDownHandlerRef = function (evt) {
  97311. _this._onPointerDown(evt);
  97312. };
  97313. this._onPointerMoveHandlerRef = function (evt) {
  97314. _this._onPointerMove(evt);
  97315. };
  97316. this._onPointerUpHandlerRef = function (evt) {
  97317. _this._onPointerUp(evt);
  97318. };
  97319. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  97320. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  97321. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  97322. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  97323. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  97324. evt.preventDefault(); // Disables system menu
  97325. }, false);
  97326. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97327. }
  97328. /**
  97329. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  97330. * @param newJoystickSensibility defines the new sensibility
  97331. */
  97332. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  97333. this._joystickSensibility = newJoystickSensibility;
  97334. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97335. };
  97336. VirtualJoystick.prototype._onPointerDown = function (e) {
  97337. var positionOnScreenCondition;
  97338. e.preventDefault();
  97339. if (this._leftJoystick === true) {
  97340. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  97341. }
  97342. else {
  97343. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  97344. }
  97345. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  97346. // First contact will be dedicated to the virtual joystick
  97347. this._joystickPointerID = e.pointerId;
  97348. this._joystickPointerStartPos.x = e.clientX;
  97349. this._joystickPointerStartPos.y = e.clientY;
  97350. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  97351. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  97352. this._deltaJoystickVector.x = 0;
  97353. this._deltaJoystickVector.y = 0;
  97354. this.pressed = true;
  97355. this._touches.add(e.pointerId.toString(), e);
  97356. }
  97357. else {
  97358. // You can only trigger the action buttons with a joystick declared
  97359. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  97360. this._action();
  97361. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  97362. }
  97363. }
  97364. };
  97365. VirtualJoystick.prototype._onPointerMove = function (e) {
  97366. // If the current pointer is the one associated to the joystick (first touch contact)
  97367. if (this._joystickPointerID == e.pointerId) {
  97368. this._joystickPointerPos.x = e.clientX;
  97369. this._joystickPointerPos.y = e.clientY;
  97370. this._deltaJoystickVector = this._joystickPointerPos.clone();
  97371. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  97372. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  97373. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  97374. switch (this._axisTargetedByLeftAndRight) {
  97375. case JoystickAxis.X:
  97376. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  97377. break;
  97378. case JoystickAxis.Y:
  97379. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  97380. break;
  97381. case JoystickAxis.Z:
  97382. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  97383. break;
  97384. }
  97385. var directionUpDown = this.reverseUpDown ? 1 : -1;
  97386. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  97387. switch (this._axisTargetedByUpAndDown) {
  97388. case JoystickAxis.X:
  97389. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  97390. break;
  97391. case JoystickAxis.Y:
  97392. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  97393. break;
  97394. case JoystickAxis.Z:
  97395. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  97396. break;
  97397. }
  97398. }
  97399. else {
  97400. var data = this._touches.get(e.pointerId.toString());
  97401. if (data) {
  97402. data.x = e.clientX;
  97403. data.y = e.clientY;
  97404. }
  97405. }
  97406. };
  97407. VirtualJoystick.prototype._onPointerUp = function (e) {
  97408. if (this._joystickPointerID == e.pointerId) {
  97409. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  97410. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  97411. this._joystickPointerID = -1;
  97412. this.pressed = false;
  97413. }
  97414. else {
  97415. var touch = this._touches.get(e.pointerId.toString());
  97416. if (touch) {
  97417. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97418. }
  97419. }
  97420. this._deltaJoystickVector.x = 0;
  97421. this._deltaJoystickVector.y = 0;
  97422. this._touches.remove(e.pointerId.toString());
  97423. };
  97424. /**
  97425. * Change the color of the virtual joystick
  97426. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  97427. */
  97428. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  97429. this._joystickColor = newColor;
  97430. };
  97431. /**
  97432. * Defines a callback to call when the joystick is touched
  97433. * @param action defines the callback
  97434. */
  97435. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  97436. this._action = action;
  97437. };
  97438. /**
  97439. * Defines which axis you'd like to control for left & right
  97440. * @param axis defines the axis to use
  97441. */
  97442. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  97443. switch (axis) {
  97444. case JoystickAxis.X:
  97445. case JoystickAxis.Y:
  97446. case JoystickAxis.Z:
  97447. this._axisTargetedByLeftAndRight = axis;
  97448. break;
  97449. default:
  97450. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97451. break;
  97452. }
  97453. };
  97454. /**
  97455. * Defines which axis you'd like to control for up & down
  97456. * @param axis defines the axis to use
  97457. */
  97458. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  97459. switch (axis) {
  97460. case JoystickAxis.X:
  97461. case JoystickAxis.Y:
  97462. case JoystickAxis.Z:
  97463. this._axisTargetedByUpAndDown = axis;
  97464. break;
  97465. default:
  97466. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97467. break;
  97468. }
  97469. };
  97470. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  97471. var _this = this;
  97472. if (this.pressed) {
  97473. this._touches.forEach(function (key, touch) {
  97474. if (touch.pointerId === _this._joystickPointerID) {
  97475. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  97476. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  97477. VirtualJoystick.vjCanvasContext.beginPath();
  97478. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97479. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97480. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  97481. VirtualJoystick.vjCanvasContext.stroke();
  97482. VirtualJoystick.vjCanvasContext.closePath();
  97483. VirtualJoystick.vjCanvasContext.beginPath();
  97484. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97485. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97486. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  97487. VirtualJoystick.vjCanvasContext.stroke();
  97488. VirtualJoystick.vjCanvasContext.closePath();
  97489. VirtualJoystick.vjCanvasContext.beginPath();
  97490. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97491. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  97492. VirtualJoystick.vjCanvasContext.stroke();
  97493. VirtualJoystick.vjCanvasContext.closePath();
  97494. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  97495. }
  97496. else {
  97497. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97498. VirtualJoystick.vjCanvasContext.beginPath();
  97499. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  97500. VirtualJoystick.vjCanvasContext.beginPath();
  97501. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  97502. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97503. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  97504. VirtualJoystick.vjCanvasContext.stroke();
  97505. VirtualJoystick.vjCanvasContext.closePath();
  97506. touch.prevX = touch.x;
  97507. touch.prevY = touch.y;
  97508. }
  97509. ;
  97510. });
  97511. }
  97512. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97513. };
  97514. /**
  97515. * Release internal HTML canvas
  97516. */
  97517. VirtualJoystick.prototype.releaseCanvas = function () {
  97518. if (VirtualJoystick.vjCanvas) {
  97519. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  97520. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  97521. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  97522. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  97523. window.removeEventListener("resize", this._onResize);
  97524. document.body.removeChild(VirtualJoystick.vjCanvas);
  97525. VirtualJoystick.vjCanvas = null;
  97526. }
  97527. };
  97528. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  97529. VirtualJoystick._globalJoystickIndex = 0;
  97530. return VirtualJoystick;
  97531. }());
  97532. BABYLON.VirtualJoystick = VirtualJoystick;
  97533. })(BABYLON || (BABYLON = {}));
  97534. //# sourceMappingURL=babylon.virtualJoystick.js.map
  97535. var BABYLON;
  97536. (function (BABYLON) {
  97537. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  97538. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  97539. });
  97540. // We're mainly based on the logic defined into the FreeCamera code
  97541. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  97542. __extends(VirtualJoysticksCamera, _super);
  97543. function VirtualJoysticksCamera(name, position, scene) {
  97544. var _this = _super.call(this, name, position, scene) || this;
  97545. _this.inputs.addVirtualJoystick();
  97546. return _this;
  97547. }
  97548. VirtualJoysticksCamera.prototype.getClassName = function () {
  97549. return "VirtualJoysticksCamera";
  97550. };
  97551. return VirtualJoysticksCamera;
  97552. }(BABYLON.FreeCamera));
  97553. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  97554. })(BABYLON || (BABYLON = {}));
  97555. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  97556. var BABYLON;
  97557. (function (BABYLON) {
  97558. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  97559. function FreeCameraVirtualJoystickInput() {
  97560. }
  97561. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  97562. return this._leftjoystick;
  97563. };
  97564. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  97565. return this._rightjoystick;
  97566. };
  97567. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  97568. if (this._leftjoystick) {
  97569. var camera = this.camera;
  97570. var speed = camera._computeLocalCameraSpeed() * 50;
  97571. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  97572. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  97573. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  97574. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  97575. if (!this._leftjoystick.pressed) {
  97576. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  97577. }
  97578. if (!this._rightjoystick.pressed) {
  97579. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  97580. }
  97581. }
  97582. };
  97583. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  97584. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  97585. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  97586. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  97587. this._leftjoystick.setJoystickSensibility(0.15);
  97588. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  97589. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  97590. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  97591. this._rightjoystick.reverseUpDown = true;
  97592. this._rightjoystick.setJoystickSensibility(0.05);
  97593. this._rightjoystick.setJoystickColor("yellow");
  97594. };
  97595. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  97596. this._leftjoystick.releaseCanvas();
  97597. this._rightjoystick.releaseCanvas();
  97598. };
  97599. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  97600. return "FreeCameraVirtualJoystickInput";
  97601. };
  97602. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  97603. return "virtualJoystick";
  97604. };
  97605. return FreeCameraVirtualJoystickInput;
  97606. }());
  97607. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  97608. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  97609. })(BABYLON || (BABYLON = {}));
  97610. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  97611. var BABYLON;
  97612. (function (BABYLON) {
  97613. var SimplificationSettings = /** @class */ (function () {
  97614. function SimplificationSettings(quality, distance, optimizeMesh) {
  97615. this.quality = quality;
  97616. this.distance = distance;
  97617. this.optimizeMesh = optimizeMesh;
  97618. }
  97619. return SimplificationSettings;
  97620. }());
  97621. BABYLON.SimplificationSettings = SimplificationSettings;
  97622. var SimplificationQueue = /** @class */ (function () {
  97623. function SimplificationQueue() {
  97624. this.running = false;
  97625. this._simplificationArray = [];
  97626. }
  97627. SimplificationQueue.prototype.addTask = function (task) {
  97628. this._simplificationArray.push(task);
  97629. };
  97630. SimplificationQueue.prototype.executeNext = function () {
  97631. var task = this._simplificationArray.pop();
  97632. if (task) {
  97633. this.running = true;
  97634. this.runSimplification(task);
  97635. }
  97636. else {
  97637. this.running = false;
  97638. }
  97639. };
  97640. SimplificationQueue.prototype.runSimplification = function (task) {
  97641. var _this = this;
  97642. if (task.parallelProcessing) {
  97643. //parallel simplifier
  97644. task.settings.forEach(function (setting) {
  97645. var simplifier = _this.getSimplifier(task);
  97646. simplifier.simplify(setting, function (newMesh) {
  97647. task.mesh.addLODLevel(setting.distance, newMesh);
  97648. newMesh.isVisible = true;
  97649. //check if it is the last
  97650. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  97651. //all done, run the success callback.
  97652. task.successCallback();
  97653. }
  97654. _this.executeNext();
  97655. });
  97656. });
  97657. }
  97658. else {
  97659. //single simplifier.
  97660. var simplifier = this.getSimplifier(task);
  97661. var runDecimation = function (setting, callback) {
  97662. simplifier.simplify(setting, function (newMesh) {
  97663. task.mesh.addLODLevel(setting.distance, newMesh);
  97664. newMesh.isVisible = true;
  97665. //run the next quality level
  97666. callback();
  97667. });
  97668. };
  97669. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  97670. runDecimation(task.settings[loop.index], function () {
  97671. loop.executeNext();
  97672. });
  97673. }, function () {
  97674. //execution ended, run the success callback.
  97675. if (task.successCallback) {
  97676. task.successCallback();
  97677. }
  97678. _this.executeNext();
  97679. });
  97680. }
  97681. };
  97682. SimplificationQueue.prototype.getSimplifier = function (task) {
  97683. switch (task.simplificationType) {
  97684. case SimplificationType.QUADRATIC:
  97685. default:
  97686. return new QuadraticErrorSimplification(task.mesh);
  97687. }
  97688. };
  97689. return SimplificationQueue;
  97690. }());
  97691. BABYLON.SimplificationQueue = SimplificationQueue;
  97692. /**
  97693. * The implemented types of simplification
  97694. * At the moment only Quadratic Error Decimation is implemented
  97695. */
  97696. var SimplificationType;
  97697. (function (SimplificationType) {
  97698. /** Quadratic error decimation */
  97699. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  97700. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  97701. var DecimationTriangle = /** @class */ (function () {
  97702. function DecimationTriangle(vertices) {
  97703. this.vertices = vertices;
  97704. this.error = new Array(4);
  97705. this.deleted = false;
  97706. this.isDirty = false;
  97707. this.deletePending = false;
  97708. this.borderFactor = 0;
  97709. }
  97710. return DecimationTriangle;
  97711. }());
  97712. BABYLON.DecimationTriangle = DecimationTriangle;
  97713. var DecimationVertex = /** @class */ (function () {
  97714. function DecimationVertex(position, id) {
  97715. this.position = position;
  97716. this.id = id;
  97717. this.isBorder = true;
  97718. this.q = new QuadraticMatrix();
  97719. this.triangleCount = 0;
  97720. this.triangleStart = 0;
  97721. this.originalOffsets = [];
  97722. }
  97723. DecimationVertex.prototype.updatePosition = function (newPosition) {
  97724. this.position.copyFrom(newPosition);
  97725. };
  97726. return DecimationVertex;
  97727. }());
  97728. BABYLON.DecimationVertex = DecimationVertex;
  97729. var QuadraticMatrix = /** @class */ (function () {
  97730. function QuadraticMatrix(data) {
  97731. this.data = new Array(10);
  97732. for (var i = 0; i < 10; ++i) {
  97733. if (data && data[i]) {
  97734. this.data[i] = data[i];
  97735. }
  97736. else {
  97737. this.data[i] = 0;
  97738. }
  97739. }
  97740. }
  97741. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  97742. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  97743. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  97744. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  97745. return det;
  97746. };
  97747. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  97748. for (var i = 0; i < 10; ++i) {
  97749. this.data[i] += matrix.data[i];
  97750. }
  97751. };
  97752. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  97753. for (var i = 0; i < 10; ++i) {
  97754. this.data[i] += data[i];
  97755. }
  97756. };
  97757. QuadraticMatrix.prototype.add = function (matrix) {
  97758. var m = new QuadraticMatrix();
  97759. for (var i = 0; i < 10; ++i) {
  97760. m.data[i] = this.data[i] + matrix.data[i];
  97761. }
  97762. return m;
  97763. };
  97764. QuadraticMatrix.FromData = function (a, b, c, d) {
  97765. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  97766. };
  97767. //returning an array to avoid garbage collection
  97768. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  97769. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  97770. };
  97771. return QuadraticMatrix;
  97772. }());
  97773. BABYLON.QuadraticMatrix = QuadraticMatrix;
  97774. var Reference = /** @class */ (function () {
  97775. function Reference(vertexId, triangleId) {
  97776. this.vertexId = vertexId;
  97777. this.triangleId = triangleId;
  97778. }
  97779. return Reference;
  97780. }());
  97781. BABYLON.Reference = Reference;
  97782. /**
  97783. * An implementation of the Quadratic Error simplification algorithm.
  97784. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97785. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  97786. * @author RaananW
  97787. */
  97788. var QuadraticErrorSimplification = /** @class */ (function () {
  97789. function QuadraticErrorSimplification(_mesh) {
  97790. this._mesh = _mesh;
  97791. this.syncIterations = 5000;
  97792. this.aggressiveness = 7;
  97793. this.decimationIterations = 100;
  97794. this.boundingBoxEpsilon = BABYLON.Epsilon;
  97795. }
  97796. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  97797. var _this = this;
  97798. this.initDecimatedMesh();
  97799. //iterating through the submeshes array, one after the other.
  97800. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  97801. _this.initWithMesh(loop.index, function () {
  97802. _this.runDecimation(settings, loop.index, function () {
  97803. loop.executeNext();
  97804. });
  97805. }, settings.optimizeMesh);
  97806. }, function () {
  97807. setTimeout(function () {
  97808. successCallback(_this._reconstructedMesh);
  97809. }, 0);
  97810. });
  97811. };
  97812. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  97813. var _this = this;
  97814. var targetCount = ~~(this.triangles.length * settings.quality);
  97815. var deletedTriangles = 0;
  97816. var triangleCount = this.triangles.length;
  97817. var iterationFunction = function (iteration, callback) {
  97818. setTimeout(function () {
  97819. if (iteration % 5 === 0) {
  97820. _this.updateMesh(iteration === 0);
  97821. }
  97822. for (var i = 0; i < _this.triangles.length; ++i) {
  97823. _this.triangles[i].isDirty = false;
  97824. }
  97825. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  97826. var trianglesIterator = function (i) {
  97827. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  97828. var t = _this.triangles[tIdx];
  97829. if (!t)
  97830. return;
  97831. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  97832. return;
  97833. }
  97834. for (var j = 0; j < 3; ++j) {
  97835. if (t.error[j] < threshold) {
  97836. var deleted0 = [];
  97837. var deleted1 = [];
  97838. var v0 = t.vertices[j];
  97839. var v1 = t.vertices[(j + 1) % 3];
  97840. if (v0.isBorder || v1.isBorder)
  97841. continue;
  97842. var p = BABYLON.Vector3.Zero();
  97843. var n = BABYLON.Vector3.Zero();
  97844. var uv = BABYLON.Vector2.Zero();
  97845. var color = new BABYLON.Color4(0, 0, 0, 1);
  97846. _this.calculateError(v0, v1, p, n, uv, color);
  97847. var delTr = new Array();
  97848. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  97849. continue;
  97850. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  97851. continue;
  97852. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  97853. continue;
  97854. var uniqueArray = new Array();
  97855. delTr.forEach(function (deletedT) {
  97856. if (uniqueArray.indexOf(deletedT) === -1) {
  97857. deletedT.deletePending = true;
  97858. uniqueArray.push(deletedT);
  97859. }
  97860. });
  97861. if (uniqueArray.length % 2 !== 0) {
  97862. continue;
  97863. }
  97864. v0.q = v1.q.add(v0.q);
  97865. v0.updatePosition(p);
  97866. var tStart = _this.references.length;
  97867. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  97868. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  97869. var tCount = _this.references.length - tStart;
  97870. if (tCount <= v0.triangleCount) {
  97871. if (tCount) {
  97872. for (var c = 0; c < tCount; c++) {
  97873. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  97874. }
  97875. }
  97876. }
  97877. else {
  97878. v0.triangleStart = tStart;
  97879. }
  97880. v0.triangleCount = tCount;
  97881. break;
  97882. }
  97883. }
  97884. };
  97885. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  97886. }, 0);
  97887. };
  97888. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  97889. if (triangleCount - deletedTriangles <= targetCount)
  97890. loop.breakLoop();
  97891. else {
  97892. iterationFunction(loop.index, function () {
  97893. loop.executeNext();
  97894. });
  97895. }
  97896. }, function () {
  97897. setTimeout(function () {
  97898. //reconstruct this part of the mesh
  97899. _this.reconstructMesh(submeshIndex);
  97900. successCallback();
  97901. }, 0);
  97902. });
  97903. };
  97904. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  97905. var _this = this;
  97906. this.vertices = [];
  97907. this.triangles = [];
  97908. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97909. var indices = this._mesh.getIndices();
  97910. var submesh = this._mesh.subMeshes[submeshIndex];
  97911. var findInVertices = function (positionToSearch) {
  97912. if (optimizeMesh) {
  97913. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  97914. if (_this.vertices[ii].position.equals(positionToSearch)) {
  97915. return _this.vertices[ii];
  97916. }
  97917. }
  97918. }
  97919. return null;
  97920. };
  97921. var vertexReferences = [];
  97922. var vertexInit = function (i) {
  97923. if (!positionData) {
  97924. return;
  97925. }
  97926. var offset = i + submesh.verticesStart;
  97927. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  97928. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  97929. vertex.originalOffsets.push(offset);
  97930. if (vertex.id === _this.vertices.length) {
  97931. _this.vertices.push(vertex);
  97932. }
  97933. vertexReferences.push(vertex.id);
  97934. };
  97935. //var totalVertices = mesh.getTotalVertices();
  97936. var totalVertices = submesh.verticesCount;
  97937. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  97938. var indicesInit = function (i) {
  97939. if (!indices) {
  97940. return;
  97941. }
  97942. var offset = (submesh.indexStart / 3) + i;
  97943. var pos = (offset * 3);
  97944. var i0 = indices[pos + 0];
  97945. var i1 = indices[pos + 1];
  97946. var i2 = indices[pos + 2];
  97947. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  97948. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  97949. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  97950. var triangle = new DecimationTriangle([v0, v1, v2]);
  97951. triangle.originalOffset = pos;
  97952. _this.triangles.push(triangle);
  97953. };
  97954. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  97955. _this.init(callback);
  97956. });
  97957. });
  97958. };
  97959. QuadraticErrorSimplification.prototype.init = function (callback) {
  97960. var _this = this;
  97961. var triangleInit1 = function (i) {
  97962. var t = _this.triangles[i];
  97963. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  97964. for (var j = 0; j < 3; j++) {
  97965. 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))));
  97966. }
  97967. };
  97968. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  97969. var triangleInit2 = function (i) {
  97970. var t = _this.triangles[i];
  97971. for (var j = 0; j < 3; ++j) {
  97972. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  97973. }
  97974. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  97975. };
  97976. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  97977. callback();
  97978. });
  97979. });
  97980. };
  97981. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  97982. var newTriangles = [];
  97983. var i;
  97984. for (i = 0; i < this.vertices.length; ++i) {
  97985. this.vertices[i].triangleCount = 0;
  97986. }
  97987. var t;
  97988. var j;
  97989. for (i = 0; i < this.triangles.length; ++i) {
  97990. if (!this.triangles[i].deleted) {
  97991. t = this.triangles[i];
  97992. for (j = 0; j < 3; ++j) {
  97993. t.vertices[j].triangleCount = 1;
  97994. }
  97995. newTriangles.push(t);
  97996. }
  97997. }
  97998. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  97999. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  98000. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  98001. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  98002. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  98003. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  98004. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  98005. var vertexCount = 0;
  98006. for (i = 0; i < this.vertices.length; ++i) {
  98007. var vertex = this.vertices[i];
  98008. vertex.id = vertexCount;
  98009. if (vertex.triangleCount) {
  98010. vertex.originalOffsets.forEach(function (originalOffset) {
  98011. if (!normalData) {
  98012. return;
  98013. }
  98014. newPositionData.push(vertex.position.x);
  98015. newPositionData.push(vertex.position.y);
  98016. newPositionData.push(vertex.position.z);
  98017. newNormalData.push(normalData[originalOffset * 3]);
  98018. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  98019. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  98020. if (uvs && uvs.length) {
  98021. newUVsData.push(uvs[(originalOffset * 2)]);
  98022. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  98023. }
  98024. else if (colorsData && colorsData.length) {
  98025. newColorsData.push(colorsData[(originalOffset * 4)]);
  98026. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  98027. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  98028. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  98029. }
  98030. ++vertexCount;
  98031. });
  98032. }
  98033. }
  98034. var startingIndex = this._reconstructedMesh.getTotalIndices();
  98035. var startingVertex = this._reconstructedMesh.getTotalVertices();
  98036. var submeshesArray = this._reconstructedMesh.subMeshes;
  98037. this._reconstructedMesh.subMeshes = [];
  98038. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  98039. var originalIndices = this._mesh.getIndices();
  98040. for (i = 0; i < newTriangles.length; ++i) {
  98041. t = newTriangles[i]; //now get the new referencing point for each vertex
  98042. [0, 1, 2].forEach(function (idx) {
  98043. var id = originalIndices[t.originalOffset + idx];
  98044. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  98045. if (offset < 0)
  98046. offset = 0;
  98047. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  98048. });
  98049. }
  98050. //overwriting the old vertex buffers and indices.
  98051. this._reconstructedMesh.setIndices(newIndicesArray);
  98052. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  98053. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  98054. if (newUVsData.length > 0)
  98055. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  98056. if (newColorsData.length > 0)
  98057. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  98058. //create submesh
  98059. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  98060. if (submeshIndex > 0) {
  98061. this._reconstructedMesh.subMeshes = [];
  98062. submeshesArray.forEach(function (submesh) {
  98063. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  98064. });
  98065. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  98066. }
  98067. };
  98068. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  98069. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  98070. this._reconstructedMesh.material = this._mesh.material;
  98071. this._reconstructedMesh.parent = this._mesh.parent;
  98072. this._reconstructedMesh.isVisible = false;
  98073. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  98074. };
  98075. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  98076. for (var i = 0; i < vertex1.triangleCount; ++i) {
  98077. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  98078. if (t.deleted)
  98079. continue;
  98080. var s = this.references[vertex1.triangleStart + i].vertexId;
  98081. var v1 = t.vertices[(s + 1) % 3];
  98082. var v2 = t.vertices[(s + 2) % 3];
  98083. if ((v1 === vertex2 || v2 === vertex2)) {
  98084. deletedArray[i] = true;
  98085. delTr.push(t);
  98086. continue;
  98087. }
  98088. var d1 = v1.position.subtract(point);
  98089. d1 = d1.normalize();
  98090. var d2 = v2.position.subtract(point);
  98091. d2 = d2.normalize();
  98092. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  98093. return true;
  98094. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  98095. deletedArray[i] = false;
  98096. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  98097. return true;
  98098. }
  98099. return false;
  98100. };
  98101. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  98102. var newDeleted = deletedTriangles;
  98103. for (var i = 0; i < vertex.triangleCount; ++i) {
  98104. var ref = this.references[vertex.triangleStart + i];
  98105. var t = this.triangles[ref.triangleId];
  98106. if (t.deleted)
  98107. continue;
  98108. if (deletedArray[i] && t.deletePending) {
  98109. t.deleted = true;
  98110. newDeleted++;
  98111. continue;
  98112. }
  98113. t.vertices[ref.vertexId] = origVertex;
  98114. t.isDirty = true;
  98115. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  98116. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  98117. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  98118. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98119. this.references.push(ref);
  98120. }
  98121. return newDeleted;
  98122. };
  98123. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  98124. for (var i = 0; i < this.vertices.length; ++i) {
  98125. var vCount = [];
  98126. var vId = [];
  98127. var v = this.vertices[i];
  98128. var j;
  98129. for (j = 0; j < v.triangleCount; ++j) {
  98130. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  98131. for (var ii = 0; ii < 3; ii++) {
  98132. var ofs = 0;
  98133. var vv = triangle.vertices[ii];
  98134. while (ofs < vCount.length) {
  98135. if (vId[ofs] === vv.id)
  98136. break;
  98137. ++ofs;
  98138. }
  98139. if (ofs === vCount.length) {
  98140. vCount.push(1);
  98141. vId.push(vv.id);
  98142. }
  98143. else {
  98144. vCount[ofs]++;
  98145. }
  98146. }
  98147. }
  98148. for (j = 0; j < vCount.length; ++j) {
  98149. if (vCount[j] === 1) {
  98150. this.vertices[vId[j]].isBorder = true;
  98151. }
  98152. else {
  98153. this.vertices[vId[j]].isBorder = false;
  98154. }
  98155. }
  98156. }
  98157. };
  98158. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  98159. if (identifyBorders === void 0) { identifyBorders = false; }
  98160. var i;
  98161. if (!identifyBorders) {
  98162. var newTrianglesVector = [];
  98163. for (i = 0; i < this.triangles.length; ++i) {
  98164. if (!this.triangles[i].deleted) {
  98165. newTrianglesVector.push(this.triangles[i]);
  98166. }
  98167. }
  98168. this.triangles = newTrianglesVector;
  98169. }
  98170. for (i = 0; i < this.vertices.length; ++i) {
  98171. this.vertices[i].triangleCount = 0;
  98172. this.vertices[i].triangleStart = 0;
  98173. }
  98174. var t;
  98175. var j;
  98176. var v;
  98177. for (i = 0; i < this.triangles.length; ++i) {
  98178. t = this.triangles[i];
  98179. for (j = 0; j < 3; ++j) {
  98180. v = t.vertices[j];
  98181. v.triangleCount++;
  98182. }
  98183. }
  98184. var tStart = 0;
  98185. for (i = 0; i < this.vertices.length; ++i) {
  98186. this.vertices[i].triangleStart = tStart;
  98187. tStart += this.vertices[i].triangleCount;
  98188. this.vertices[i].triangleCount = 0;
  98189. }
  98190. var newReferences = new Array(this.triangles.length * 3);
  98191. for (i = 0; i < this.triangles.length; ++i) {
  98192. t = this.triangles[i];
  98193. for (j = 0; j < 3; ++j) {
  98194. v = t.vertices[j];
  98195. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  98196. v.triangleCount++;
  98197. }
  98198. }
  98199. this.references = newReferences;
  98200. if (identifyBorders) {
  98201. this.identifyBorder();
  98202. }
  98203. };
  98204. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  98205. var x = point.x;
  98206. var y = point.y;
  98207. var z = point.z;
  98208. 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
  98209. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  98210. };
  98211. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  98212. var q = vertex1.q.add(vertex2.q);
  98213. var border = vertex1.isBorder && vertex2.isBorder;
  98214. var error = 0;
  98215. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  98216. if (qDet !== 0 && !border) {
  98217. if (!pointResult) {
  98218. pointResult = BABYLON.Vector3.Zero();
  98219. }
  98220. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  98221. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  98222. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  98223. error = this.vertexError(q, pointResult);
  98224. }
  98225. else {
  98226. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  98227. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  98228. var error1 = this.vertexError(q, vertex1.position);
  98229. var error2 = this.vertexError(q, vertex2.position);
  98230. var error3 = this.vertexError(q, p3);
  98231. error = Math.min(error1, error2, error3);
  98232. if (error === error1) {
  98233. if (pointResult) {
  98234. pointResult.copyFrom(vertex1.position);
  98235. }
  98236. }
  98237. else if (error === error2) {
  98238. if (pointResult) {
  98239. pointResult.copyFrom(vertex2.position);
  98240. }
  98241. }
  98242. else {
  98243. if (pointResult) {
  98244. pointResult.copyFrom(p3);
  98245. }
  98246. }
  98247. }
  98248. return error;
  98249. };
  98250. return QuadraticErrorSimplification;
  98251. }());
  98252. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  98253. })(BABYLON || (BABYLON = {}));
  98254. //# sourceMappingURL=babylon.meshSimplification.js.map
  98255. var BABYLON;
  98256. (function (BABYLON) {
  98257. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  98258. get: function () {
  98259. if (!this._simplificationQueue) {
  98260. this._simplificationQueue = new BABYLON.SimplificationQueue();
  98261. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  98262. if (!component) {
  98263. component = new SimplicationQueueSceneComponent(this);
  98264. this._addComponent(component);
  98265. }
  98266. }
  98267. return this._simplificationQueue;
  98268. },
  98269. set: function (value) {
  98270. this._simplificationQueue = value;
  98271. },
  98272. enumerable: true,
  98273. configurable: true
  98274. });
  98275. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  98276. if (parallelProcessing === void 0) { parallelProcessing = true; }
  98277. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  98278. this.getScene().simplificationQueue.addTask({
  98279. settings: settings,
  98280. parallelProcessing: parallelProcessing,
  98281. mesh: this,
  98282. simplificationType: simplificationType,
  98283. successCallback: successCallback
  98284. });
  98285. return this;
  98286. };
  98287. /**
  98288. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  98289. * created in a scene
  98290. */
  98291. var SimplicationQueueSceneComponent = /** @class */ (function () {
  98292. /**
  98293. * Creates a new instance of the component for the given scene
  98294. * @param scene Defines the scene to register the component in
  98295. */
  98296. function SimplicationQueueSceneComponent(scene) {
  98297. /**
  98298. * The component name helpfull to identify the component in the list of scene components.
  98299. */
  98300. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  98301. this.scene = scene;
  98302. }
  98303. /**
  98304. * Registers the component in a given scene
  98305. */
  98306. SimplicationQueueSceneComponent.prototype.register = function () {
  98307. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  98308. };
  98309. /**
  98310. * Rebuilds the elements related to this component in case of
  98311. * context lost for instance.
  98312. */
  98313. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  98314. // Nothing to do for this component
  98315. };
  98316. /**
  98317. * Disposes the component and the associated ressources
  98318. */
  98319. SimplicationQueueSceneComponent.prototype.dispose = function () {
  98320. // Nothing to do for this component
  98321. };
  98322. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  98323. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  98324. this.scene._simplificationQueue.executeNext();
  98325. }
  98326. };
  98327. return SimplicationQueueSceneComponent;
  98328. }());
  98329. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  98330. })(BABYLON || (BABYLON = {}));
  98331. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  98332. var BABYLON;
  98333. (function (BABYLON) {
  98334. var MeshLODLevel = /** @class */ (function () {
  98335. function MeshLODLevel(distance, mesh) {
  98336. this.distance = distance;
  98337. this.mesh = mesh;
  98338. }
  98339. return MeshLODLevel;
  98340. }());
  98341. BABYLON.MeshLODLevel = MeshLODLevel;
  98342. })(BABYLON || (BABYLON = {}));
  98343. //# sourceMappingURL=babylon.meshLODLevel.js.map
  98344. var BABYLON;
  98345. (function (BABYLON) {
  98346. /**
  98347. * Defines the root class used to create scene optimization to use with SceneOptimizer
  98348. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98349. */
  98350. var SceneOptimization = /** @class */ (function () {
  98351. /**
  98352. * Creates the SceneOptimization object
  98353. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98354. * @param desc defines the description associated with the optimization
  98355. */
  98356. function SceneOptimization(
  98357. /**
  98358. * Defines the priority of this optimization (0 by default which means first in the list)
  98359. */
  98360. priority) {
  98361. if (priority === void 0) { priority = 0; }
  98362. this.priority = priority;
  98363. }
  98364. /**
  98365. * Gets a string describing the action executed by the current optimization
  98366. * @returns description string
  98367. */
  98368. SceneOptimization.prototype.getDescription = function () {
  98369. return "";
  98370. };
  98371. /**
  98372. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98373. * @param scene defines the current scene where to apply this optimization
  98374. * @param optimizer defines the current optimizer
  98375. * @returns true if everything that can be done was applied
  98376. */
  98377. SceneOptimization.prototype.apply = function (scene, optimizer) {
  98378. return true;
  98379. };
  98380. ;
  98381. return SceneOptimization;
  98382. }());
  98383. BABYLON.SceneOptimization = SceneOptimization;
  98384. /**
  98385. * Defines an optimization used to reduce the size of render target textures
  98386. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98387. */
  98388. var TextureOptimization = /** @class */ (function (_super) {
  98389. __extends(TextureOptimization, _super);
  98390. /**
  98391. * Creates the TextureOptimization object
  98392. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98393. * @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
  98394. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98395. */
  98396. function TextureOptimization(
  98397. /**
  98398. * Defines the priority of this optimization (0 by default which means first in the list)
  98399. */
  98400. priority,
  98401. /**
  98402. * 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
  98403. */
  98404. maximumSize,
  98405. /**
  98406. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98407. */
  98408. step) {
  98409. if (priority === void 0) { priority = 0; }
  98410. if (maximumSize === void 0) { maximumSize = 1024; }
  98411. if (step === void 0) { step = 0.5; }
  98412. var _this = _super.call(this, priority) || this;
  98413. _this.priority = priority;
  98414. _this.maximumSize = maximumSize;
  98415. _this.step = step;
  98416. return _this;
  98417. }
  98418. /**
  98419. * Gets a string describing the action executed by the current optimization
  98420. * @returns description string
  98421. */
  98422. TextureOptimization.prototype.getDescription = function () {
  98423. return "Reducing render target texture size to " + this.maximumSize;
  98424. };
  98425. /**
  98426. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98427. * @param scene defines the current scene where to apply this optimization
  98428. * @param optimizer defines the current optimizer
  98429. * @returns true if everything that can be done was applied
  98430. */
  98431. TextureOptimization.prototype.apply = function (scene, optimizer) {
  98432. var allDone = true;
  98433. for (var index = 0; index < scene.textures.length; index++) {
  98434. var texture = scene.textures[index];
  98435. if (!texture.canRescale || texture.getContext) {
  98436. continue;
  98437. }
  98438. var currentSize = texture.getSize();
  98439. var maxDimension = Math.max(currentSize.width, currentSize.height);
  98440. if (maxDimension > this.maximumSize) {
  98441. texture.scale(this.step);
  98442. allDone = false;
  98443. }
  98444. }
  98445. return allDone;
  98446. };
  98447. return TextureOptimization;
  98448. }(SceneOptimization));
  98449. BABYLON.TextureOptimization = TextureOptimization;
  98450. /**
  98451. * Defines an optimization used to increase or decrease the rendering resolution
  98452. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98453. */
  98454. var HardwareScalingOptimization = /** @class */ (function (_super) {
  98455. __extends(HardwareScalingOptimization, _super);
  98456. /**
  98457. * Creates the HardwareScalingOptimization object
  98458. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98459. * @param maximumScale defines the maximum scale to use (2 by default)
  98460. * @param step defines the step to use between two passes (0.5 by default)
  98461. */
  98462. function HardwareScalingOptimization(
  98463. /**
  98464. * Defines the priority of this optimization (0 by default which means first in the list)
  98465. */
  98466. priority,
  98467. /**
  98468. * Defines the maximum scale to use (2 by default)
  98469. */
  98470. maximumScale,
  98471. /**
  98472. * Defines the step to use between two passes (0.5 by default)
  98473. */
  98474. step) {
  98475. if (priority === void 0) { priority = 0; }
  98476. if (maximumScale === void 0) { maximumScale = 2; }
  98477. if (step === void 0) { step = 0.25; }
  98478. var _this = _super.call(this, priority) || this;
  98479. _this.priority = priority;
  98480. _this.maximumScale = maximumScale;
  98481. _this.step = step;
  98482. _this._currentScale = -1;
  98483. _this._directionOffset = 1;
  98484. return _this;
  98485. }
  98486. /**
  98487. * Gets a string describing the action executed by the current optimization
  98488. * @return description string
  98489. */
  98490. HardwareScalingOptimization.prototype.getDescription = function () {
  98491. return "Setting hardware scaling level to " + this._currentScale;
  98492. };
  98493. /**
  98494. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98495. * @param scene defines the current scene where to apply this optimization
  98496. * @param optimizer defines the current optimizer
  98497. * @returns true if everything that can be done was applied
  98498. */
  98499. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  98500. if (this._currentScale === -1) {
  98501. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  98502. if (this._currentScale > this.maximumScale) {
  98503. this._directionOffset = -1;
  98504. }
  98505. }
  98506. this._currentScale += this._directionOffset * this.step;
  98507. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  98508. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  98509. };
  98510. ;
  98511. return HardwareScalingOptimization;
  98512. }(SceneOptimization));
  98513. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  98514. /**
  98515. * Defines an optimization used to remove shadows
  98516. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98517. */
  98518. var ShadowsOptimization = /** @class */ (function (_super) {
  98519. __extends(ShadowsOptimization, _super);
  98520. function ShadowsOptimization() {
  98521. return _super !== null && _super.apply(this, arguments) || this;
  98522. }
  98523. /**
  98524. * Gets a string describing the action executed by the current optimization
  98525. * @return description string
  98526. */
  98527. ShadowsOptimization.prototype.getDescription = function () {
  98528. return "Turning shadows on/off";
  98529. };
  98530. /**
  98531. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98532. * @param scene defines the current scene where to apply this optimization
  98533. * @param optimizer defines the current optimizer
  98534. * @returns true if everything that can be done was applied
  98535. */
  98536. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  98537. scene.shadowsEnabled = optimizer.isInImprovementMode;
  98538. return true;
  98539. };
  98540. ;
  98541. return ShadowsOptimization;
  98542. }(SceneOptimization));
  98543. BABYLON.ShadowsOptimization = ShadowsOptimization;
  98544. /**
  98545. * Defines an optimization used to turn post-processes off
  98546. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98547. */
  98548. var PostProcessesOptimization = /** @class */ (function (_super) {
  98549. __extends(PostProcessesOptimization, _super);
  98550. function PostProcessesOptimization() {
  98551. return _super !== null && _super.apply(this, arguments) || this;
  98552. }
  98553. /**
  98554. * Gets a string describing the action executed by the current optimization
  98555. * @return description string
  98556. */
  98557. PostProcessesOptimization.prototype.getDescription = function () {
  98558. return "Turning post-processes on/off";
  98559. };
  98560. /**
  98561. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98562. * @param scene defines the current scene where to apply this optimization
  98563. * @param optimizer defines the current optimizer
  98564. * @returns true if everything that can be done was applied
  98565. */
  98566. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  98567. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  98568. return true;
  98569. };
  98570. ;
  98571. return PostProcessesOptimization;
  98572. }(SceneOptimization));
  98573. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  98574. /**
  98575. * Defines an optimization used to turn lens flares off
  98576. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98577. */
  98578. var LensFlaresOptimization = /** @class */ (function (_super) {
  98579. __extends(LensFlaresOptimization, _super);
  98580. function LensFlaresOptimization() {
  98581. return _super !== null && _super.apply(this, arguments) || this;
  98582. }
  98583. /**
  98584. * Gets a string describing the action executed by the current optimization
  98585. * @return description string
  98586. */
  98587. LensFlaresOptimization.prototype.getDescription = function () {
  98588. return "Turning lens flares on/off";
  98589. };
  98590. /**
  98591. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98592. * @param scene defines the current scene where to apply this optimization
  98593. * @param optimizer defines the current optimizer
  98594. * @returns true if everything that can be done was applied
  98595. */
  98596. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  98597. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  98598. return true;
  98599. };
  98600. ;
  98601. return LensFlaresOptimization;
  98602. }(SceneOptimization));
  98603. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  98604. /**
  98605. * Defines an optimization based on user defined callback.
  98606. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98607. */
  98608. var CustomOptimization = /** @class */ (function (_super) {
  98609. __extends(CustomOptimization, _super);
  98610. function CustomOptimization() {
  98611. return _super !== null && _super.apply(this, arguments) || this;
  98612. }
  98613. /**
  98614. * Gets a string describing the action executed by the current optimization
  98615. * @returns description string
  98616. */
  98617. CustomOptimization.prototype.getDescription = function () {
  98618. if (this.onGetDescription) {
  98619. return this.onGetDescription();
  98620. }
  98621. return "Running user defined callback";
  98622. };
  98623. /**
  98624. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98625. * @param scene defines the current scene where to apply this optimization
  98626. * @param optimizer defines the current optimizer
  98627. * @returns true if everything that can be done was applied
  98628. */
  98629. CustomOptimization.prototype.apply = function (scene, optimizer) {
  98630. if (this.onApply) {
  98631. return this.onApply(scene, optimizer);
  98632. }
  98633. return true;
  98634. };
  98635. ;
  98636. return CustomOptimization;
  98637. }(SceneOptimization));
  98638. BABYLON.CustomOptimization = CustomOptimization;
  98639. /**
  98640. * Defines an optimization used to turn particles off
  98641. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98642. */
  98643. var ParticlesOptimization = /** @class */ (function (_super) {
  98644. __extends(ParticlesOptimization, _super);
  98645. function ParticlesOptimization() {
  98646. return _super !== null && _super.apply(this, arguments) || this;
  98647. }
  98648. /**
  98649. * Gets a string describing the action executed by the current optimization
  98650. * @return description string
  98651. */
  98652. ParticlesOptimization.prototype.getDescription = function () {
  98653. return "Turning particles on/off";
  98654. };
  98655. /**
  98656. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98657. * @param scene defines the current scene where to apply this optimization
  98658. * @param optimizer defines the current optimizer
  98659. * @returns true if everything that can be done was applied
  98660. */
  98661. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  98662. scene.particlesEnabled = optimizer.isInImprovementMode;
  98663. return true;
  98664. };
  98665. ;
  98666. return ParticlesOptimization;
  98667. }(SceneOptimization));
  98668. BABYLON.ParticlesOptimization = ParticlesOptimization;
  98669. /**
  98670. * Defines an optimization used to turn render targets off
  98671. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98672. */
  98673. var RenderTargetsOptimization = /** @class */ (function (_super) {
  98674. __extends(RenderTargetsOptimization, _super);
  98675. function RenderTargetsOptimization() {
  98676. return _super !== null && _super.apply(this, arguments) || this;
  98677. }
  98678. /**
  98679. * Gets a string describing the action executed by the current optimization
  98680. * @return description string
  98681. */
  98682. RenderTargetsOptimization.prototype.getDescription = function () {
  98683. return "Turning render targets off";
  98684. };
  98685. /**
  98686. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98687. * @param scene defines the current scene where to apply this optimization
  98688. * @param optimizer defines the current optimizer
  98689. * @returns true if everything that can be done was applied
  98690. */
  98691. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  98692. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  98693. return true;
  98694. };
  98695. ;
  98696. return RenderTargetsOptimization;
  98697. }(SceneOptimization));
  98698. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  98699. /**
  98700. * Defines an optimization used to merge meshes with compatible materials
  98701. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98702. */
  98703. var MergeMeshesOptimization = /** @class */ (function (_super) {
  98704. __extends(MergeMeshesOptimization, _super);
  98705. function MergeMeshesOptimization() {
  98706. var _this = _super !== null && _super.apply(this, arguments) || this;
  98707. _this._canBeMerged = function (abstractMesh) {
  98708. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  98709. return false;
  98710. }
  98711. var mesh = abstractMesh;
  98712. if (mesh.isDisposed()) {
  98713. return false;
  98714. }
  98715. if (!mesh.isVisible || !mesh.isEnabled()) {
  98716. return false;
  98717. }
  98718. if (mesh.instances.length > 0) {
  98719. return false;
  98720. }
  98721. if (mesh.skeleton || mesh.hasLODLevels) {
  98722. return false;
  98723. }
  98724. return true;
  98725. };
  98726. return _this;
  98727. }
  98728. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  98729. /**
  98730. * Gets or sets a boolean which defines if optimization octree has to be updated
  98731. */
  98732. get: function () {
  98733. return MergeMeshesOptimization._UpdateSelectionTree;
  98734. },
  98735. /**
  98736. * Gets or sets a boolean which defines if optimization octree has to be updated
  98737. */
  98738. set: function (value) {
  98739. MergeMeshesOptimization._UpdateSelectionTree = value;
  98740. },
  98741. enumerable: true,
  98742. configurable: true
  98743. });
  98744. /**
  98745. * Gets a string describing the action executed by the current optimization
  98746. * @return description string
  98747. */
  98748. MergeMeshesOptimization.prototype.getDescription = function () {
  98749. return "Merging similar meshes together";
  98750. };
  98751. /**
  98752. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98753. * @param scene defines the current scene where to apply this optimization
  98754. * @param optimizer defines the current optimizer
  98755. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  98756. * @returns true if everything that can be done was applied
  98757. */
  98758. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  98759. var globalPool = scene.meshes.slice(0);
  98760. var globalLength = globalPool.length;
  98761. for (var index = 0; index < globalLength; index++) {
  98762. var currentPool = new Array();
  98763. var current = globalPool[index];
  98764. // Checks
  98765. if (!this._canBeMerged(current)) {
  98766. continue;
  98767. }
  98768. currentPool.push(current);
  98769. // Find compatible meshes
  98770. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  98771. var otherMesh = globalPool[subIndex];
  98772. if (!this._canBeMerged(otherMesh)) {
  98773. continue;
  98774. }
  98775. if (otherMesh.material !== current.material) {
  98776. continue;
  98777. }
  98778. if (otherMesh.checkCollisions !== current.checkCollisions) {
  98779. continue;
  98780. }
  98781. currentPool.push(otherMesh);
  98782. globalLength--;
  98783. globalPool.splice(subIndex, 1);
  98784. subIndex--;
  98785. }
  98786. if (currentPool.length < 2) {
  98787. continue;
  98788. }
  98789. // Merge meshes
  98790. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  98791. }
  98792. if (updateSelectionTree != undefined) {
  98793. if (updateSelectionTree) {
  98794. scene.createOrUpdateSelectionOctree();
  98795. }
  98796. }
  98797. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  98798. scene.createOrUpdateSelectionOctree();
  98799. }
  98800. return true;
  98801. };
  98802. ;
  98803. MergeMeshesOptimization._UpdateSelectionTree = false;
  98804. return MergeMeshesOptimization;
  98805. }(SceneOptimization));
  98806. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  98807. /**
  98808. * Defines a list of options used by SceneOptimizer
  98809. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98810. */
  98811. var SceneOptimizerOptions = /** @class */ (function () {
  98812. /**
  98813. * Creates a new list of options used by SceneOptimizer
  98814. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  98815. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  98816. */
  98817. function SceneOptimizerOptions(
  98818. /**
  98819. * Defines the target frame rate to reach (60 by default)
  98820. */
  98821. targetFrameRate,
  98822. /**
  98823. * Defines the interval between two checkes (2000ms by default)
  98824. */
  98825. trackerDuration) {
  98826. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  98827. if (trackerDuration === void 0) { trackerDuration = 2000; }
  98828. this.targetFrameRate = targetFrameRate;
  98829. this.trackerDuration = trackerDuration;
  98830. /**
  98831. * Gets the list of optimizations to apply
  98832. */
  98833. this.optimizations = new Array();
  98834. }
  98835. /**
  98836. * Add a new optimization
  98837. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  98838. * @returns the current SceneOptimizerOptions
  98839. */
  98840. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  98841. this.optimizations.push(optimization);
  98842. return this;
  98843. };
  98844. /**
  98845. * Add a new custom optimization
  98846. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  98847. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  98848. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98849. * @returns the current SceneOptimizerOptions
  98850. */
  98851. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  98852. if (priority === void 0) { priority = 0; }
  98853. var optimization = new CustomOptimization(priority);
  98854. optimization.onApply = onApply;
  98855. optimization.onGetDescription = onGetDescription;
  98856. this.optimizations.push(optimization);
  98857. return this;
  98858. };
  98859. /**
  98860. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  98861. * @param targetFrameRate defines the target frame rate (60 by default)
  98862. * @returns a SceneOptimizerOptions object
  98863. */
  98864. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  98865. var result = new SceneOptimizerOptions(targetFrameRate);
  98866. var priority = 0;
  98867. result.addOptimization(new MergeMeshesOptimization(priority));
  98868. result.addOptimization(new ShadowsOptimization(priority));
  98869. result.addOptimization(new LensFlaresOptimization(priority));
  98870. // Next priority
  98871. priority++;
  98872. result.addOptimization(new PostProcessesOptimization(priority));
  98873. result.addOptimization(new ParticlesOptimization(priority));
  98874. // Next priority
  98875. priority++;
  98876. result.addOptimization(new TextureOptimization(priority, 1024));
  98877. return result;
  98878. };
  98879. /**
  98880. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  98881. * @param targetFrameRate defines the target frame rate (60 by default)
  98882. * @returns a SceneOptimizerOptions object
  98883. */
  98884. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  98885. var result = new SceneOptimizerOptions(targetFrameRate);
  98886. var priority = 0;
  98887. result.addOptimization(new MergeMeshesOptimization(priority));
  98888. result.addOptimization(new ShadowsOptimization(priority));
  98889. result.addOptimization(new LensFlaresOptimization(priority));
  98890. // Next priority
  98891. priority++;
  98892. result.addOptimization(new PostProcessesOptimization(priority));
  98893. result.addOptimization(new ParticlesOptimization(priority));
  98894. // Next priority
  98895. priority++;
  98896. result.addOptimization(new TextureOptimization(priority, 512));
  98897. // Next priority
  98898. priority++;
  98899. result.addOptimization(new RenderTargetsOptimization(priority));
  98900. // Next priority
  98901. priority++;
  98902. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  98903. return result;
  98904. };
  98905. /**
  98906. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  98907. * @param targetFrameRate defines the target frame rate (60 by default)
  98908. * @returns a SceneOptimizerOptions object
  98909. */
  98910. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  98911. var result = new SceneOptimizerOptions(targetFrameRate);
  98912. var priority = 0;
  98913. result.addOptimization(new MergeMeshesOptimization(priority));
  98914. result.addOptimization(new ShadowsOptimization(priority));
  98915. result.addOptimization(new LensFlaresOptimization(priority));
  98916. // Next priority
  98917. priority++;
  98918. result.addOptimization(new PostProcessesOptimization(priority));
  98919. result.addOptimization(new ParticlesOptimization(priority));
  98920. // Next priority
  98921. priority++;
  98922. result.addOptimization(new TextureOptimization(priority, 256));
  98923. // Next priority
  98924. priority++;
  98925. result.addOptimization(new RenderTargetsOptimization(priority));
  98926. // Next priority
  98927. priority++;
  98928. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  98929. return result;
  98930. };
  98931. return SceneOptimizerOptions;
  98932. }());
  98933. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  98934. /**
  98935. * Class used to run optimizations in order to reach a target frame rate
  98936. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98937. */
  98938. var SceneOptimizer = /** @class */ (function () {
  98939. /**
  98940. * Creates a new SceneOptimizer
  98941. * @param scene defines the scene to work on
  98942. * @param options defines the options to use with the SceneOptimizer
  98943. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  98944. * @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)
  98945. */
  98946. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  98947. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  98948. if (improvementMode === void 0) { improvementMode = false; }
  98949. var _this = this;
  98950. this._isRunning = false;
  98951. this._currentPriorityLevel = 0;
  98952. this._targetFrameRate = 60;
  98953. this._trackerDuration = 2000;
  98954. this._currentFrameRate = 0;
  98955. this._improvementMode = false;
  98956. /**
  98957. * Defines an observable called when the optimizer reaches the target frame rate
  98958. */
  98959. this.onSuccessObservable = new BABYLON.Observable();
  98960. /**
  98961. * Defines an observable called when the optimizer enables an optimization
  98962. */
  98963. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  98964. /**
  98965. * Defines an observable called when the optimizer is not able to reach the target frame rate
  98966. */
  98967. this.onFailureObservable = new BABYLON.Observable();
  98968. if (!options) {
  98969. this._options = new SceneOptimizerOptions();
  98970. }
  98971. else {
  98972. this._options = options;
  98973. }
  98974. if (this._options.targetFrameRate) {
  98975. this._targetFrameRate = this._options.targetFrameRate;
  98976. }
  98977. if (this._options.trackerDuration) {
  98978. this._trackerDuration = this._options.trackerDuration;
  98979. }
  98980. if (autoGeneratePriorities) {
  98981. var priority = 0;
  98982. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  98983. var optim = _a[_i];
  98984. optim.priority = priority++;
  98985. }
  98986. }
  98987. this._improvementMode = improvementMode;
  98988. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98989. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  98990. _this._sceneDisposeObserver = null;
  98991. _this.dispose();
  98992. });
  98993. }
  98994. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  98995. /**
  98996. * Gets a boolean indicating if the optimizer is in improvement mode
  98997. */
  98998. get: function () {
  98999. return this._improvementMode;
  99000. },
  99001. enumerable: true,
  99002. configurable: true
  99003. });
  99004. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  99005. /**
  99006. * Gets the current priority level (0 at start)
  99007. */
  99008. get: function () {
  99009. return this._currentPriorityLevel;
  99010. },
  99011. enumerable: true,
  99012. configurable: true
  99013. });
  99014. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  99015. /**
  99016. * Gets the current frame rate checked by the SceneOptimizer
  99017. */
  99018. get: function () {
  99019. return this._currentFrameRate;
  99020. },
  99021. enumerable: true,
  99022. configurable: true
  99023. });
  99024. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  99025. /**
  99026. * Gets or sets the current target frame rate (60 by default)
  99027. */
  99028. get: function () {
  99029. return this._targetFrameRate;
  99030. },
  99031. /**
  99032. * Gets or sets the current target frame rate (60 by default)
  99033. */
  99034. set: function (value) {
  99035. this._targetFrameRate = value;
  99036. },
  99037. enumerable: true,
  99038. configurable: true
  99039. });
  99040. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  99041. /**
  99042. * Gets or sets the current interval between two checks (every 2000ms by default)
  99043. */
  99044. get: function () {
  99045. return this._trackerDuration;
  99046. },
  99047. /**
  99048. * Gets or sets the current interval between two checks (every 2000ms by default)
  99049. */
  99050. set: function (value) {
  99051. this._trackerDuration = value;
  99052. },
  99053. enumerable: true,
  99054. configurable: true
  99055. });
  99056. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  99057. /**
  99058. * Gets the list of active optimizations
  99059. */
  99060. get: function () {
  99061. return this._options.optimizations;
  99062. },
  99063. enumerable: true,
  99064. configurable: true
  99065. });
  99066. /**
  99067. * Stops the current optimizer
  99068. */
  99069. SceneOptimizer.prototype.stop = function () {
  99070. this._isRunning = false;
  99071. };
  99072. /**
  99073. * Reset the optimizer to initial step (current priority level = 0)
  99074. */
  99075. SceneOptimizer.prototype.reset = function () {
  99076. this._currentPriorityLevel = 0;
  99077. };
  99078. /**
  99079. * Start the optimizer. By default it will try to reach a specific framerate
  99080. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  99081. */
  99082. SceneOptimizer.prototype.start = function () {
  99083. var _this = this;
  99084. if (this._isRunning) {
  99085. return;
  99086. }
  99087. this._isRunning = true;
  99088. // Let's wait for the scene to be ready before running our check
  99089. this._scene.executeWhenReady(function () {
  99090. setTimeout(function () {
  99091. _this._checkCurrentState();
  99092. }, _this._trackerDuration);
  99093. });
  99094. };
  99095. SceneOptimizer.prototype._checkCurrentState = function () {
  99096. var _this = this;
  99097. if (!this._isRunning) {
  99098. return;
  99099. }
  99100. var scene = this._scene;
  99101. var options = this._options;
  99102. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  99103. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  99104. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  99105. this._isRunning = false;
  99106. this.onSuccessObservable.notifyObservers(this);
  99107. return;
  99108. }
  99109. // Apply current level of optimizations
  99110. var allDone = true;
  99111. var noOptimizationApplied = true;
  99112. for (var index = 0; index < options.optimizations.length; index++) {
  99113. var optimization = options.optimizations[index];
  99114. if (optimization.priority === this._currentPriorityLevel) {
  99115. noOptimizationApplied = false;
  99116. allDone = allDone && optimization.apply(scene, this);
  99117. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  99118. }
  99119. }
  99120. // If no optimization was applied, this is a failure :(
  99121. if (noOptimizationApplied) {
  99122. this._isRunning = false;
  99123. this.onFailureObservable.notifyObservers(this);
  99124. return;
  99125. }
  99126. // If all optimizations were done, move to next level
  99127. if (allDone) {
  99128. this._currentPriorityLevel++;
  99129. }
  99130. // Let's the system running for a specific amount of time before checking FPS
  99131. scene.executeWhenReady(function () {
  99132. setTimeout(function () {
  99133. _this._checkCurrentState();
  99134. }, _this._trackerDuration);
  99135. });
  99136. };
  99137. /**
  99138. * Release all resources
  99139. */
  99140. SceneOptimizer.prototype.dispose = function () {
  99141. this.stop();
  99142. this.onSuccessObservable.clear();
  99143. this.onFailureObservable.clear();
  99144. this.onNewOptimizationAppliedObservable.clear();
  99145. if (this._sceneDisposeObserver) {
  99146. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99147. }
  99148. };
  99149. /**
  99150. * Helper function to create a SceneOptimizer with one single line of code
  99151. * @param scene defines the scene to work on
  99152. * @param options defines the options to use with the SceneOptimizer
  99153. * @param onSuccess defines a callback to call on success
  99154. * @param onFailure defines a callback to call on failure
  99155. * @returns the new SceneOptimizer object
  99156. */
  99157. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  99158. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  99159. if (onSuccess) {
  99160. optimizer.onSuccessObservable.add(function () {
  99161. onSuccess();
  99162. });
  99163. }
  99164. if (onFailure) {
  99165. optimizer.onFailureObservable.add(function () {
  99166. onFailure();
  99167. });
  99168. }
  99169. optimizer.start();
  99170. return optimizer;
  99171. };
  99172. return SceneOptimizer;
  99173. }());
  99174. BABYLON.SceneOptimizer = SceneOptimizer;
  99175. })(BABYLON || (BABYLON = {}));
  99176. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  99177. var BABYLON;
  99178. (function (BABYLON) {
  99179. var OutlineRenderer = /** @class */ (function () {
  99180. function OutlineRenderer(scene) {
  99181. this.zOffset = 1;
  99182. this._scene = scene;
  99183. }
  99184. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  99185. var _this = this;
  99186. if (useOverlay === void 0) { useOverlay = false; }
  99187. var scene = this._scene;
  99188. var engine = this._scene.getEngine();
  99189. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99190. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  99191. return;
  99192. }
  99193. var mesh = subMesh.getRenderingMesh();
  99194. var material = subMesh.getMaterial();
  99195. if (!material || !scene.activeCamera) {
  99196. return;
  99197. }
  99198. engine.enableEffect(this._effect);
  99199. // Logarithmic depth
  99200. if (material.useLogarithmicDepth) {
  99201. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  99202. }
  99203. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  99204. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  99205. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  99206. // Bones
  99207. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99208. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99209. }
  99210. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  99211. // Alpha test
  99212. if (material && material.needAlphaTesting()) {
  99213. var alphaTexture = material.getAlphaTestTexture();
  99214. if (alphaTexture) {
  99215. this._effect.setTexture("diffuseSampler", alphaTexture);
  99216. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  99217. }
  99218. }
  99219. engine.setZOffset(-this.zOffset);
  99220. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  99221. engine.setZOffset(0);
  99222. };
  99223. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  99224. var defines = [];
  99225. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  99226. var mesh = subMesh.getMesh();
  99227. var material = subMesh.getMaterial();
  99228. if (material) {
  99229. // Alpha test
  99230. if (material.needAlphaTesting()) {
  99231. defines.push("#define ALPHATEST");
  99232. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99233. attribs.push(BABYLON.VertexBuffer.UVKind);
  99234. defines.push("#define UV1");
  99235. }
  99236. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  99237. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99238. defines.push("#define UV2");
  99239. }
  99240. }
  99241. //Logarithmic depth
  99242. if (material.useLogarithmicDepth) {
  99243. defines.push("#define LOGARITHMICDEPTH");
  99244. }
  99245. }
  99246. // Bones
  99247. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99250. if (mesh.numBoneInfluencers > 4) {
  99251. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99252. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99253. }
  99254. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99255. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  99256. }
  99257. else {
  99258. defines.push("#define NUM_BONE_INFLUENCERS 0");
  99259. }
  99260. // Instances
  99261. if (useInstances) {
  99262. defines.push("#define INSTANCES");
  99263. attribs.push("world0");
  99264. attribs.push("world1");
  99265. attribs.push("world2");
  99266. attribs.push("world3");
  99267. }
  99268. // Get correct effect
  99269. var join = defines.join("\n");
  99270. if (this._cachedDefines !== join) {
  99271. this._cachedDefines = join;
  99272. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  99273. }
  99274. return this._effect.isReady();
  99275. };
  99276. return OutlineRenderer;
  99277. }());
  99278. BABYLON.OutlineRenderer = OutlineRenderer;
  99279. })(BABYLON || (BABYLON = {}));
  99280. //# sourceMappingURL=babylon.outlineRenderer.js.map
  99281. var BABYLON;
  99282. (function (BABYLON) {
  99283. /**
  99284. * FaceAdjacencies Helper class to generate edges
  99285. */
  99286. var FaceAdjacencies = /** @class */ (function () {
  99287. function FaceAdjacencies() {
  99288. this.edges = new Array();
  99289. this.edgesConnectedCount = 0;
  99290. }
  99291. return FaceAdjacencies;
  99292. }());
  99293. /**
  99294. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  99295. */
  99296. var EdgesRenderer = /** @class */ (function () {
  99297. /**
  99298. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  99299. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  99300. * @param source Mesh used to create edges
  99301. * @param epsilon sum of angles in adjacency to check for edge
  99302. * @param checkVerticesInsteadOfIndices
  99303. * @param generateEdgesLines - should generate Lines or only prepare resources.
  99304. */
  99305. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  99306. if (epsilon === void 0) { epsilon = 0.95; }
  99307. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99308. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  99309. this.edgesWidthScalerForOrthographic = 1000.0;
  99310. this.edgesWidthScalerForPerspective = 50.0;
  99311. this._linesPositions = new Array();
  99312. this._linesNormals = new Array();
  99313. this._linesIndices = new Array();
  99314. this._buffers = {};
  99315. this._checkVerticesInsteadOfIndices = false;
  99316. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  99317. this.isEnabled = true;
  99318. this._source = source;
  99319. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  99320. this._epsilon = epsilon;
  99321. this._prepareRessources();
  99322. if (generateEdgesLines) {
  99323. this._generateEdgesLines();
  99324. }
  99325. }
  99326. EdgesRenderer.prototype._prepareRessources = function () {
  99327. if (this._lineShader) {
  99328. return;
  99329. }
  99330. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  99331. attributes: ["position", "normal"],
  99332. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  99333. });
  99334. this._lineShader.disableDepthWrite = true;
  99335. this._lineShader.backFaceCulling = false;
  99336. };
  99337. /** @hidden */
  99338. EdgesRenderer.prototype._rebuild = function () {
  99339. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99340. if (buffer) {
  99341. buffer._rebuild();
  99342. }
  99343. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99344. if (buffer) {
  99345. buffer._rebuild();
  99346. }
  99347. var scene = this._source.getScene();
  99348. var engine = scene.getEngine();
  99349. this._ib = engine.createIndexBuffer(this._linesIndices);
  99350. };
  99351. /**
  99352. * Releases the required resources for the edges renderer
  99353. */
  99354. EdgesRenderer.prototype.dispose = function () {
  99355. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99356. if (buffer) {
  99357. buffer.dispose();
  99358. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  99359. }
  99360. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99361. if (buffer) {
  99362. buffer.dispose();
  99363. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  99364. }
  99365. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  99366. this._lineShader.dispose();
  99367. };
  99368. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  99369. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  99370. return 0;
  99371. }
  99372. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  99373. return 1;
  99374. }
  99375. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  99376. return 2;
  99377. }
  99378. return -1;
  99379. };
  99380. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  99381. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  99382. return 0;
  99383. }
  99384. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  99385. return 1;
  99386. }
  99387. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  99388. return 2;
  99389. }
  99390. return -1;
  99391. };
  99392. /**
  99393. * Checks if the pair of p0 and p1 is en edge
  99394. * @param faceIndex
  99395. * @param edge
  99396. * @param faceNormals
  99397. * @param p0
  99398. * @param p1
  99399. * @private
  99400. */
  99401. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99402. var needToCreateLine;
  99403. if (edge === undefined) {
  99404. needToCreateLine = true;
  99405. }
  99406. else {
  99407. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  99408. needToCreateLine = dotProduct < this._epsilon;
  99409. }
  99410. if (needToCreateLine) {
  99411. var offset = this._linesPositions.length / 3;
  99412. var normal = p0.subtract(p1);
  99413. normal.normalize();
  99414. // Positions
  99415. this._linesPositions.push(p0.x);
  99416. this._linesPositions.push(p0.y);
  99417. this._linesPositions.push(p0.z);
  99418. this._linesPositions.push(p0.x);
  99419. this._linesPositions.push(p0.y);
  99420. this._linesPositions.push(p0.z);
  99421. this._linesPositions.push(p1.x);
  99422. this._linesPositions.push(p1.y);
  99423. this._linesPositions.push(p1.z);
  99424. this._linesPositions.push(p1.x);
  99425. this._linesPositions.push(p1.y);
  99426. this._linesPositions.push(p1.z);
  99427. // Normals
  99428. this._linesNormals.push(p1.x);
  99429. this._linesNormals.push(p1.y);
  99430. this._linesNormals.push(p1.z);
  99431. this._linesNormals.push(-1);
  99432. this._linesNormals.push(p1.x);
  99433. this._linesNormals.push(p1.y);
  99434. this._linesNormals.push(p1.z);
  99435. this._linesNormals.push(1);
  99436. this._linesNormals.push(p0.x);
  99437. this._linesNormals.push(p0.y);
  99438. this._linesNormals.push(p0.z);
  99439. this._linesNormals.push(-1);
  99440. this._linesNormals.push(p0.x);
  99441. this._linesNormals.push(p0.y);
  99442. this._linesNormals.push(p0.z);
  99443. this._linesNormals.push(1);
  99444. // Indices
  99445. this._linesIndices.push(offset);
  99446. this._linesIndices.push(offset + 1);
  99447. this._linesIndices.push(offset + 2);
  99448. this._linesIndices.push(offset);
  99449. this._linesIndices.push(offset + 2);
  99450. this._linesIndices.push(offset + 3);
  99451. }
  99452. };
  99453. /**
  99454. * Generates lines edges from adjacencjes
  99455. * @private
  99456. */
  99457. EdgesRenderer.prototype._generateEdgesLines = function () {
  99458. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99459. var indices = this._source.getIndices();
  99460. if (!indices || !positions) {
  99461. return;
  99462. }
  99463. // First let's find adjacencies
  99464. var adjacencies = new Array();
  99465. var faceNormals = new Array();
  99466. var index;
  99467. var faceAdjacencies;
  99468. // Prepare faces
  99469. for (index = 0; index < indices.length; index += 3) {
  99470. faceAdjacencies = new FaceAdjacencies();
  99471. var p0Index = indices[index];
  99472. var p1Index = indices[index + 1];
  99473. var p2Index = indices[index + 2];
  99474. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  99475. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  99476. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  99477. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  99478. faceNormal.normalize();
  99479. faceNormals.push(faceNormal);
  99480. adjacencies.push(faceAdjacencies);
  99481. }
  99482. // Scan
  99483. for (index = 0; index < adjacencies.length; index++) {
  99484. faceAdjacencies = adjacencies[index];
  99485. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  99486. var otherFaceAdjacencies = adjacencies[otherIndex];
  99487. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  99488. break;
  99489. }
  99490. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  99491. continue;
  99492. }
  99493. var otherP0 = indices[otherIndex * 3];
  99494. var otherP1 = indices[otherIndex * 3 + 1];
  99495. var otherP2 = indices[otherIndex * 3 + 2];
  99496. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  99497. var otherEdgeIndex = 0;
  99498. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  99499. continue;
  99500. }
  99501. switch (edgeIndex) {
  99502. case 0:
  99503. if (this._checkVerticesInsteadOfIndices) {
  99504. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99505. }
  99506. else {
  99507. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  99508. }
  99509. break;
  99510. case 1:
  99511. if (this._checkVerticesInsteadOfIndices) {
  99512. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99513. }
  99514. else {
  99515. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  99516. }
  99517. break;
  99518. case 2:
  99519. if (this._checkVerticesInsteadOfIndices) {
  99520. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99521. }
  99522. else {
  99523. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  99524. }
  99525. break;
  99526. }
  99527. if (otherEdgeIndex === -1) {
  99528. continue;
  99529. }
  99530. faceAdjacencies.edges[edgeIndex] = otherIndex;
  99531. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  99532. faceAdjacencies.edgesConnectedCount++;
  99533. otherFaceAdjacencies.edgesConnectedCount++;
  99534. if (faceAdjacencies.edgesConnectedCount === 3) {
  99535. break;
  99536. }
  99537. }
  99538. }
  99539. }
  99540. // Create lines
  99541. for (index = 0; index < adjacencies.length; index++) {
  99542. // 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
  99543. var current = adjacencies[index];
  99544. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99545. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  99546. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  99547. }
  99548. // Merge into a single mesh
  99549. var engine = this._source.getScene().getEngine();
  99550. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99551. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99552. this._ib = engine.createIndexBuffer(this._linesIndices);
  99553. this._indicesCount = this._linesIndices.length;
  99554. };
  99555. EdgesRenderer.prototype.render = function () {
  99556. var scene = this._source.getScene();
  99557. if (!this._lineShader.isReady() || !scene.activeCamera) {
  99558. return;
  99559. }
  99560. var engine = scene.getEngine();
  99561. this._lineShader._preBind();
  99562. if (this._source.edgesColor.a !== 1) {
  99563. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  99564. }
  99565. else {
  99566. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99567. }
  99568. // VBOs
  99569. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  99570. scene.resetCachedMaterial();
  99571. this._lineShader.setColor4("color", this._source.edgesColor);
  99572. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  99573. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  99574. }
  99575. else {
  99576. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  99577. }
  99578. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  99579. this._lineShader.bind(this._source.getWorldMatrix());
  99580. // Draw order
  99581. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  99582. this._lineShader.unbind();
  99583. };
  99584. return EdgesRenderer;
  99585. }());
  99586. BABYLON.EdgesRenderer = EdgesRenderer;
  99587. })(BABYLON || (BABYLON = {}));
  99588. //# sourceMappingURL=babylon.edgesRenderer.js.map
  99589. var BABYLON;
  99590. (function (BABYLON) {
  99591. /**
  99592. * FaceAdjacencies Helper class to generate edges
  99593. */
  99594. var FaceAdjacencies = /** @class */ (function () {
  99595. function FaceAdjacencies() {
  99596. this.edges = new Array();
  99597. this.edgesConnectedCount = 0;
  99598. }
  99599. return FaceAdjacencies;
  99600. }());
  99601. /**
  99602. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  99603. */
  99604. var LineEdgesRenderer = /** @class */ (function (_super) {
  99605. __extends(LineEdgesRenderer, _super);
  99606. /**
  99607. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  99608. * @param source LineMesh used to generate edges
  99609. * @param epsilon not important (specified angle for edge detection)
  99610. * @param checkVerticesInsteadOfIndices not important for LineMesh
  99611. */
  99612. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  99613. if (epsilon === void 0) { epsilon = 0.95; }
  99614. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99615. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  99616. _this._generateEdgesLines();
  99617. return _this;
  99618. }
  99619. /**
  99620. * Always create the edge since its a line so only important things are p0 and p1
  99621. * @param faceIndex not important for LineMesh
  99622. * @param edge not important for LineMesh
  99623. * @param faceNormals not important for LineMesh
  99624. * @param p0 beginnig of line
  99625. * @param p1 end of line
  99626. */
  99627. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99628. var offset = this._linesPositions.length / 3;
  99629. var normal = p0.subtract(p1);
  99630. normal.normalize();
  99631. // Positions
  99632. this._linesPositions.push(p0.x);
  99633. this._linesPositions.push(p0.y);
  99634. this._linesPositions.push(p0.z);
  99635. this._linesPositions.push(p0.x);
  99636. this._linesPositions.push(p0.y);
  99637. this._linesPositions.push(p0.z);
  99638. this._linesPositions.push(p1.x);
  99639. this._linesPositions.push(p1.y);
  99640. this._linesPositions.push(p1.z);
  99641. this._linesPositions.push(p1.x);
  99642. this._linesPositions.push(p1.y);
  99643. this._linesPositions.push(p1.z);
  99644. // Normals
  99645. this._linesNormals.push(p1.x);
  99646. this._linesNormals.push(p1.y);
  99647. this._linesNormals.push(p1.z);
  99648. this._linesNormals.push(-1);
  99649. this._linesNormals.push(p1.x);
  99650. this._linesNormals.push(p1.y);
  99651. this._linesNormals.push(p1.z);
  99652. this._linesNormals.push(1);
  99653. this._linesNormals.push(p0.x);
  99654. this._linesNormals.push(p0.y);
  99655. this._linesNormals.push(p0.z);
  99656. this._linesNormals.push(-1);
  99657. this._linesNormals.push(p0.x);
  99658. this._linesNormals.push(p0.y);
  99659. this._linesNormals.push(p0.z);
  99660. this._linesNormals.push(1);
  99661. // Indices
  99662. this._linesIndices.push(offset);
  99663. this._linesIndices.push(offset + 1);
  99664. this._linesIndices.push(offset + 2);
  99665. this._linesIndices.push(offset);
  99666. this._linesIndices.push(offset + 2);
  99667. this._linesIndices.push(offset + 3);
  99668. };
  99669. /**
  99670. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  99671. */
  99672. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  99673. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99674. var indices = this._source.getIndices();
  99675. if (!indices || !positions) {
  99676. return;
  99677. }
  99678. // First let's find adjacencies
  99679. var adjacencies = new Array();
  99680. var faceNormals = new Array();
  99681. var index;
  99682. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  99683. var currentAdjecancy = new FaceAdjacencies();
  99684. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  99685. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  99686. adjacencies.push(currentAdjecancy);
  99687. }
  99688. // Create lines
  99689. for (index = 0; index < adjacencies.length; index++) {
  99690. // 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
  99691. var current = adjacencies[index];
  99692. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99693. }
  99694. // Merge into a single mesh
  99695. var engine = this._source.getScene().getEngine();
  99696. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99697. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99698. this._ib = engine.createIndexBuffer(this._linesIndices);
  99699. this._indicesCount = this._linesIndices.length;
  99700. };
  99701. return LineEdgesRenderer;
  99702. }(BABYLON.EdgesRenderer));
  99703. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  99704. })(BABYLON || (BABYLON = {}));
  99705. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  99706. var BABYLON;
  99707. (function (BABYLON) {
  99708. // Adds the parser to the scene parsers.
  99709. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  99710. if (parsedData.effectLayers) {
  99711. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  99712. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  99713. container.effectLayers.push(effectLayer);
  99714. }
  99715. }
  99716. });
  99717. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  99718. var index = this.effectLayers.indexOf(toRemove);
  99719. if (index !== -1) {
  99720. this.effectLayers.splice(index, 1);
  99721. }
  99722. return index;
  99723. };
  99724. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  99725. this.effectLayers.push(newEffectLayer);
  99726. };
  99727. /**
  99728. * Defines the layer scene component responsible to manage any effect layers
  99729. * in a given scene.
  99730. */
  99731. var EffectLayerSceneComponent = /** @class */ (function () {
  99732. /**
  99733. * Creates a new instance of the component for the given scene
  99734. * @param scene Defines the scene to register the component in
  99735. */
  99736. function EffectLayerSceneComponent(scene) {
  99737. /**
  99738. * The component name helpfull to identify the component in the list of scene components.
  99739. */
  99740. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  99741. this._renderEffects = false;
  99742. this._needStencil = false;
  99743. this._previousStencilState = false;
  99744. this.scene = scene;
  99745. this._engine = scene.getEngine();
  99746. scene.effectLayers = new Array();
  99747. }
  99748. /**
  99749. * Registers the component in a given scene
  99750. */
  99751. EffectLayerSceneComponent.prototype.register = function () {
  99752. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  99753. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  99754. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  99755. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  99756. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  99757. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  99758. };
  99759. /**
  99760. * Rebuilds the elements related to this component in case of
  99761. * context lost for instance.
  99762. */
  99763. EffectLayerSceneComponent.prototype.rebuild = function () {
  99764. var layers = this.scene.effectLayers;
  99765. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99766. var effectLayer = layers_1[_i];
  99767. effectLayer._rebuild();
  99768. }
  99769. };
  99770. /**
  99771. * Serializes the component data to the specified json object
  99772. * @param serializationObject The object to serialize to
  99773. */
  99774. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  99775. // Effect layers
  99776. serializationObject.effectLayers = [];
  99777. var layers = this.scene.effectLayers;
  99778. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99779. var effectLayer = layers_2[_i];
  99780. if (effectLayer.serialize) {
  99781. serializationObject.effectLayers.push(effectLayer.serialize());
  99782. }
  99783. }
  99784. };
  99785. /**
  99786. * Adds all the element from the container to the scene
  99787. * @param container the container holding the elements
  99788. */
  99789. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  99790. var _this = this;
  99791. if (!container.effectLayers) {
  99792. return;
  99793. }
  99794. container.effectLayers.forEach(function (o) {
  99795. _this.scene.addEffectLayer(o);
  99796. });
  99797. };
  99798. /**
  99799. * Removes all the elements in the container from the scene
  99800. * @param container contains the elements to remove
  99801. */
  99802. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  99803. var _this = this;
  99804. if (!container.effectLayers) {
  99805. return;
  99806. }
  99807. container.effectLayers.forEach(function (o) {
  99808. _this.scene.removeEffectLayer(o);
  99809. });
  99810. };
  99811. /**
  99812. * Disposes the component and the associated ressources.
  99813. */
  99814. EffectLayerSceneComponent.prototype.dispose = function () {
  99815. var layers = this.scene.effectLayers;
  99816. while (layers.length) {
  99817. layers[0].dispose();
  99818. }
  99819. };
  99820. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  99821. var layers = this.scene.effectLayers;
  99822. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  99823. var layer = layers_3[_i];
  99824. if (!layer.hasMesh(mesh)) {
  99825. continue;
  99826. }
  99827. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  99828. var subMesh = _b[_a];
  99829. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  99830. return false;
  99831. }
  99832. }
  99833. }
  99834. return true;
  99835. };
  99836. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  99837. this._renderEffects = false;
  99838. this._needStencil = false;
  99839. var layers = this.scene.effectLayers;
  99840. if (layers && layers.length > 0) {
  99841. this._previousStencilState = this._engine.getStencilBuffer();
  99842. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  99843. var effectLayer = layers_4[_i];
  99844. if (effectLayer.shouldRender() &&
  99845. (!effectLayer.camera ||
  99846. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  99847. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  99848. this._renderEffects = true;
  99849. this._needStencil = this._needStencil || effectLayer.needStencil();
  99850. var renderTarget = effectLayer._mainTexture;
  99851. if (renderTarget._shouldRender()) {
  99852. this.scene.incrementRenderId();
  99853. renderTarget.render(false, false);
  99854. }
  99855. }
  99856. }
  99857. this.scene.incrementRenderId();
  99858. }
  99859. };
  99860. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  99861. // Activate effect Layer stencil
  99862. if (this._needStencil) {
  99863. this._engine.setStencilBuffer(true);
  99864. }
  99865. };
  99866. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  99867. // Restore effect Layer stencil
  99868. if (this._needStencil) {
  99869. this._engine.setStencilBuffer(this._previousStencilState);
  99870. }
  99871. };
  99872. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  99873. if (this._renderEffects) {
  99874. this._engine.setDepthBuffer(false);
  99875. var layers = this.scene.effectLayers;
  99876. for (var i = 0; i < layers.length; i++) {
  99877. var effectLayer = layers[i];
  99878. if (effectLayer.renderingGroupId === renderingGroupId) {
  99879. if (effectLayer.shouldRender()) {
  99880. effectLayer.render();
  99881. }
  99882. }
  99883. }
  99884. this._engine.setDepthBuffer(true);
  99885. }
  99886. };
  99887. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  99888. if (this._renderEffects) {
  99889. this._draw(-1);
  99890. }
  99891. };
  99892. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  99893. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  99894. this._draw(index);
  99895. }
  99896. };
  99897. return EffectLayerSceneComponent;
  99898. }());
  99899. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  99900. })(BABYLON || (BABYLON = {}));
  99901. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  99902. var __assign = (this && this.__assign) || function () {
  99903. __assign = Object.assign || function(t) {
  99904. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99905. s = arguments[i];
  99906. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99907. t[p] = s[p];
  99908. }
  99909. return t;
  99910. };
  99911. return __assign.apply(this, arguments);
  99912. };
  99913. var BABYLON;
  99914. (function (BABYLON) {
  99915. /**
  99916. * The effect layer Helps adding post process effect blended with the main pass.
  99917. *
  99918. * This can be for instance use to generate glow or higlight effects on the scene.
  99919. *
  99920. * The effect layer class can not be used directly and is intented to inherited from to be
  99921. * customized per effects.
  99922. */
  99923. var EffectLayer = /** @class */ (function () {
  99924. /**
  99925. * Instantiates a new effect Layer and references it in the scene.
  99926. * @param name The name of the layer
  99927. * @param scene The scene to use the layer in
  99928. */
  99929. function EffectLayer(
  99930. /** The Friendly of the effect in the scene */
  99931. name, scene) {
  99932. this._vertexBuffers = {};
  99933. this._maxSize = 0;
  99934. this._mainTextureDesiredSize = { width: 0, height: 0 };
  99935. this._shouldRender = true;
  99936. this._postProcesses = [];
  99937. this._textures = [];
  99938. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  99939. /**
  99940. * The clear color of the texture used to generate the glow map.
  99941. */
  99942. this.neutralColor = new BABYLON.Color4();
  99943. /**
  99944. * Specifies wether the highlight layer is enabled or not.
  99945. */
  99946. this.isEnabled = true;
  99947. /**
  99948. * An event triggered when the effect layer has been disposed.
  99949. */
  99950. this.onDisposeObservable = new BABYLON.Observable();
  99951. /**
  99952. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  99953. */
  99954. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  99955. /**
  99956. * An event triggered when the generated texture is being merged in the scene.
  99957. */
  99958. this.onBeforeComposeObservable = new BABYLON.Observable();
  99959. /**
  99960. * An event triggered when the generated texture has been merged in the scene.
  99961. */
  99962. this.onAfterComposeObservable = new BABYLON.Observable();
  99963. /**
  99964. * An event triggered when the efffect layer changes its size.
  99965. */
  99966. this.onSizeChangedObservable = new BABYLON.Observable();
  99967. this.name = name;
  99968. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99969. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  99970. if (!component) {
  99971. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  99972. this._scene._addComponent(component);
  99973. }
  99974. this._engine = this._scene.getEngine();
  99975. this._maxSize = this._engine.getCaps().maxTextureSize;
  99976. this._scene.effectLayers.push(this);
  99977. // Generate Buffers
  99978. this._generateIndexBuffer();
  99979. this._genrateVertexBuffer();
  99980. }
  99981. Object.defineProperty(EffectLayer.prototype, "camera", {
  99982. /**
  99983. * Gets the camera attached to the layer.
  99984. */
  99985. get: function () {
  99986. return this._effectLayerOptions.camera;
  99987. },
  99988. enumerable: true,
  99989. configurable: true
  99990. });
  99991. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  99992. /**
  99993. * Gets the rendering group id the layer should render in.
  99994. */
  99995. get: function () {
  99996. return this._effectLayerOptions.renderingGroupId;
  99997. },
  99998. enumerable: true,
  99999. configurable: true
  100000. });
  100001. /**
  100002. * Initializes the effect layer with the required options.
  100003. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  100004. */
  100005. EffectLayer.prototype._init = function (options) {
  100006. // Adapt options
  100007. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  100008. this._setMainTextureSize();
  100009. this._createMainTexture();
  100010. this._createTextureAndPostProcesses();
  100011. this._mergeEffect = this._createMergeEffect();
  100012. };
  100013. /**
  100014. * Generates the index buffer of the full screen quad blending to the main canvas.
  100015. */
  100016. EffectLayer.prototype._generateIndexBuffer = function () {
  100017. // Indices
  100018. var indices = [];
  100019. indices.push(0);
  100020. indices.push(1);
  100021. indices.push(2);
  100022. indices.push(0);
  100023. indices.push(2);
  100024. indices.push(3);
  100025. this._indexBuffer = this._engine.createIndexBuffer(indices);
  100026. };
  100027. /**
  100028. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  100029. */
  100030. EffectLayer.prototype._genrateVertexBuffer = function () {
  100031. // VBO
  100032. var vertices = [];
  100033. vertices.push(1, 1);
  100034. vertices.push(-1, 1);
  100035. vertices.push(-1, -1);
  100036. vertices.push(1, -1);
  100037. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100038. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100039. };
  100040. /**
  100041. * Sets the main texture desired size which is the closest power of two
  100042. * of the engine canvas size.
  100043. */
  100044. EffectLayer.prototype._setMainTextureSize = function () {
  100045. if (this._effectLayerOptions.mainTextureFixedSize) {
  100046. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  100047. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  100048. }
  100049. else {
  100050. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  100051. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  100052. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  100053. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  100054. }
  100055. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  100056. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  100057. };
  100058. /**
  100059. * Creates the main texture for the effect layer.
  100060. */
  100061. EffectLayer.prototype._createMainTexture = function () {
  100062. var _this = this;
  100063. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  100064. width: this._mainTextureDesiredSize.width,
  100065. height: this._mainTextureDesiredSize.height
  100066. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100067. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  100068. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100069. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100070. this._mainTexture.anisotropicFilteringLevel = 1;
  100071. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100072. this._mainTexture.renderParticles = false;
  100073. this._mainTexture.renderList = null;
  100074. this._mainTexture.ignoreCameraViewport = true;
  100075. // Custom render function
  100076. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  100077. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  100078. var index;
  100079. var engine = _this._scene.getEngine();
  100080. if (depthOnlySubMeshes.length) {
  100081. engine.setColorWrite(false);
  100082. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  100083. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  100084. }
  100085. engine.setColorWrite(true);
  100086. }
  100087. for (index = 0; index < opaqueSubMeshes.length; index++) {
  100088. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  100089. }
  100090. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  100091. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  100092. }
  100093. for (index = 0; index < transparentSubMeshes.length; index++) {
  100094. _this._renderSubMesh(transparentSubMeshes.data[index]);
  100095. }
  100096. };
  100097. this._mainTexture.onClearObservable.add(function (engine) {
  100098. engine.clear(_this.neutralColor, true, true, true);
  100099. });
  100100. };
  100101. /**
  100102. * Checks for the readiness of the element composing the layer.
  100103. * @param subMesh the mesh to check for
  100104. * @param useInstances specify wether or not to use instances to render the mesh
  100105. * @param emissiveTexture the associated emissive texture used to generate the glow
  100106. * @return true if ready otherwise, false
  100107. */
  100108. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  100109. var material = subMesh.getMaterial();
  100110. if (!material) {
  100111. return false;
  100112. }
  100113. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  100114. return false;
  100115. }
  100116. var defines = [];
  100117. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100118. var mesh = subMesh.getMesh();
  100119. var uv1 = false;
  100120. var uv2 = false;
  100121. // Alpha test
  100122. if (material && material.needAlphaTesting()) {
  100123. var alphaTexture = material.getAlphaTestTexture();
  100124. if (alphaTexture) {
  100125. defines.push("#define ALPHATEST");
  100126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100127. alphaTexture.coordinatesIndex === 1) {
  100128. defines.push("#define DIFFUSEUV2");
  100129. uv2 = true;
  100130. }
  100131. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100132. defines.push("#define DIFFUSEUV1");
  100133. uv1 = true;
  100134. }
  100135. }
  100136. }
  100137. // Emissive
  100138. if (emissiveTexture) {
  100139. defines.push("#define EMISSIVE");
  100140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100141. emissiveTexture.coordinatesIndex === 1) {
  100142. defines.push("#define EMISSIVEUV2");
  100143. uv2 = true;
  100144. }
  100145. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100146. defines.push("#define EMISSIVEUV1");
  100147. uv1 = true;
  100148. }
  100149. }
  100150. if (uv1) {
  100151. attribs.push(BABYLON.VertexBuffer.UVKind);
  100152. defines.push("#define UV1");
  100153. }
  100154. if (uv2) {
  100155. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100156. defines.push("#define UV2");
  100157. }
  100158. // Bones
  100159. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100160. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100161. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100162. if (mesh.numBoneInfluencers > 4) {
  100163. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100164. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100165. }
  100166. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100167. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  100168. }
  100169. else {
  100170. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100171. }
  100172. // Morph targets
  100173. var manager = mesh.morphTargetManager;
  100174. var morphInfluencers = 0;
  100175. if (manager) {
  100176. if (manager.numInfluencers > 0) {
  100177. defines.push("#define MORPHTARGETS");
  100178. morphInfluencers = manager.numInfluencers;
  100179. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  100180. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  100181. }
  100182. }
  100183. // Instances
  100184. if (useInstances) {
  100185. defines.push("#define INSTANCES");
  100186. attribs.push("world0");
  100187. attribs.push("world1");
  100188. attribs.push("world2");
  100189. attribs.push("world3");
  100190. }
  100191. // Get correct effect
  100192. var join = defines.join("\n");
  100193. if (this._cachedDefines !== join) {
  100194. this._cachedDefines = join;
  100195. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  100196. }
  100197. return this._effectLayerMapGenerationEffect.isReady();
  100198. };
  100199. /**
  100200. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  100201. */
  100202. EffectLayer.prototype.render = function () {
  100203. var currentEffect = this._mergeEffect;
  100204. // Check
  100205. if (!currentEffect.isReady())
  100206. return;
  100207. for (var i = 0; i < this._postProcesses.length; i++) {
  100208. if (!this._postProcesses[i].isReady()) {
  100209. return;
  100210. }
  100211. }
  100212. var engine = this._scene.getEngine();
  100213. this.onBeforeComposeObservable.notifyObservers(this);
  100214. // Render
  100215. engine.enableEffect(currentEffect);
  100216. engine.setState(false);
  100217. // VBOs
  100218. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100219. // Cache
  100220. var previousAlphaMode = engine.getAlphaMode();
  100221. // Go Blend.
  100222. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  100223. // Blends the map on the main canvas.
  100224. this._internalRender(currentEffect);
  100225. // Restore Alpha
  100226. engine.setAlphaMode(previousAlphaMode);
  100227. this.onAfterComposeObservable.notifyObservers(this);
  100228. // Handle size changes.
  100229. var size = this._mainTexture.getSize();
  100230. this._setMainTextureSize();
  100231. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  100232. // Recreate RTT and post processes on size change.
  100233. this.onSizeChangedObservable.notifyObservers(this);
  100234. this._disposeTextureAndPostProcesses();
  100235. this._createMainTexture();
  100236. this._createTextureAndPostProcesses();
  100237. }
  100238. };
  100239. /**
  100240. * Determine if a given mesh will be used in the current effect.
  100241. * @param mesh mesh to test
  100242. * @returns true if the mesh will be used
  100243. */
  100244. EffectLayer.prototype.hasMesh = function (mesh) {
  100245. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  100246. return true;
  100247. }
  100248. return false;
  100249. };
  100250. /**
  100251. * Returns true if the layer contains information to display, otherwise false.
  100252. * @returns true if the glow layer should be rendered
  100253. */
  100254. EffectLayer.prototype.shouldRender = function () {
  100255. return this.isEnabled && this._shouldRender;
  100256. };
  100257. /**
  100258. * Returns true if the mesh should render, otherwise false.
  100259. * @param mesh The mesh to render
  100260. * @returns true if it should render otherwise false
  100261. */
  100262. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  100263. return true;
  100264. };
  100265. /**
  100266. * Returns true if the mesh should render, otherwise false.
  100267. * @param mesh The mesh to render
  100268. * @returns true if it should render otherwise false
  100269. */
  100270. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  100271. return true;
  100272. };
  100273. /**
  100274. * Renders the submesh passed in parameter to the generation map.
  100275. */
  100276. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  100277. var _this = this;
  100278. if (!this.shouldRender()) {
  100279. return;
  100280. }
  100281. var material = subMesh.getMaterial();
  100282. var mesh = subMesh.getRenderingMesh();
  100283. var scene = this._scene;
  100284. var engine = scene.getEngine();
  100285. if (!material) {
  100286. return;
  100287. }
  100288. // Do not block in blend mode.
  100289. if (material.needAlphaBlendingForMesh(mesh)) {
  100290. return;
  100291. }
  100292. // Culling
  100293. engine.setState(material.backFaceCulling);
  100294. // Managing instances
  100295. var batch = mesh._getInstancesRenderList(subMesh._id);
  100296. if (batch.mustReturn) {
  100297. return;
  100298. }
  100299. // Early Exit per mesh
  100300. if (!this._shouldRenderMesh(mesh)) {
  100301. return;
  100302. }
  100303. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100304. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  100305. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  100306. engine.enableEffect(this._effectLayerMapGenerationEffect);
  100307. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  100308. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  100309. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  100310. // Alpha test
  100311. if (material && material.needAlphaTesting()) {
  100312. var alphaTexture = material.getAlphaTestTexture();
  100313. if (alphaTexture) {
  100314. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  100315. var textureMatrix = alphaTexture.getTextureMatrix();
  100316. if (textureMatrix) {
  100317. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  100318. }
  100319. }
  100320. }
  100321. // Glow emissive only
  100322. if (this._emissiveTextureAndColor.texture) {
  100323. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  100324. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  100325. }
  100326. // Bones
  100327. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100328. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100329. }
  100330. // Morph targets
  100331. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  100332. // Draw
  100333. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  100334. }
  100335. else {
  100336. // Need to reset refresh rate of the main map
  100337. this._mainTexture.resetRefreshCounter();
  100338. }
  100339. };
  100340. /**
  100341. * Rebuild the required buffers.
  100342. * @hidden Internal use only.
  100343. */
  100344. EffectLayer.prototype._rebuild = function () {
  100345. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100346. if (vb) {
  100347. vb._rebuild();
  100348. }
  100349. this._generateIndexBuffer();
  100350. };
  100351. /**
  100352. * Dispose only the render target textures and post process.
  100353. */
  100354. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  100355. this._mainTexture.dispose();
  100356. for (var i = 0; i < this._postProcesses.length; i++) {
  100357. if (this._postProcesses[i]) {
  100358. this._postProcesses[i].dispose();
  100359. }
  100360. }
  100361. this._postProcesses = [];
  100362. for (var i = 0; i < this._textures.length; i++) {
  100363. if (this._textures[i]) {
  100364. this._textures[i].dispose();
  100365. }
  100366. }
  100367. this._textures = [];
  100368. };
  100369. /**
  100370. * Dispose the highlight layer and free resources.
  100371. */
  100372. EffectLayer.prototype.dispose = function () {
  100373. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100374. if (vertexBuffer) {
  100375. vertexBuffer.dispose();
  100376. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100377. }
  100378. if (this._indexBuffer) {
  100379. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100380. this._indexBuffer = null;
  100381. }
  100382. // Clean textures and post processes
  100383. this._disposeTextureAndPostProcesses();
  100384. // Remove from scene
  100385. var index = this._scene.effectLayers.indexOf(this, 0);
  100386. if (index > -1) {
  100387. this._scene.effectLayers.splice(index, 1);
  100388. }
  100389. // Callback
  100390. this.onDisposeObservable.notifyObservers(this);
  100391. this.onDisposeObservable.clear();
  100392. this.onBeforeRenderMainTextureObservable.clear();
  100393. this.onBeforeComposeObservable.clear();
  100394. this.onAfterComposeObservable.clear();
  100395. this.onSizeChangedObservable.clear();
  100396. };
  100397. /**
  100398. * Gets the class name of the effect layer
  100399. * @returns the string with the class name of the effect layer
  100400. */
  100401. EffectLayer.prototype.getClassName = function () {
  100402. return "EffectLayer";
  100403. };
  100404. /**
  100405. * Creates an effect layer from parsed effect layer data
  100406. * @param parsedEffectLayer defines effect layer data
  100407. * @param scene defines the current scene
  100408. * @param rootUrl defines the root URL containing the effect layer information
  100409. * @returns a parsed effect Layer
  100410. */
  100411. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  100412. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  100413. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  100414. };
  100415. __decorate([
  100416. BABYLON.serialize()
  100417. ], EffectLayer.prototype, "name", void 0);
  100418. __decorate([
  100419. BABYLON.serializeAsColor4()
  100420. ], EffectLayer.prototype, "neutralColor", void 0);
  100421. __decorate([
  100422. BABYLON.serialize()
  100423. ], EffectLayer.prototype, "isEnabled", void 0);
  100424. __decorate([
  100425. BABYLON.serializeAsCameraReference()
  100426. ], EffectLayer.prototype, "camera", null);
  100427. __decorate([
  100428. BABYLON.serialize()
  100429. ], EffectLayer.prototype, "renderingGroupId", null);
  100430. return EffectLayer;
  100431. }());
  100432. BABYLON.EffectLayer = EffectLayer;
  100433. })(BABYLON || (BABYLON = {}));
  100434. //# sourceMappingURL=babylon.effectLayer.js.map
  100435. var BABYLON;
  100436. (function (BABYLON) {
  100437. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  100438. for (var index = 0; index < this.effectLayers.length; index++) {
  100439. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  100440. return this.effectLayers[index];
  100441. }
  100442. }
  100443. return null;
  100444. };
  100445. /**
  100446. * Special Glow Blur post process only blurring the alpha channel
  100447. * It enforces keeping the most luminous color in the color channel.
  100448. */
  100449. var GlowBlurPostProcess = /** @class */ (function (_super) {
  100450. __extends(GlowBlurPostProcess, _super);
  100451. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  100452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  100453. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  100454. _this.direction = direction;
  100455. _this.kernel = kernel;
  100456. _this.onApplyObservable.add(function (effect) {
  100457. effect.setFloat2("screenSize", _this.width, _this.height);
  100458. effect.setVector2("direction", _this.direction);
  100459. effect.setFloat("blurWidth", _this.kernel);
  100460. });
  100461. return _this;
  100462. }
  100463. return GlowBlurPostProcess;
  100464. }(BABYLON.PostProcess));
  100465. /**
  100466. * The highlight layer Helps adding a glow effect around a mesh.
  100467. *
  100468. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100469. * glowy meshes to your scene.
  100470. *
  100471. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  100472. */
  100473. var HighlightLayer = /** @class */ (function (_super) {
  100474. __extends(HighlightLayer, _super);
  100475. /**
  100476. * Instantiates a new highlight Layer and references it to the scene..
  100477. * @param name The name of the layer
  100478. * @param scene The scene to use the layer in
  100479. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  100480. */
  100481. function HighlightLayer(name, scene, options) {
  100482. var _this = _super.call(this, name, scene) || this;
  100483. _this.name = name;
  100484. /**
  100485. * Specifies whether or not the inner glow is ACTIVE in the layer.
  100486. */
  100487. _this.innerGlow = true;
  100488. /**
  100489. * Specifies whether or not the outer glow is ACTIVE in the layer.
  100490. */
  100491. _this.outerGlow = true;
  100492. /**
  100493. * An event triggered when the highlight layer is being blurred.
  100494. */
  100495. _this.onBeforeBlurObservable = new BABYLON.Observable();
  100496. /**
  100497. * An event triggered when the highlight layer has been blurred.
  100498. */
  100499. _this.onAfterBlurObservable = new BABYLON.Observable();
  100500. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  100501. _this._meshes = {};
  100502. _this._excludedMeshes = {};
  100503. _this.neutralColor = HighlightLayer.NeutralColor;
  100504. // Warn on stencil
  100505. if (!_this._engine.isStencilEnable) {
  100506. 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 }");
  100507. }
  100508. // Adapt options
  100509. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  100510. // Initialize the layer
  100511. _this._init({
  100512. alphaBlendingMode: _this._options.alphaBlendingMode,
  100513. camera: _this._options.camera,
  100514. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100515. mainTextureRatio: _this._options.mainTextureRatio,
  100516. renderingGroupId: _this._options.renderingGroupId
  100517. });
  100518. // Do not render as long as no meshes have been added
  100519. _this._shouldRender = false;
  100520. return _this;
  100521. }
  100522. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  100523. /**
  100524. * Gets the horizontal size of the blur.
  100525. */
  100526. get: function () {
  100527. return this._horizontalBlurPostprocess.kernel;
  100528. },
  100529. /**
  100530. * Specifies the horizontal size of the blur.
  100531. */
  100532. set: function (value) {
  100533. this._horizontalBlurPostprocess.kernel = value;
  100534. },
  100535. enumerable: true,
  100536. configurable: true
  100537. });
  100538. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  100539. /**
  100540. * Gets the vertical size of the blur.
  100541. */
  100542. get: function () {
  100543. return this._verticalBlurPostprocess.kernel;
  100544. },
  100545. /**
  100546. * Specifies the vertical size of the blur.
  100547. */
  100548. set: function (value) {
  100549. this._verticalBlurPostprocess.kernel = value;
  100550. },
  100551. enumerable: true,
  100552. configurable: true
  100553. });
  100554. /**
  100555. * Get the effect name of the layer.
  100556. * @return The effect name
  100557. */
  100558. HighlightLayer.prototype.getEffectName = function () {
  100559. return HighlightLayer.EffectName;
  100560. };
  100561. /**
  100562. * Create the merge effect. This is the shader use to blit the information back
  100563. * to the main canvas at the end of the scene rendering.
  100564. */
  100565. HighlightLayer.prototype._createMergeEffect = function () {
  100566. // Effect
  100567. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  100568. };
  100569. /**
  100570. * Creates the render target textures and post processes used in the highlight layer.
  100571. */
  100572. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  100573. var _this = this;
  100574. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  100575. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  100576. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100577. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100578. var textureType = 0;
  100579. if (this._engine.getCaps().textureHalfFloatRender) {
  100580. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100581. }
  100582. else {
  100583. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100584. }
  100585. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  100586. width: blurTextureWidth,
  100587. height: blurTextureHeight
  100588. }, this._scene, false, true, textureType);
  100589. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100590. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100591. this._blurTexture.anisotropicFilteringLevel = 16;
  100592. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  100593. this._blurTexture.renderParticles = false;
  100594. this._blurTexture.ignoreCameraViewport = true;
  100595. this._textures = [this._blurTexture];
  100596. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  100597. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100598. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  100599. effect.setTexture("textureSampler", _this._mainTexture);
  100600. });
  100601. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100602. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100603. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100604. });
  100605. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100606. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  100607. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100608. });
  100609. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100610. }
  100611. else {
  100612. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  100613. width: blurTextureWidth,
  100614. height: blurTextureHeight
  100615. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100616. this._horizontalBlurPostprocess.width = blurTextureWidth;
  100617. this._horizontalBlurPostprocess.height = blurTextureHeight;
  100618. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100619. effect.setTexture("textureSampler", _this._mainTexture);
  100620. });
  100621. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  100622. width: blurTextureWidth,
  100623. height: blurTextureHeight
  100624. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100625. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100626. }
  100627. this._mainTexture.onAfterUnbindObservable.add(function () {
  100628. _this.onBeforeBlurObservable.notifyObservers(_this);
  100629. var internalTexture = _this._blurTexture.getInternalTexture();
  100630. if (internalTexture) {
  100631. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  100632. }
  100633. _this.onAfterBlurObservable.notifyObservers(_this);
  100634. });
  100635. // Prevent autoClear.
  100636. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100637. };
  100638. /**
  100639. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100640. */
  100641. HighlightLayer.prototype.needStencil = function () {
  100642. return true;
  100643. };
  100644. /**
  100645. * Checks for the readiness of the element composing the layer.
  100646. * @param subMesh the mesh to check for
  100647. * @param useInstances specify wether or not to use instances to render the mesh
  100648. * @param emissiveTexture the associated emissive texture used to generate the glow
  100649. * @return true if ready otherwise, false
  100650. */
  100651. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  100652. var material = subMesh.getMaterial();
  100653. var mesh = subMesh.getRenderingMesh();
  100654. if (!material || !mesh || !this._meshes) {
  100655. return false;
  100656. }
  100657. var emissiveTexture = null;
  100658. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100659. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100660. emissiveTexture = material.emissiveTexture;
  100661. }
  100662. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100663. };
  100664. /**
  100665. * Implementation specific of rendering the generating effect on the main canvas.
  100666. * @param effect The effect used to render through
  100667. */
  100668. HighlightLayer.prototype._internalRender = function (effect) {
  100669. // Texture
  100670. effect.setTexture("textureSampler", this._blurTexture);
  100671. // Cache
  100672. var engine = this._engine;
  100673. var previousStencilBuffer = engine.getStencilBuffer();
  100674. var previousStencilFunction = engine.getStencilFunction();
  100675. var previousStencilMask = engine.getStencilMask();
  100676. var previousStencilOperationPass = engine.getStencilOperationPass();
  100677. var previousStencilOperationFail = engine.getStencilOperationFail();
  100678. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  100679. var previousStencilReference = engine.getStencilFunctionReference();
  100680. // Stencil operations
  100681. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  100682. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  100683. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  100684. // Draw order
  100685. engine.setStencilMask(0x00);
  100686. engine.setStencilBuffer(true);
  100687. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  100688. // 2 passes inner outer
  100689. if (this.outerGlow) {
  100690. effect.setFloat("offset", 0);
  100691. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  100692. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100693. }
  100694. if (this.innerGlow) {
  100695. effect.setFloat("offset", 1);
  100696. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  100697. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100698. }
  100699. // Restore Cache
  100700. engine.setStencilFunction(previousStencilFunction);
  100701. engine.setStencilMask(previousStencilMask);
  100702. engine.setStencilBuffer(previousStencilBuffer);
  100703. engine.setStencilOperationPass(previousStencilOperationPass);
  100704. engine.setStencilOperationFail(previousStencilOperationFail);
  100705. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  100706. engine.setStencilFunctionReference(previousStencilReference);
  100707. };
  100708. /**
  100709. * Returns true if the layer contains information to display, otherwise false.
  100710. */
  100711. HighlightLayer.prototype.shouldRender = function () {
  100712. if (_super.prototype.shouldRender.call(this)) {
  100713. return this._meshes ? true : false;
  100714. }
  100715. return false;
  100716. };
  100717. /**
  100718. * Returns true if the mesh should render, otherwise false.
  100719. * @param mesh The mesh to render
  100720. * @returns true if it should render otherwise false
  100721. */
  100722. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  100723. // Excluded Mesh
  100724. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  100725. return false;
  100726. }
  100727. ;
  100728. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100729. return false;
  100730. }
  100731. return true;
  100732. };
  100733. /**
  100734. * Sets the required values for both the emissive texture and and the main color.
  100735. */
  100736. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100737. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100738. if (highlightLayerMesh) {
  100739. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  100740. }
  100741. else {
  100742. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100743. }
  100744. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100745. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100746. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  100747. }
  100748. else {
  100749. this._emissiveTextureAndColor.texture = null;
  100750. }
  100751. };
  100752. /**
  100753. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  100754. * @param mesh The mesh to exclude from the highlight layer
  100755. */
  100756. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  100757. if (!this._excludedMeshes) {
  100758. return;
  100759. }
  100760. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100761. if (!meshExcluded) {
  100762. this._excludedMeshes[mesh.uniqueId] = {
  100763. mesh: mesh,
  100764. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  100765. mesh.getEngine().setStencilBuffer(false);
  100766. }),
  100767. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  100768. mesh.getEngine().setStencilBuffer(true);
  100769. }),
  100770. };
  100771. }
  100772. };
  100773. /**
  100774. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  100775. * @param mesh The mesh to highlight
  100776. */
  100777. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  100778. if (!this._excludedMeshes) {
  100779. return;
  100780. }
  100781. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100782. if (meshExcluded) {
  100783. if (meshExcluded.beforeRender) {
  100784. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  100785. }
  100786. if (meshExcluded.afterRender) {
  100787. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  100788. }
  100789. }
  100790. this._excludedMeshes[mesh.uniqueId] = null;
  100791. };
  100792. /**
  100793. * Determine if a given mesh will be highlighted by the current HighlightLayer
  100794. * @param mesh mesh to test
  100795. * @returns true if the mesh will be highlighted by the current HighlightLayer
  100796. */
  100797. HighlightLayer.prototype.hasMesh = function (mesh) {
  100798. if (!this._meshes) {
  100799. return false;
  100800. }
  100801. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100802. return false;
  100803. }
  100804. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  100805. };
  100806. /**
  100807. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  100808. * @param mesh The mesh to highlight
  100809. * @param color The color of the highlight
  100810. * @param glowEmissiveOnly Extract the glow from the emissive texture
  100811. */
  100812. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  100813. var _this = this;
  100814. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  100815. if (!this._meshes) {
  100816. return;
  100817. }
  100818. var meshHighlight = this._meshes[mesh.uniqueId];
  100819. if (meshHighlight) {
  100820. meshHighlight.color = color;
  100821. }
  100822. else {
  100823. this._meshes[mesh.uniqueId] = {
  100824. mesh: mesh,
  100825. color: color,
  100826. // Lambda required for capture due to Observable this context
  100827. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  100828. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  100829. _this._defaultStencilReference(mesh);
  100830. }
  100831. else {
  100832. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  100833. }
  100834. }),
  100835. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  100836. glowEmissiveOnly: glowEmissiveOnly
  100837. };
  100838. mesh.onDisposeObservable.add(function () {
  100839. _this._disposeMesh(mesh);
  100840. });
  100841. }
  100842. this._shouldRender = true;
  100843. };
  100844. /**
  100845. * Remove a mesh from the highlight layer in order to make it stop glowing.
  100846. * @param mesh The mesh to highlight
  100847. */
  100848. HighlightLayer.prototype.removeMesh = function (mesh) {
  100849. if (!this._meshes) {
  100850. return;
  100851. }
  100852. var meshHighlight = this._meshes[mesh.uniqueId];
  100853. if (meshHighlight) {
  100854. if (meshHighlight.observerHighlight) {
  100855. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100856. }
  100857. if (meshHighlight.observerDefault) {
  100858. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100859. }
  100860. delete this._meshes[mesh.uniqueId];
  100861. }
  100862. this._shouldRender = false;
  100863. for (var meshHighlightToCheck in this._meshes) {
  100864. if (this._meshes[meshHighlightToCheck]) {
  100865. this._shouldRender = true;
  100866. break;
  100867. }
  100868. }
  100869. };
  100870. /**
  100871. * Force the stencil to the normal expected value for none glowing parts
  100872. */
  100873. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  100874. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  100875. };
  100876. /**
  100877. * Free any resources and references associated to a mesh.
  100878. * Internal use
  100879. * @param mesh The mesh to free.
  100880. * @hidden
  100881. */
  100882. HighlightLayer.prototype._disposeMesh = function (mesh) {
  100883. this.removeMesh(mesh);
  100884. this.removeExcludedMesh(mesh);
  100885. };
  100886. /**
  100887. * Dispose the highlight layer and free resources.
  100888. */
  100889. HighlightLayer.prototype.dispose = function () {
  100890. if (this._meshes) {
  100891. // Clean mesh references
  100892. for (var id in this._meshes) {
  100893. var meshHighlight = this._meshes[id];
  100894. if (meshHighlight && meshHighlight.mesh) {
  100895. if (meshHighlight.observerHighlight) {
  100896. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100897. }
  100898. if (meshHighlight.observerDefault) {
  100899. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100900. }
  100901. }
  100902. }
  100903. this._meshes = null;
  100904. }
  100905. if (this._excludedMeshes) {
  100906. for (var id in this._excludedMeshes) {
  100907. var meshHighlight = this._excludedMeshes[id];
  100908. if (meshHighlight) {
  100909. if (meshHighlight.beforeRender) {
  100910. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  100911. }
  100912. if (meshHighlight.afterRender) {
  100913. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  100914. }
  100915. }
  100916. }
  100917. this._excludedMeshes = null;
  100918. }
  100919. _super.prototype.dispose.call(this);
  100920. };
  100921. /**
  100922. * Gets the class name of the effect layer
  100923. * @returns the string with the class name of the effect layer
  100924. */
  100925. HighlightLayer.prototype.getClassName = function () {
  100926. return "HighlightLayer";
  100927. };
  100928. /**
  100929. * Serializes this Highlight layer
  100930. * @returns a serialized Highlight layer object
  100931. */
  100932. HighlightLayer.prototype.serialize = function () {
  100933. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100934. serializationObject.customType = "BABYLON.HighlightLayer";
  100935. // Highlighted meshes
  100936. serializationObject.meshes = [];
  100937. if (this._meshes) {
  100938. for (var m in this._meshes) {
  100939. var mesh = this._meshes[m];
  100940. if (mesh) {
  100941. serializationObject.meshes.push({
  100942. glowEmissiveOnly: mesh.glowEmissiveOnly,
  100943. color: mesh.color.asArray(),
  100944. meshId: mesh.mesh.id
  100945. });
  100946. }
  100947. }
  100948. }
  100949. // Excluded meshes
  100950. serializationObject.excludedMeshes = [];
  100951. if (this._excludedMeshes) {
  100952. for (var e in this._excludedMeshes) {
  100953. var excludedMesh = this._excludedMeshes[e];
  100954. if (excludedMesh) {
  100955. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  100956. }
  100957. }
  100958. }
  100959. return serializationObject;
  100960. };
  100961. /**
  100962. * Creates a Highlight layer from parsed Highlight layer data
  100963. * @param parsedHightlightLayer defines the Highlight layer data
  100964. * @param scene defines the current scene
  100965. * @param rootUrl defines the root URL containing the Highlight layer information
  100966. * @returns a parsed Highlight layer
  100967. */
  100968. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  100969. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  100970. var index;
  100971. // Excluded meshes
  100972. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  100973. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  100974. if (mesh) {
  100975. hl.addExcludedMesh(mesh);
  100976. }
  100977. }
  100978. // Included meshes
  100979. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  100980. var highlightedMesh = parsedHightlightLayer.meshes[index];
  100981. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  100982. if (mesh) {
  100983. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  100984. }
  100985. }
  100986. return hl;
  100987. };
  100988. /**
  100989. * Effect Name of the highlight layer.
  100990. */
  100991. HighlightLayer.EffectName = "HighlightLayer";
  100992. /**
  100993. * The neutral color used during the preparation of the glow effect.
  100994. * This is black by default as the blend operation is a blend operation.
  100995. */
  100996. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  100997. /**
  100998. * Stencil value used for glowing meshes.
  100999. */
  101000. HighlightLayer.GlowingMeshStencilReference = 0x02;
  101001. /**
  101002. * Stencil value used for the other meshes in the scene.
  101003. */
  101004. HighlightLayer.NormalMeshStencilReference = 0x01;
  101005. __decorate([
  101006. BABYLON.serialize()
  101007. ], HighlightLayer.prototype, "innerGlow", void 0);
  101008. __decorate([
  101009. BABYLON.serialize()
  101010. ], HighlightLayer.prototype, "outerGlow", void 0);
  101011. __decorate([
  101012. BABYLON.serialize()
  101013. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  101014. __decorate([
  101015. BABYLON.serialize()
  101016. ], HighlightLayer.prototype, "blurVerticalSize", null);
  101017. __decorate([
  101018. BABYLON.serialize("options")
  101019. ], HighlightLayer.prototype, "_options", void 0);
  101020. return HighlightLayer;
  101021. }(BABYLON.EffectLayer));
  101022. BABYLON.HighlightLayer = HighlightLayer;
  101023. })(BABYLON || (BABYLON = {}));
  101024. //# sourceMappingURL=babylon.highlightLayer.js.map
  101025. var BABYLON;
  101026. (function (BABYLON) {
  101027. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  101028. for (var index = 0; index < this.effectLayers.length; index++) {
  101029. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  101030. return this.effectLayers[index];
  101031. }
  101032. }
  101033. return null;
  101034. };
  101035. /**
  101036. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  101037. *
  101038. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  101039. * glowy meshes to your scene.
  101040. *
  101041. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  101042. */
  101043. var GlowLayer = /** @class */ (function (_super) {
  101044. __extends(GlowLayer, _super);
  101045. /**
  101046. * Instantiates a new glow Layer and references it to the scene.
  101047. * @param name The name of the layer
  101048. * @param scene The scene to use the layer in
  101049. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  101050. */
  101051. function GlowLayer(name, scene, options) {
  101052. var _this = _super.call(this, name, scene) || this;
  101053. _this._intensity = 1.0;
  101054. _this._includedOnlyMeshes = [];
  101055. _this._excludedMeshes = [];
  101056. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  101057. // Adapt options
  101058. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  101059. // Initialize the layer
  101060. _this._init({
  101061. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  101062. camera: _this._options.camera,
  101063. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  101064. mainTextureRatio: _this._options.mainTextureRatio,
  101065. renderingGroupId: _this._options.renderingGroupId
  101066. });
  101067. return _this;
  101068. }
  101069. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  101070. /**
  101071. * Gets the kernel size of the blur.
  101072. */
  101073. get: function () {
  101074. return this._horizontalBlurPostprocess1.kernel;
  101075. },
  101076. /**
  101077. * Sets the kernel size of the blur.
  101078. */
  101079. set: function (value) {
  101080. this._horizontalBlurPostprocess1.kernel = value;
  101081. this._verticalBlurPostprocess1.kernel = value;
  101082. this._horizontalBlurPostprocess2.kernel = value;
  101083. this._verticalBlurPostprocess2.kernel = value;
  101084. },
  101085. enumerable: true,
  101086. configurable: true
  101087. });
  101088. Object.defineProperty(GlowLayer.prototype, "intensity", {
  101089. /**
  101090. * Gets the glow intensity.
  101091. */
  101092. get: function () {
  101093. return this._intensity;
  101094. },
  101095. /**
  101096. * Sets the glow intensity.
  101097. */
  101098. set: function (value) {
  101099. this._intensity = value;
  101100. },
  101101. enumerable: true,
  101102. configurable: true
  101103. });
  101104. /**
  101105. * Get the effect name of the layer.
  101106. * @return The effect name
  101107. */
  101108. GlowLayer.prototype.getEffectName = function () {
  101109. return GlowLayer.EffectName;
  101110. };
  101111. /**
  101112. * Create the merge effect. This is the shader use to blit the information back
  101113. * to the main canvas at the end of the scene rendering.
  101114. */
  101115. GlowLayer.prototype._createMergeEffect = function () {
  101116. // Effect
  101117. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  101118. };
  101119. /**
  101120. * Creates the render target textures and post processes used in the glow layer.
  101121. */
  101122. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  101123. var _this = this;
  101124. var blurTextureWidth = this._mainTextureDesiredSize.width;
  101125. var blurTextureHeight = this._mainTextureDesiredSize.height;
  101126. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101127. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101128. var textureType = 0;
  101129. if (this._engine.getCaps().textureHalfFloatRender) {
  101130. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101131. }
  101132. else {
  101133. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101134. }
  101135. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  101136. width: blurTextureWidth,
  101137. height: blurTextureHeight
  101138. }, this._scene, false, true, textureType);
  101139. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101140. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101141. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101142. this._blurTexture1.renderParticles = false;
  101143. this._blurTexture1.ignoreCameraViewport = true;
  101144. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  101145. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  101146. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  101147. width: blurTextureWidth2,
  101148. height: blurTextureHeight2
  101149. }, this._scene, false, true, textureType);
  101150. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101151. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101152. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101153. this._blurTexture2.renderParticles = false;
  101154. this._blurTexture2.ignoreCameraViewport = true;
  101155. this._textures = [this._blurTexture1, this._blurTexture2];
  101156. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101157. width: blurTextureWidth,
  101158. height: blurTextureHeight
  101159. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101160. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  101161. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  101162. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  101163. effect.setTexture("textureSampler", _this._mainTexture);
  101164. });
  101165. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101166. width: blurTextureWidth,
  101167. height: blurTextureHeight
  101168. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101169. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101170. width: blurTextureWidth2,
  101171. height: blurTextureHeight2
  101172. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101173. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  101174. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  101175. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  101176. effect.setTexture("textureSampler", _this._blurTexture1);
  101177. });
  101178. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101179. width: blurTextureWidth2,
  101180. height: blurTextureHeight2
  101181. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101182. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101183. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  101184. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101185. this._mainTexture.samples = this._options.mainTextureSamples;
  101186. this._mainTexture.onAfterUnbindObservable.add(function () {
  101187. var internalTexture = _this._blurTexture1.getInternalTexture();
  101188. if (internalTexture) {
  101189. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  101190. internalTexture = _this._blurTexture2.getInternalTexture();
  101191. if (internalTexture) {
  101192. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  101193. }
  101194. }
  101195. });
  101196. // Prevent autoClear.
  101197. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  101198. };
  101199. /**
  101200. * Checks for the readiness of the element composing the layer.
  101201. * @param subMesh the mesh to check for
  101202. * @param useInstances specify wether or not to use instances to render the mesh
  101203. * @param emissiveTexture the associated emissive texture used to generate the glow
  101204. * @return true if ready otherwise, false
  101205. */
  101206. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  101207. var material = subMesh.getMaterial();
  101208. var mesh = subMesh.getRenderingMesh();
  101209. if (!material || !mesh) {
  101210. return false;
  101211. }
  101212. var emissiveTexture = material.emissiveTexture;
  101213. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  101214. };
  101215. /**
  101216. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  101217. */
  101218. GlowLayer.prototype.needStencil = function () {
  101219. return false;
  101220. };
  101221. /**
  101222. * Implementation specific of rendering the generating effect on the main canvas.
  101223. * @param effect The effect used to render through
  101224. */
  101225. GlowLayer.prototype._internalRender = function (effect) {
  101226. // Texture
  101227. effect.setTexture("textureSampler", this._blurTexture1);
  101228. effect.setTexture("textureSampler2", this._blurTexture2);
  101229. effect.setFloat("offset", this._intensity);
  101230. // Cache
  101231. var engine = this._engine;
  101232. var previousStencilBuffer = engine.getStencilBuffer();
  101233. // Draw order
  101234. engine.setStencilBuffer(false);
  101235. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101236. // Draw order
  101237. engine.setStencilBuffer(previousStencilBuffer);
  101238. };
  101239. /**
  101240. * Sets the required values for both the emissive texture and and the main color.
  101241. */
  101242. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  101243. var textureLevel = 1.0;
  101244. if (this.customEmissiveTextureSelector) {
  101245. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  101246. }
  101247. else {
  101248. if (material) {
  101249. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  101250. if (this._emissiveTextureAndColor.texture) {
  101251. textureLevel = this._emissiveTextureAndColor.texture.level;
  101252. }
  101253. }
  101254. else {
  101255. this._emissiveTextureAndColor.texture = null;
  101256. }
  101257. }
  101258. if (this.customEmissiveColorSelector) {
  101259. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  101260. }
  101261. else {
  101262. if (material.emissiveColor) {
  101263. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  101264. }
  101265. else {
  101266. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  101267. }
  101268. }
  101269. };
  101270. /**
  101271. * Returns true if the mesh should render, otherwise false.
  101272. * @param mesh The mesh to render
  101273. * @returns true if it should render otherwise false
  101274. */
  101275. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  101276. return this.hasMesh(mesh);
  101277. };
  101278. /**
  101279. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  101280. * @param mesh The mesh to exclude from the glow layer
  101281. */
  101282. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  101283. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  101284. this._excludedMeshes.push(mesh.uniqueId);
  101285. }
  101286. };
  101287. /**
  101288. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  101289. * @param mesh The mesh to remove
  101290. */
  101291. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  101292. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  101293. if (index !== -1) {
  101294. this._excludedMeshes.splice(index, 1);
  101295. }
  101296. };
  101297. /**
  101298. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  101299. * @param mesh The mesh to include in the glow layer
  101300. */
  101301. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  101302. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  101303. this._includedOnlyMeshes.push(mesh.uniqueId);
  101304. }
  101305. };
  101306. /**
  101307. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  101308. * @param mesh The mesh to remove
  101309. */
  101310. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  101311. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  101312. if (index !== -1) {
  101313. this._includedOnlyMeshes.splice(index, 1);
  101314. }
  101315. };
  101316. /**
  101317. * Determine if a given mesh will be used in the glow layer
  101318. * @param mesh The mesh to test
  101319. * @returns true if the mesh will be highlighted by the current glow layer
  101320. */
  101321. GlowLayer.prototype.hasMesh = function (mesh) {
  101322. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101323. return false;
  101324. }
  101325. // Included Mesh
  101326. if (this._includedOnlyMeshes.length) {
  101327. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  101328. }
  101329. ;
  101330. // Excluded Mesh
  101331. if (this._excludedMeshes.length) {
  101332. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  101333. }
  101334. ;
  101335. return true;
  101336. };
  101337. /**
  101338. * Free any resources and references associated to a mesh.
  101339. * Internal use
  101340. * @param mesh The mesh to free.
  101341. * @hidden
  101342. */
  101343. GlowLayer.prototype._disposeMesh = function (mesh) {
  101344. this.removeIncludedOnlyMesh(mesh);
  101345. this.removeExcludedMesh(mesh);
  101346. };
  101347. /**
  101348. * Gets the class name of the effect layer
  101349. * @returns the string with the class name of the effect layer
  101350. */
  101351. GlowLayer.prototype.getClassName = function () {
  101352. return "GlowLayer";
  101353. };
  101354. /**
  101355. * Serializes this glow layer
  101356. * @returns a serialized glow layer object
  101357. */
  101358. GlowLayer.prototype.serialize = function () {
  101359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101360. serializationObject.customType = "BABYLON.GlowLayer";
  101361. var index;
  101362. // Included meshes
  101363. serializationObject.includedMeshes = [];
  101364. if (this._includedOnlyMeshes.length) {
  101365. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  101366. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  101367. if (mesh) {
  101368. serializationObject.includedMeshes.push(mesh.id);
  101369. }
  101370. }
  101371. }
  101372. // Excluded meshes
  101373. serializationObject.excludedMeshes = [];
  101374. if (this._excludedMeshes.length) {
  101375. for (index = 0; index < this._excludedMeshes.length; index++) {
  101376. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  101377. if (mesh) {
  101378. serializationObject.excludedMeshes.push(mesh.id);
  101379. }
  101380. }
  101381. }
  101382. return serializationObject;
  101383. };
  101384. /**
  101385. * Creates a Glow Layer from parsed glow layer data
  101386. * @param parsedGlowLayer defines glow layer data
  101387. * @param scene defines the current scene
  101388. * @param rootUrl defines the root URL containing the glow layer information
  101389. * @returns a parsed Glow Layer
  101390. */
  101391. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  101392. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  101393. var index;
  101394. // Excluded meshes
  101395. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  101396. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  101397. if (mesh) {
  101398. gl.addExcludedMesh(mesh);
  101399. }
  101400. }
  101401. // Included meshes
  101402. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  101403. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  101404. if (mesh) {
  101405. gl.addIncludedOnlyMesh(mesh);
  101406. }
  101407. }
  101408. return gl;
  101409. };
  101410. /**
  101411. * Effect Name of the layer.
  101412. */
  101413. GlowLayer.EffectName = "GlowLayer";
  101414. /**
  101415. * The default blur kernel size used for the glow.
  101416. */
  101417. GlowLayer.DefaultBlurKernelSize = 32;
  101418. /**
  101419. * The default texture size ratio used for the glow.
  101420. */
  101421. GlowLayer.DefaultTextureRatio = 0.5;
  101422. __decorate([
  101423. BABYLON.serialize()
  101424. ], GlowLayer.prototype, "blurKernelSize", null);
  101425. __decorate([
  101426. BABYLON.serialize()
  101427. ], GlowLayer.prototype, "intensity", null);
  101428. __decorate([
  101429. BABYLON.serialize("options")
  101430. ], GlowLayer.prototype, "_options", void 0);
  101431. return GlowLayer;
  101432. }(BABYLON.EffectLayer));
  101433. BABYLON.GlowLayer = GlowLayer;
  101434. })(BABYLON || (BABYLON = {}));
  101435. //# sourceMappingURL=babylon.glowLayer.js.map
  101436. var BABYLON;
  101437. (function (BABYLON) {
  101438. /**
  101439. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  101440. */
  101441. var AssetTaskState;
  101442. (function (AssetTaskState) {
  101443. /**
  101444. * Initialization
  101445. */
  101446. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  101447. /**
  101448. * Running
  101449. */
  101450. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  101451. /**
  101452. * Done
  101453. */
  101454. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  101455. /**
  101456. * Error
  101457. */
  101458. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  101459. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  101460. /**
  101461. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  101462. */
  101463. var AbstractAssetTask = /** @class */ (function () {
  101464. /**
  101465. * Creates a new {BABYLON.AssetsManager}
  101466. * @param name defines the name of the task
  101467. */
  101468. function AbstractAssetTask(
  101469. /**
  101470. * Task name
  101471. */ name) {
  101472. this.name = name;
  101473. this._isCompleted = false;
  101474. this._taskState = AssetTaskState.INIT;
  101475. }
  101476. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  101477. /**
  101478. * Get if the task is completed
  101479. */
  101480. get: function () {
  101481. return this._isCompleted;
  101482. },
  101483. enumerable: true,
  101484. configurable: true
  101485. });
  101486. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  101487. /**
  101488. * Gets the current state of the task
  101489. */
  101490. get: function () {
  101491. return this._taskState;
  101492. },
  101493. enumerable: true,
  101494. configurable: true
  101495. });
  101496. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  101497. /**
  101498. * Gets the current error object (if task is in error)
  101499. */
  101500. get: function () {
  101501. return this._errorObject;
  101502. },
  101503. enumerable: true,
  101504. configurable: true
  101505. });
  101506. /**
  101507. * Internal only
  101508. * @hidden
  101509. */
  101510. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  101511. if (this._errorObject) {
  101512. return;
  101513. }
  101514. this._errorObject = {
  101515. message: message,
  101516. exception: exception
  101517. };
  101518. };
  101519. /**
  101520. * Execute the current task
  101521. * @param scene defines the scene where you want your assets to be loaded
  101522. * @param onSuccess is a callback called when the task is successfully executed
  101523. * @param onError is a callback called if an error occurs
  101524. */
  101525. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101526. var _this = this;
  101527. this._taskState = AssetTaskState.RUNNING;
  101528. this.runTask(scene, function () {
  101529. _this.onDoneCallback(onSuccess, onError);
  101530. }, function (msg, exception) {
  101531. _this.onErrorCallback(onError, msg, exception);
  101532. });
  101533. };
  101534. /**
  101535. * Execute the current task
  101536. * @param scene defines the scene where you want your assets to be loaded
  101537. * @param onSuccess is a callback called when the task is successfully executed
  101538. * @param onError is a callback called if an error occurs
  101539. */
  101540. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101541. throw new Error("runTask is not implemented");
  101542. };
  101543. /**
  101544. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  101545. * This can be used with failed tasks that have the reason for failure fixed.
  101546. */
  101547. AbstractAssetTask.prototype.reset = function () {
  101548. this._taskState = AssetTaskState.INIT;
  101549. };
  101550. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  101551. this._taskState = AssetTaskState.ERROR;
  101552. this._errorObject = {
  101553. message: message,
  101554. exception: exception
  101555. };
  101556. if (this.onError) {
  101557. this.onError(this, message, exception);
  101558. }
  101559. onError();
  101560. };
  101561. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  101562. try {
  101563. this._taskState = AssetTaskState.DONE;
  101564. this._isCompleted = true;
  101565. if (this.onSuccess) {
  101566. this.onSuccess(this);
  101567. }
  101568. onSuccess();
  101569. }
  101570. catch (e) {
  101571. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  101572. }
  101573. };
  101574. return AbstractAssetTask;
  101575. }());
  101576. BABYLON.AbstractAssetTask = AbstractAssetTask;
  101577. /**
  101578. * Class used to share progress information about assets loading
  101579. */
  101580. var AssetsProgressEvent = /** @class */ (function () {
  101581. /**
  101582. * Creates a {BABYLON.AssetsProgressEvent}
  101583. * @param remainingCount defines the number of remaining tasks to process
  101584. * @param totalCount defines the total number of tasks
  101585. * @param task defines the task that was just processed
  101586. */
  101587. function AssetsProgressEvent(remainingCount, totalCount, task) {
  101588. this.remainingCount = remainingCount;
  101589. this.totalCount = totalCount;
  101590. this.task = task;
  101591. }
  101592. return AssetsProgressEvent;
  101593. }());
  101594. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  101595. /**
  101596. * Define a task used by {BABYLON.AssetsManager} to load meshes
  101597. */
  101598. var MeshAssetTask = /** @class */ (function (_super) {
  101599. __extends(MeshAssetTask, _super);
  101600. /**
  101601. * Creates a new {BABYLON.MeshAssetTask}
  101602. * @param name defines the name of the task
  101603. * @param meshesNames defines the list of mesh's names you want to load
  101604. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  101605. * @param sceneFilename defines the filename of the scene to load from
  101606. */
  101607. function MeshAssetTask(
  101608. /**
  101609. * Defines the name of the task
  101610. */
  101611. name,
  101612. /**
  101613. * Defines the list of mesh's names you want to load
  101614. */
  101615. meshesNames,
  101616. /**
  101617. * Defines the root url to use as a base to load your meshes and associated resources
  101618. */
  101619. rootUrl,
  101620. /**
  101621. * Defines the filename of the scene to load from
  101622. */
  101623. sceneFilename) {
  101624. var _this = _super.call(this, name) || this;
  101625. _this.name = name;
  101626. _this.meshesNames = meshesNames;
  101627. _this.rootUrl = rootUrl;
  101628. _this.sceneFilename = sceneFilename;
  101629. return _this;
  101630. }
  101631. /**
  101632. * Execute the current task
  101633. * @param scene defines the scene where you want your assets to be loaded
  101634. * @param onSuccess is a callback called when the task is successfully executed
  101635. * @param onError is a callback called if an error occurs
  101636. */
  101637. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101638. var _this = this;
  101639. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  101640. _this.loadedMeshes = meshes;
  101641. _this.loadedParticleSystems = particleSystems;
  101642. _this.loadedSkeletons = skeletons;
  101643. onSuccess();
  101644. }, null, function (scene, message, exception) {
  101645. onError(message, exception);
  101646. });
  101647. };
  101648. return MeshAssetTask;
  101649. }(AbstractAssetTask));
  101650. BABYLON.MeshAssetTask = MeshAssetTask;
  101651. /**
  101652. * Define a task used by {BABYLON.AssetsManager} to load text content
  101653. */
  101654. var TextFileAssetTask = /** @class */ (function (_super) {
  101655. __extends(TextFileAssetTask, _super);
  101656. /**
  101657. * Creates a new TextFileAssetTask object
  101658. * @param name defines the name of the task
  101659. * @param url defines the location of the file to load
  101660. */
  101661. function TextFileAssetTask(
  101662. /**
  101663. * Defines the name of the task
  101664. */
  101665. name,
  101666. /**
  101667. * Defines the location of the file to load
  101668. */
  101669. url) {
  101670. var _this = _super.call(this, name) || this;
  101671. _this.name = name;
  101672. _this.url = url;
  101673. return _this;
  101674. }
  101675. /**
  101676. * Execute the current task
  101677. * @param scene defines the scene where you want your assets to be loaded
  101678. * @param onSuccess is a callback called when the task is successfully executed
  101679. * @param onError is a callback called if an error occurs
  101680. */
  101681. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101682. var _this = this;
  101683. scene._loadFile(this.url, function (data) {
  101684. _this.text = data;
  101685. onSuccess();
  101686. }, undefined, false, false, function (request, exception) {
  101687. if (request) {
  101688. onError(request.status + " " + request.statusText, exception);
  101689. }
  101690. });
  101691. };
  101692. return TextFileAssetTask;
  101693. }(AbstractAssetTask));
  101694. BABYLON.TextFileAssetTask = TextFileAssetTask;
  101695. /**
  101696. * Define a task used by {BABYLON.AssetsManager} to load binary data
  101697. */
  101698. var BinaryFileAssetTask = /** @class */ (function (_super) {
  101699. __extends(BinaryFileAssetTask, _super);
  101700. /**
  101701. * Creates a new BinaryFileAssetTask object
  101702. * @param name defines the name of the new task
  101703. * @param url defines the location of the file to load
  101704. */
  101705. function BinaryFileAssetTask(
  101706. /**
  101707. * Defines the name of the task
  101708. */
  101709. name,
  101710. /**
  101711. * Defines the location of the file to load
  101712. */
  101713. url) {
  101714. var _this = _super.call(this, name) || this;
  101715. _this.name = name;
  101716. _this.url = url;
  101717. return _this;
  101718. }
  101719. /**
  101720. * Execute the current task
  101721. * @param scene defines the scene where you want your assets to be loaded
  101722. * @param onSuccess is a callback called when the task is successfully executed
  101723. * @param onError is a callback called if an error occurs
  101724. */
  101725. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101726. var _this = this;
  101727. scene._loadFile(this.url, function (data) {
  101728. _this.data = data;
  101729. onSuccess();
  101730. }, undefined, true, true, function (request, exception) {
  101731. if (request) {
  101732. onError(request.status + " " + request.statusText, exception);
  101733. }
  101734. });
  101735. };
  101736. return BinaryFileAssetTask;
  101737. }(AbstractAssetTask));
  101738. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  101739. /**
  101740. * Define a task used by {BABYLON.AssetsManager} to load images
  101741. */
  101742. var ImageAssetTask = /** @class */ (function (_super) {
  101743. __extends(ImageAssetTask, _super);
  101744. /**
  101745. * Creates a new ImageAssetTask
  101746. * @param name defines the name of the task
  101747. * @param url defines the location of the image to load
  101748. */
  101749. function ImageAssetTask(
  101750. /**
  101751. * Defines the name of the task
  101752. */
  101753. name,
  101754. /**
  101755. * Defines the location of the image to load
  101756. */
  101757. url) {
  101758. var _this = _super.call(this, name) || this;
  101759. _this.name = name;
  101760. _this.url = url;
  101761. return _this;
  101762. }
  101763. /**
  101764. * Execute the current task
  101765. * @param scene defines the scene where you want your assets to be loaded
  101766. * @param onSuccess is a callback called when the task is successfully executed
  101767. * @param onError is a callback called if an error occurs
  101768. */
  101769. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101770. var _this = this;
  101771. var img = new Image();
  101772. BABYLON.Tools.SetCorsBehavior(this.url, img);
  101773. img.onload = function () {
  101774. _this.image = img;
  101775. onSuccess();
  101776. };
  101777. img.onerror = function (err) {
  101778. onError("Error loading image", err);
  101779. };
  101780. img.src = this.url;
  101781. };
  101782. return ImageAssetTask;
  101783. }(AbstractAssetTask));
  101784. BABYLON.ImageAssetTask = ImageAssetTask;
  101785. /**
  101786. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  101787. */
  101788. var TextureAssetTask = /** @class */ (function (_super) {
  101789. __extends(TextureAssetTask, _super);
  101790. /**
  101791. * Creates a new TextureAssetTask object
  101792. * @param name defines the name of the task
  101793. * @param url defines the location of the file to load
  101794. * @param noMipmap defines if mipmap should not be generated (default is false)
  101795. * @param invertY defines if texture must be inverted on Y axis (default is false)
  101796. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101797. */
  101798. function TextureAssetTask(
  101799. /**
  101800. * Defines the name of the task
  101801. */
  101802. name,
  101803. /**
  101804. * Defines the location of the file to load
  101805. */
  101806. url,
  101807. /**
  101808. * Defines if mipmap should not be generated (default is false)
  101809. */
  101810. noMipmap,
  101811. /**
  101812. * Defines if texture must be inverted on Y axis (default is false)
  101813. */
  101814. invertY,
  101815. /**
  101816. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101817. */
  101818. samplingMode) {
  101819. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101820. var _this = _super.call(this, name) || this;
  101821. _this.name = name;
  101822. _this.url = url;
  101823. _this.noMipmap = noMipmap;
  101824. _this.invertY = invertY;
  101825. _this.samplingMode = samplingMode;
  101826. return _this;
  101827. }
  101828. /**
  101829. * Execute the current task
  101830. * @param scene defines the scene where you want your assets to be loaded
  101831. * @param onSuccess is a callback called when the task is successfully executed
  101832. * @param onError is a callback called if an error occurs
  101833. */
  101834. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101835. var onload = function () {
  101836. onSuccess();
  101837. };
  101838. var onerror = function (message, exception) {
  101839. onError(message, exception);
  101840. };
  101841. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  101842. };
  101843. return TextureAssetTask;
  101844. }(AbstractAssetTask));
  101845. BABYLON.TextureAssetTask = TextureAssetTask;
  101846. /**
  101847. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  101848. */
  101849. var CubeTextureAssetTask = /** @class */ (function (_super) {
  101850. __extends(CubeTextureAssetTask, _super);
  101851. /**
  101852. * Creates a new CubeTextureAssetTask
  101853. * @param name defines the name of the task
  101854. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101855. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101856. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101857. * @param files defines the explicit list of files (undefined by default)
  101858. */
  101859. function CubeTextureAssetTask(
  101860. /**
  101861. * Defines the name of the task
  101862. */
  101863. name,
  101864. /**
  101865. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101866. */
  101867. url,
  101868. /**
  101869. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101870. */
  101871. extensions,
  101872. /**
  101873. * Defines if mipmaps should not be generated (default is false)
  101874. */
  101875. noMipmap,
  101876. /**
  101877. * Defines the explicit list of files (undefined by default)
  101878. */
  101879. files) {
  101880. var _this = _super.call(this, name) || this;
  101881. _this.name = name;
  101882. _this.url = url;
  101883. _this.extensions = extensions;
  101884. _this.noMipmap = noMipmap;
  101885. _this.files = files;
  101886. return _this;
  101887. }
  101888. /**
  101889. * Execute the current task
  101890. * @param scene defines the scene where you want your assets to be loaded
  101891. * @param onSuccess is a callback called when the task is successfully executed
  101892. * @param onError is a callback called if an error occurs
  101893. */
  101894. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101895. var onload = function () {
  101896. onSuccess();
  101897. };
  101898. var onerror = function (message, exception) {
  101899. onError(message, exception);
  101900. };
  101901. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  101902. };
  101903. return CubeTextureAssetTask;
  101904. }(AbstractAssetTask));
  101905. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  101906. /**
  101907. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  101908. */
  101909. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  101910. __extends(HDRCubeTextureAssetTask, _super);
  101911. /**
  101912. * Creates a new HDRCubeTextureAssetTask object
  101913. * @param name defines the name of the task
  101914. * @param url defines the location of the file to load
  101915. * @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.
  101916. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101917. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101918. * @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)
  101919. * @param reserved Internal use only
  101920. */
  101921. function HDRCubeTextureAssetTask(
  101922. /**
  101923. * Defines the name of the task
  101924. */
  101925. name,
  101926. /**
  101927. * Defines the location of the file to load
  101928. */
  101929. url,
  101930. /**
  101931. * Defines the desired size (the more it increases the longer the generation will be)
  101932. */
  101933. size,
  101934. /**
  101935. * Defines if mipmaps should not be generated (default is false)
  101936. */
  101937. noMipmap,
  101938. /**
  101939. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101940. */
  101941. generateHarmonics,
  101942. /**
  101943. * 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)
  101944. */
  101945. gammaSpace,
  101946. /**
  101947. * Internal Use Only
  101948. */
  101949. reserved) {
  101950. if (noMipmap === void 0) { noMipmap = false; }
  101951. if (generateHarmonics === void 0) { generateHarmonics = true; }
  101952. if (gammaSpace === void 0) { gammaSpace = false; }
  101953. if (reserved === void 0) { reserved = false; }
  101954. var _this = _super.call(this, name) || this;
  101955. _this.name = name;
  101956. _this.url = url;
  101957. _this.size = size;
  101958. _this.noMipmap = noMipmap;
  101959. _this.generateHarmonics = generateHarmonics;
  101960. _this.gammaSpace = gammaSpace;
  101961. _this.reserved = reserved;
  101962. return _this;
  101963. }
  101964. /**
  101965. * Execute the current task
  101966. * @param scene defines the scene where you want your assets to be loaded
  101967. * @param onSuccess is a callback called when the task is successfully executed
  101968. * @param onError is a callback called if an error occurs
  101969. */
  101970. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101971. var onload = function () {
  101972. onSuccess();
  101973. };
  101974. var onerror = function (message, exception) {
  101975. onError(message, exception);
  101976. };
  101977. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  101978. };
  101979. return HDRCubeTextureAssetTask;
  101980. }(AbstractAssetTask));
  101981. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  101982. /**
  101983. * This class can be used to easily import assets into a scene
  101984. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  101985. */
  101986. var AssetsManager = /** @class */ (function () {
  101987. /**
  101988. * Creates a new AssetsManager
  101989. * @param scene defines the scene to work on
  101990. */
  101991. function AssetsManager(scene) {
  101992. this._isLoading = false;
  101993. this._tasks = new Array();
  101994. this._waitingTasksCount = 0;
  101995. this._totalTasksCount = 0;
  101996. /**
  101997. * Observable called when all tasks are processed
  101998. */
  101999. this.onTaskSuccessObservable = new BABYLON.Observable();
  102000. /**
  102001. * Observable called when a task had an error
  102002. */
  102003. this.onTaskErrorObservable = new BABYLON.Observable();
  102004. /**
  102005. * Observable called when a task is successful
  102006. */
  102007. this.onTasksDoneObservable = new BABYLON.Observable();
  102008. /**
  102009. * Observable called when a task is done (whatever the result is)
  102010. */
  102011. this.onProgressObservable = new BABYLON.Observable();
  102012. /**
  102013. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  102014. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  102015. */
  102016. this.useDefaultLoadingScreen = true;
  102017. this._scene = scene;
  102018. }
  102019. /**
  102020. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  102021. * @param taskName defines the name of the new task
  102022. * @param meshesNames defines the name of meshes to load
  102023. * @param rootUrl defines the root url to use to locate files
  102024. * @param sceneFilename defines the filename of the scene file
  102025. * @returns a new {BABYLON.MeshAssetTask} object
  102026. */
  102027. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  102028. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  102029. this._tasks.push(task);
  102030. return task;
  102031. };
  102032. /**
  102033. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  102034. * @param taskName defines the name of the new task
  102035. * @param url defines the url of the file to load
  102036. * @returns a new {BABYLON.TextFileAssetTask} object
  102037. */
  102038. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  102039. var task = new TextFileAssetTask(taskName, url);
  102040. this._tasks.push(task);
  102041. return task;
  102042. };
  102043. /**
  102044. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  102045. * @param taskName defines the name of the new task
  102046. * @param url defines the url of the file to load
  102047. * @returns a new {BABYLON.BinaryFileAssetTask} object
  102048. */
  102049. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  102050. var task = new BinaryFileAssetTask(taskName, url);
  102051. this._tasks.push(task);
  102052. return task;
  102053. };
  102054. /**
  102055. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  102056. * @param taskName defines the name of the new task
  102057. * @param url defines the url of the file to load
  102058. * @returns a new {BABYLON.ImageAssetTask} object
  102059. */
  102060. AssetsManager.prototype.addImageTask = function (taskName, url) {
  102061. var task = new ImageAssetTask(taskName, url);
  102062. this._tasks.push(task);
  102063. return task;
  102064. };
  102065. /**
  102066. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  102067. * @param taskName defines the name of the new task
  102068. * @param url defines the url of the file to load
  102069. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102070. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  102071. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  102072. * @returns a new {BABYLON.TextureAssetTask} object
  102073. */
  102074. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  102075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102076. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  102077. this._tasks.push(task);
  102078. return task;
  102079. };
  102080. /**
  102081. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  102082. * @param taskName defines the name of the new task
  102083. * @param url defines the url of the file to load
  102084. * @param extensions defines the extension to use to load the cube map (can be null)
  102085. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102086. * @param files defines the list of files to load (can be null)
  102087. * @returns a new {BABYLON.CubeTextureAssetTask} object
  102088. */
  102089. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  102090. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  102091. this._tasks.push(task);
  102092. return task;
  102093. };
  102094. /**
  102095. *
  102096. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  102097. * @param taskName defines the name of the new task
  102098. * @param url defines the url of the file to load
  102099. * @param size defines the size you want for the cubemap (can be null)
  102100. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102101. * @param generateHarmonics defines if you want to automatically generate (true by default)
  102102. * @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)
  102103. * @param reserved Internal use only
  102104. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  102105. */
  102106. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  102107. if (noMipmap === void 0) { noMipmap = false; }
  102108. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102109. if (gammaSpace === void 0) { gammaSpace = false; }
  102110. if (reserved === void 0) { reserved = false; }
  102111. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  102112. this._tasks.push(task);
  102113. return task;
  102114. };
  102115. /**
  102116. * Remove a task from the assets manager.
  102117. * @param task the task to remove
  102118. */
  102119. AssetsManager.prototype.removeTask = function (task) {
  102120. var index = this._tasks.indexOf(task);
  102121. if (index > -1) {
  102122. this._tasks.splice(index, 1);
  102123. }
  102124. };
  102125. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  102126. this._waitingTasksCount--;
  102127. try {
  102128. if (this.onProgress) {
  102129. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  102130. }
  102131. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  102132. }
  102133. catch (e) {
  102134. BABYLON.Tools.Error("Error running progress callbacks.");
  102135. console.log(e);
  102136. }
  102137. if (this._waitingTasksCount === 0) {
  102138. try {
  102139. if (this.onFinish) {
  102140. this.onFinish(this._tasks);
  102141. }
  102142. // Let's remove successfull tasks
  102143. var currentTasks = this._tasks.slice();
  102144. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  102145. var task = currentTasks_1[_i];
  102146. if (task.taskState === AssetTaskState.DONE) {
  102147. var index = this._tasks.indexOf(task);
  102148. if (index > -1) {
  102149. this._tasks.splice(index, 1);
  102150. }
  102151. }
  102152. }
  102153. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102154. }
  102155. catch (e) {
  102156. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  102157. console.log(e);
  102158. }
  102159. this._isLoading = false;
  102160. this._scene.getEngine().hideLoadingUI();
  102161. }
  102162. };
  102163. AssetsManager.prototype._runTask = function (task) {
  102164. var _this = this;
  102165. var done = function () {
  102166. try {
  102167. if (_this.onTaskSuccess) {
  102168. _this.onTaskSuccess(task);
  102169. }
  102170. _this.onTaskSuccessObservable.notifyObservers(task);
  102171. _this._decreaseWaitingTasksCount(task);
  102172. }
  102173. catch (e) {
  102174. error("Error executing task success callbacks", e);
  102175. }
  102176. };
  102177. var error = function (message, exception) {
  102178. task._setErrorObject(message, exception);
  102179. if (_this.onTaskError) {
  102180. _this.onTaskError(task);
  102181. }
  102182. _this.onTaskErrorObservable.notifyObservers(task);
  102183. _this._decreaseWaitingTasksCount(task);
  102184. };
  102185. task.run(this._scene, done, error);
  102186. };
  102187. /**
  102188. * Reset the {BABYLON.AssetsManager} and remove all tasks
  102189. * @return the current instance of the {BABYLON.AssetsManager}
  102190. */
  102191. AssetsManager.prototype.reset = function () {
  102192. this._isLoading = false;
  102193. this._tasks = new Array();
  102194. return this;
  102195. };
  102196. /**
  102197. * Start the loading process
  102198. * @return the current instance of the {BABYLON.AssetsManager}
  102199. */
  102200. AssetsManager.prototype.load = function () {
  102201. if (this._isLoading) {
  102202. return this;
  102203. }
  102204. this._isLoading = true;
  102205. this._waitingTasksCount = this._tasks.length;
  102206. this._totalTasksCount = this._tasks.length;
  102207. if (this._waitingTasksCount === 0) {
  102208. this._isLoading = false;
  102209. if (this.onFinish) {
  102210. this.onFinish(this._tasks);
  102211. }
  102212. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102213. return this;
  102214. }
  102215. if (this.useDefaultLoadingScreen) {
  102216. this._scene.getEngine().displayLoadingUI();
  102217. }
  102218. for (var index = 0; index < this._tasks.length; index++) {
  102219. var task = this._tasks[index];
  102220. if (task.taskState === AssetTaskState.INIT) {
  102221. this._runTask(task);
  102222. }
  102223. }
  102224. return this;
  102225. };
  102226. return AssetsManager;
  102227. }());
  102228. BABYLON.AssetsManager = AssetsManager;
  102229. })(BABYLON || (BABYLON = {}));
  102230. //# sourceMappingURL=babylon.assetsManager.js.map
  102231. var BABYLON;
  102232. (function (BABYLON) {
  102233. var serializedGeometries = [];
  102234. var serializeGeometry = function (geometry, serializationGeometries) {
  102235. if (serializedGeometries[geometry.id]) {
  102236. return;
  102237. }
  102238. if (geometry.doNotSerialize) {
  102239. return;
  102240. }
  102241. if (geometry instanceof BABYLON.BoxGeometry) {
  102242. serializationGeometries.boxes.push(geometry.serialize());
  102243. }
  102244. else if (geometry instanceof BABYLON.SphereGeometry) {
  102245. serializationGeometries.spheres.push(geometry.serialize());
  102246. }
  102247. else if (geometry instanceof BABYLON.CylinderGeometry) {
  102248. serializationGeometries.cylinders.push(geometry.serialize());
  102249. }
  102250. else if (geometry instanceof BABYLON.TorusGeometry) {
  102251. serializationGeometries.toruses.push(geometry.serialize());
  102252. }
  102253. else if (geometry instanceof BABYLON.GroundGeometry) {
  102254. serializationGeometries.grounds.push(geometry.serialize());
  102255. }
  102256. else if (geometry instanceof BABYLON.Plane) {
  102257. serializationGeometries.planes.push(geometry.serialize());
  102258. }
  102259. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  102260. serializationGeometries.torusKnots.push(geometry.serialize());
  102261. }
  102262. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  102263. throw new Error("Unknown primitive type");
  102264. }
  102265. else {
  102266. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  102267. }
  102268. serializedGeometries[geometry.id] = true;
  102269. };
  102270. var serializeMesh = function (mesh, serializationScene) {
  102271. var serializationObject = {};
  102272. // Geometry
  102273. var geometry = mesh._geometry;
  102274. if (geometry) {
  102275. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  102276. // 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
  102277. serializeGeometry(geometry, serializationScene.geometries);
  102278. }
  102279. }
  102280. // Custom
  102281. if (mesh.serialize) {
  102282. mesh.serialize(serializationObject);
  102283. }
  102284. return serializationObject;
  102285. };
  102286. var finalizeSingleMesh = function (mesh, serializationObject) {
  102287. //only works if the mesh is already loaded
  102288. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102289. //serialize material
  102290. if (mesh.material) {
  102291. if (mesh.material instanceof BABYLON.MultiMaterial) {
  102292. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  102293. serializationObject.materials = serializationObject.materials || [];
  102294. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102295. serializationObject.multiMaterials.push(mesh.material.serialize());
  102296. var _loop_1 = function (submaterial) {
  102297. if (submaterial) {
  102298. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  102299. serializationObject.materials.push(submaterial.serialize());
  102300. }
  102301. }
  102302. };
  102303. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  102304. var submaterial = _a[_i];
  102305. _loop_1(submaterial);
  102306. }
  102307. }
  102308. }
  102309. else {
  102310. serializationObject.materials = serializationObject.materials || [];
  102311. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102312. serializationObject.materials.push(mesh.material.serialize());
  102313. }
  102314. }
  102315. }
  102316. //serialize geometry
  102317. var geometry = mesh._geometry;
  102318. if (geometry) {
  102319. if (!serializationObject.geometries) {
  102320. serializationObject.geometries = {};
  102321. serializationObject.geometries.boxes = [];
  102322. serializationObject.geometries.spheres = [];
  102323. serializationObject.geometries.cylinders = [];
  102324. serializationObject.geometries.toruses = [];
  102325. serializationObject.geometries.grounds = [];
  102326. serializationObject.geometries.planes = [];
  102327. serializationObject.geometries.torusKnots = [];
  102328. serializationObject.geometries.vertexData = [];
  102329. }
  102330. serializeGeometry(geometry, serializationObject.geometries);
  102331. }
  102332. // Skeletons
  102333. if (mesh.skeleton) {
  102334. serializationObject.skeletons = serializationObject.skeletons || [];
  102335. serializationObject.skeletons.push(mesh.skeleton.serialize());
  102336. }
  102337. //serialize the actual mesh
  102338. serializationObject.meshes = serializationObject.meshes || [];
  102339. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102340. }
  102341. };
  102342. var SceneSerializer = /** @class */ (function () {
  102343. function SceneSerializer() {
  102344. }
  102345. SceneSerializer.ClearCache = function () {
  102346. serializedGeometries = [];
  102347. };
  102348. SceneSerializer.Serialize = function (scene) {
  102349. var serializationObject = {};
  102350. SceneSerializer.ClearCache();
  102351. // Scene
  102352. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  102353. serializationObject.autoClear = scene.autoClear;
  102354. serializationObject.clearColor = scene.clearColor.asArray();
  102355. serializationObject.ambientColor = scene.ambientColor.asArray();
  102356. serializationObject.gravity = scene.gravity.asArray();
  102357. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  102358. serializationObject.workerCollisions = scene.workerCollisions;
  102359. // Fog
  102360. if (scene.fogMode && scene.fogMode !== 0) {
  102361. serializationObject.fogMode = scene.fogMode;
  102362. serializationObject.fogColor = scene.fogColor.asArray();
  102363. serializationObject.fogStart = scene.fogStart;
  102364. serializationObject.fogEnd = scene.fogEnd;
  102365. serializationObject.fogDensity = scene.fogDensity;
  102366. }
  102367. //Physics
  102368. if (scene.isPhysicsEnabled()) {
  102369. var physicEngine = scene.getPhysicsEngine();
  102370. if (physicEngine) {
  102371. serializationObject.physicsEnabled = true;
  102372. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  102373. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  102374. }
  102375. }
  102376. // Metadata
  102377. if (scene.metadata) {
  102378. serializationObject.metadata = scene.metadata;
  102379. }
  102380. // Morph targets
  102381. serializationObject.morphTargetManagers = [];
  102382. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  102383. var abstractMesh = _a[_i];
  102384. var manager = abstractMesh.morphTargetManager;
  102385. if (manager) {
  102386. serializationObject.morphTargetManagers.push(manager.serialize());
  102387. }
  102388. }
  102389. // Lights
  102390. serializationObject.lights = [];
  102391. var index;
  102392. var light;
  102393. for (index = 0; index < scene.lights.length; index++) {
  102394. light = scene.lights[index];
  102395. if (!light.doNotSerialize) {
  102396. serializationObject.lights.push(light.serialize());
  102397. }
  102398. }
  102399. // Cameras
  102400. serializationObject.cameras = [];
  102401. for (index = 0; index < scene.cameras.length; index++) {
  102402. var camera = scene.cameras[index];
  102403. if (!camera.doNotSerialize) {
  102404. serializationObject.cameras.push(camera.serialize());
  102405. }
  102406. }
  102407. if (scene.activeCamera) {
  102408. serializationObject.activeCameraID = scene.activeCamera.id;
  102409. }
  102410. // Animations
  102411. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  102412. // Materials
  102413. serializationObject.materials = [];
  102414. serializationObject.multiMaterials = [];
  102415. var material;
  102416. for (index = 0; index < scene.materials.length; index++) {
  102417. material = scene.materials[index];
  102418. if (!material.doNotSerialize) {
  102419. serializationObject.materials.push(material.serialize());
  102420. }
  102421. }
  102422. // MultiMaterials
  102423. serializationObject.multiMaterials = [];
  102424. for (index = 0; index < scene.multiMaterials.length; index++) {
  102425. var multiMaterial = scene.multiMaterials[index];
  102426. serializationObject.multiMaterials.push(multiMaterial.serialize());
  102427. }
  102428. // Environment texture
  102429. if (scene.environmentTexture) {
  102430. serializationObject.environmentTexture = scene.environmentTexture.name;
  102431. }
  102432. // Skeletons
  102433. serializationObject.skeletons = [];
  102434. for (index = 0; index < scene.skeletons.length; index++) {
  102435. var skeleton = scene.skeletons[index];
  102436. if (!skeleton.doNotSerialize) {
  102437. serializationObject.skeletons.push(skeleton.serialize());
  102438. }
  102439. }
  102440. // Transform nodes
  102441. serializationObject.transformNodes = [];
  102442. for (index = 0; index < scene.transformNodes.length; index++) {
  102443. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  102444. }
  102445. // Geometries
  102446. serializationObject.geometries = {};
  102447. serializationObject.geometries.boxes = [];
  102448. serializationObject.geometries.spheres = [];
  102449. serializationObject.geometries.cylinders = [];
  102450. serializationObject.geometries.toruses = [];
  102451. serializationObject.geometries.grounds = [];
  102452. serializationObject.geometries.planes = [];
  102453. serializationObject.geometries.torusKnots = [];
  102454. serializationObject.geometries.vertexData = [];
  102455. serializedGeometries = [];
  102456. var geometries = scene.getGeometries();
  102457. for (index = 0; index < geometries.length; index++) {
  102458. var geometry = geometries[index];
  102459. if (geometry.isReady()) {
  102460. serializeGeometry(geometry, serializationObject.geometries);
  102461. }
  102462. }
  102463. // Meshes
  102464. serializationObject.meshes = [];
  102465. for (index = 0; index < scene.meshes.length; index++) {
  102466. var abstractMesh = scene.meshes[index];
  102467. if (abstractMesh instanceof BABYLON.Mesh) {
  102468. var mesh = abstractMesh;
  102469. if (!mesh.doNotSerialize) {
  102470. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102471. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102472. }
  102473. }
  102474. }
  102475. }
  102476. // Particles Systems
  102477. serializationObject.particleSystems = [];
  102478. for (index = 0; index < scene.particleSystems.length; index++) {
  102479. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  102480. }
  102481. // Shadows
  102482. serializationObject.shadowGenerators = [];
  102483. for (index = 0; index < scene.lights.length; index++) {
  102484. light = scene.lights[index];
  102485. var shadowGenerator = light.getShadowGenerator();
  102486. if (shadowGenerator) {
  102487. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  102488. }
  102489. }
  102490. // Action Manager
  102491. if (scene.actionManager) {
  102492. serializationObject.actions = scene.actionManager.serialize("scene");
  102493. }
  102494. // Audio
  102495. serializationObject.sounds = [];
  102496. for (index = 0; index < scene.soundTracks.length; index++) {
  102497. var soundtrack = scene.soundTracks[index];
  102498. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  102499. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  102500. }
  102501. }
  102502. // Components
  102503. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  102504. var component = _c[_b];
  102505. component.serialize(serializationObject);
  102506. }
  102507. return serializationObject;
  102508. };
  102509. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  102510. if (withParents === void 0) { withParents = false; }
  102511. if (withChildren === void 0) { withChildren = false; }
  102512. var serializationObject = {};
  102513. SceneSerializer.ClearCache();
  102514. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  102515. if (withParents || withChildren) {
  102516. //deliberate for loop! not for each, appended should be processed as well.
  102517. for (var i = 0; i < toSerialize.length; ++i) {
  102518. if (withChildren) {
  102519. toSerialize[i].getDescendants().forEach(function (node) {
  102520. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  102521. toSerialize.push(node);
  102522. }
  102523. });
  102524. }
  102525. //make sure the array doesn't contain the object already
  102526. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  102527. toSerialize.push(toSerialize[i].parent);
  102528. }
  102529. }
  102530. }
  102531. toSerialize.forEach(function (mesh) {
  102532. finalizeSingleMesh(mesh, serializationObject);
  102533. });
  102534. return serializationObject;
  102535. };
  102536. return SceneSerializer;
  102537. }());
  102538. BABYLON.SceneSerializer = SceneSerializer;
  102539. })(BABYLON || (BABYLON = {}));
  102540. //# sourceMappingURL=babylon.sceneSerializer.js.map
  102541. var BABYLON;
  102542. (function (BABYLON) {
  102543. /**
  102544. * Class used to generate realtime reflection / refraction cube textures
  102545. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  102546. */
  102547. var ReflectionProbe = /** @class */ (function () {
  102548. /**
  102549. * Creates a new reflection probe
  102550. * @param name defines the name of the probe
  102551. * @param size defines the texture resolution (for each face)
  102552. * @param scene defines the hosting scene
  102553. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  102554. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  102555. */
  102556. function ReflectionProbe(
  102557. /** defines the name of the probe */
  102558. name, size, scene, generateMipMaps, useFloat) {
  102559. if (generateMipMaps === void 0) { generateMipMaps = true; }
  102560. if (useFloat === void 0) { useFloat = false; }
  102561. var _this = this;
  102562. this.name = name;
  102563. this._viewMatrix = BABYLON.Matrix.Identity();
  102564. this._target = BABYLON.Vector3.Zero();
  102565. this._add = BABYLON.Vector3.Zero();
  102566. this._invertYAxis = false;
  102567. /** Gets or sets probe position (center of the cube map) */
  102568. this.position = BABYLON.Vector3.Zero();
  102569. this._scene = scene;
  102570. this._scene.reflectionProbes.push(this);
  102571. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  102572. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  102573. switch (faceIndex) {
  102574. case 0:
  102575. _this._add.copyFromFloats(1, 0, 0);
  102576. break;
  102577. case 1:
  102578. _this._add.copyFromFloats(-1, 0, 0);
  102579. break;
  102580. case 2:
  102581. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  102582. break;
  102583. case 3:
  102584. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  102585. break;
  102586. case 4:
  102587. _this._add.copyFromFloats(0, 0, 1);
  102588. break;
  102589. case 5:
  102590. _this._add.copyFromFloats(0, 0, -1);
  102591. break;
  102592. }
  102593. if (_this._attachedMesh) {
  102594. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  102595. }
  102596. _this.position.addToRef(_this._add, _this._target);
  102597. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  102598. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  102599. scene._forcedViewPosition = _this.position;
  102600. });
  102601. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  102602. scene._forcedViewPosition = null;
  102603. scene.updateTransformMatrix(true);
  102604. });
  102605. if (scene.activeCamera) {
  102606. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  102607. }
  102608. }
  102609. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  102610. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  102611. get: function () {
  102612. return this._renderTargetTexture.samples;
  102613. },
  102614. set: function (value) {
  102615. this._renderTargetTexture.samples = value;
  102616. },
  102617. enumerable: true,
  102618. configurable: true
  102619. });
  102620. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  102621. /** Gets or sets the refresh rate to use (on every frame by default) */
  102622. get: function () {
  102623. return this._renderTargetTexture.refreshRate;
  102624. },
  102625. set: function (value) {
  102626. this._renderTargetTexture.refreshRate = value;
  102627. },
  102628. enumerable: true,
  102629. configurable: true
  102630. });
  102631. /**
  102632. * Gets the hosting scene
  102633. * @returns a Scene
  102634. */
  102635. ReflectionProbe.prototype.getScene = function () {
  102636. return this._scene;
  102637. };
  102638. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  102639. /** Gets the internal CubeTexture used to render to */
  102640. get: function () {
  102641. return this._renderTargetTexture;
  102642. },
  102643. enumerable: true,
  102644. configurable: true
  102645. });
  102646. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  102647. /** Gets the list of meshes to render */
  102648. get: function () {
  102649. return this._renderTargetTexture.renderList;
  102650. },
  102651. enumerable: true,
  102652. configurable: true
  102653. });
  102654. /**
  102655. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  102656. * @param mesh defines the mesh to attach to
  102657. */
  102658. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  102659. this._attachedMesh = mesh;
  102660. };
  102661. /**
  102662. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  102663. * @param renderingGroupId The rendering group id corresponding to its index
  102664. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  102665. */
  102666. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  102667. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  102668. };
  102669. /**
  102670. * Clean all associated resources
  102671. */
  102672. ReflectionProbe.prototype.dispose = function () {
  102673. var index = this._scene.reflectionProbes.indexOf(this);
  102674. if (index !== -1) {
  102675. // Remove from the scene if found
  102676. this._scene.reflectionProbes.splice(index, 1);
  102677. }
  102678. if (this._renderTargetTexture) {
  102679. this._renderTargetTexture.dispose();
  102680. this._renderTargetTexture = null;
  102681. }
  102682. };
  102683. return ReflectionProbe;
  102684. }());
  102685. BABYLON.ReflectionProbe = ReflectionProbe;
  102686. })(BABYLON || (BABYLON = {}));
  102687. //# sourceMappingURL=babylon.reflectionProbe.js.map
  102688. var BABYLON;
  102689. (function (BABYLON) {
  102690. /**
  102691. * Defines the layer scene component responsible to manage any layers
  102692. * in a given scene.
  102693. */
  102694. var LayerSceneComponent = /** @class */ (function () {
  102695. /**
  102696. * Creates a new instance of the component for the given scene
  102697. * @param scene Defines the scene to register the component in
  102698. */
  102699. function LayerSceneComponent(scene) {
  102700. /**
  102701. * The component name helpfull to identify the component in the list of scene components.
  102702. */
  102703. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  102704. this.scene = scene;
  102705. this._engine = scene.getEngine();
  102706. scene.layers = new Array();
  102707. }
  102708. /**
  102709. * Registers the component in a given scene
  102710. */
  102711. LayerSceneComponent.prototype.register = function () {
  102712. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  102713. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  102714. };
  102715. /**
  102716. * Rebuilds the elements related to this component in case of
  102717. * context lost for instance.
  102718. */
  102719. LayerSceneComponent.prototype.rebuild = function () {
  102720. var layers = this.scene.layers;
  102721. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102722. var layer = layers_1[_i];
  102723. layer._rebuild();
  102724. }
  102725. };
  102726. /**
  102727. * Disposes the component and the associated ressources.
  102728. */
  102729. LayerSceneComponent.prototype.dispose = function () {
  102730. var layers = this.scene.layers;
  102731. while (layers.length) {
  102732. layers[0].dispose();
  102733. }
  102734. };
  102735. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  102736. var layers = this.scene.layers;
  102737. if (layers.length) {
  102738. this._engine.setDepthBuffer(false);
  102739. var cameraLayerMask = camera.layerMask;
  102740. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102741. var layer = layers_2[_i];
  102742. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  102743. layer.render();
  102744. }
  102745. }
  102746. this._engine.setDepthBuffer(true);
  102747. }
  102748. };
  102749. LayerSceneComponent.prototype._drawBackground = function (camera) {
  102750. this._draw(camera, true);
  102751. };
  102752. LayerSceneComponent.prototype._drawForeground = function (camera) {
  102753. this._draw(camera, false);
  102754. };
  102755. return LayerSceneComponent;
  102756. }());
  102757. BABYLON.LayerSceneComponent = LayerSceneComponent;
  102758. })(BABYLON || (BABYLON = {}));
  102759. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  102760. var BABYLON;
  102761. (function (BABYLON) {
  102762. var Layer = /** @class */ (function () {
  102763. function Layer(name, imgUrl, scene, isBackground, color) {
  102764. this.name = name;
  102765. this.scale = new BABYLON.Vector2(1, 1);
  102766. this.offset = new BABYLON.Vector2(0, 0);
  102767. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  102768. this.layerMask = 0x0FFFFFFF;
  102769. this._vertexBuffers = {};
  102770. // Events
  102771. /**
  102772. * An event triggered when the layer is disposed.
  102773. */
  102774. this.onDisposeObservable = new BABYLON.Observable();
  102775. /**
  102776. * An event triggered before rendering the scene
  102777. */
  102778. this.onBeforeRenderObservable = new BABYLON.Observable();
  102779. /**
  102780. * An event triggered after rendering the scene
  102781. */
  102782. this.onAfterRenderObservable = new BABYLON.Observable();
  102783. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  102784. this.isBackground = isBackground === undefined ? true : isBackground;
  102785. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  102786. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  102787. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  102788. if (!layerComponent) {
  102789. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  102790. this._scene._addComponent(layerComponent);
  102791. }
  102792. this._scene.layers.push(this);
  102793. var engine = this._scene.getEngine();
  102794. // VBO
  102795. var vertices = [];
  102796. vertices.push(1, 1);
  102797. vertices.push(-1, 1);
  102798. vertices.push(-1, -1);
  102799. vertices.push(1, -1);
  102800. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102802. this._createIndexBuffer();
  102803. // Effects
  102804. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  102805. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  102806. }
  102807. Object.defineProperty(Layer.prototype, "onDispose", {
  102808. set: function (callback) {
  102809. if (this._onDisposeObserver) {
  102810. this.onDisposeObservable.remove(this._onDisposeObserver);
  102811. }
  102812. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102813. },
  102814. enumerable: true,
  102815. configurable: true
  102816. });
  102817. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  102818. set: function (callback) {
  102819. if (this._onBeforeRenderObserver) {
  102820. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  102821. }
  102822. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  102823. },
  102824. enumerable: true,
  102825. configurable: true
  102826. });
  102827. Object.defineProperty(Layer.prototype, "onAfterRender", {
  102828. set: function (callback) {
  102829. if (this._onAfterRenderObserver) {
  102830. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102831. }
  102832. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  102833. },
  102834. enumerable: true,
  102835. configurable: true
  102836. });
  102837. Layer.prototype._createIndexBuffer = function () {
  102838. var engine = this._scene.getEngine();
  102839. // Indices
  102840. var indices = [];
  102841. indices.push(0);
  102842. indices.push(1);
  102843. indices.push(2);
  102844. indices.push(0);
  102845. indices.push(2);
  102846. indices.push(3);
  102847. this._indexBuffer = engine.createIndexBuffer(indices);
  102848. };
  102849. /** @hidden */
  102850. Layer.prototype._rebuild = function () {
  102851. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102852. if (vb) {
  102853. vb._rebuild();
  102854. }
  102855. this._createIndexBuffer();
  102856. };
  102857. Layer.prototype.render = function () {
  102858. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  102859. // Check
  102860. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  102861. return;
  102862. var engine = this._scene.getEngine();
  102863. this.onBeforeRenderObservable.notifyObservers(this);
  102864. // Render
  102865. engine.enableEffect(currentEffect);
  102866. engine.setState(false);
  102867. // Texture
  102868. currentEffect.setTexture("textureSampler", this.texture);
  102869. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  102870. // Color
  102871. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  102872. // Scale / offset
  102873. currentEffect.setVector2("offset", this.offset);
  102874. currentEffect.setVector2("scale", this.scale);
  102875. // VBOs
  102876. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102877. // Draw order
  102878. if (!this.alphaTest) {
  102879. engine.setAlphaMode(this.alphaBlendingMode);
  102880. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102881. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  102882. }
  102883. else {
  102884. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102885. }
  102886. this.onAfterRenderObservable.notifyObservers(this);
  102887. };
  102888. Layer.prototype.dispose = function () {
  102889. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102890. if (vertexBuffer) {
  102891. vertexBuffer.dispose();
  102892. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102893. }
  102894. if (this._indexBuffer) {
  102895. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102896. this._indexBuffer = null;
  102897. }
  102898. if (this.texture) {
  102899. this.texture.dispose();
  102900. this.texture = null;
  102901. }
  102902. // Remove from scene
  102903. var index = this._scene.layers.indexOf(this);
  102904. this._scene.layers.splice(index, 1);
  102905. // Callback
  102906. this.onDisposeObservable.notifyObservers(this);
  102907. this.onDisposeObservable.clear();
  102908. this.onAfterRenderObservable.clear();
  102909. this.onBeforeRenderObservable.clear();
  102910. };
  102911. return Layer;
  102912. }());
  102913. BABYLON.Layer = Layer;
  102914. })(BABYLON || (BABYLON = {}));
  102915. //# sourceMappingURL=babylon.layer.js.map
  102916. var BABYLON;
  102917. (function (BABYLON) {
  102918. var TextureTools = /** @class */ (function () {
  102919. function TextureTools() {
  102920. }
  102921. /**
  102922. * Uses the GPU to create a copy texture rescaled at a given size
  102923. * @param texture Texture to copy from
  102924. * @param width Desired width
  102925. * @param height Desired height
  102926. * @return Generated texture
  102927. */
  102928. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  102929. if (useBilinearMode === void 0) { useBilinearMode = true; }
  102930. var scene = texture.getScene();
  102931. var engine = scene.getEngine();
  102932. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  102933. rtt.wrapU = texture.wrapU;
  102934. rtt.wrapV = texture.wrapV;
  102935. rtt.uOffset = texture.uOffset;
  102936. rtt.vOffset = texture.vOffset;
  102937. rtt.uScale = texture.uScale;
  102938. rtt.vScale = texture.vScale;
  102939. rtt.uAng = texture.uAng;
  102940. rtt.vAng = texture.vAng;
  102941. rtt.wAng = texture.wAng;
  102942. rtt.coordinatesIndex = texture.coordinatesIndex;
  102943. rtt.level = texture.level;
  102944. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  102945. rtt._texture.isReady = false;
  102946. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102947. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102948. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102949. passPostProcess.getEffect().executeWhenCompiled(function () {
  102950. passPostProcess.onApply = function (effect) {
  102951. effect.setTexture("textureSampler", texture);
  102952. };
  102953. var internalTexture = rtt.getInternalTexture();
  102954. if (internalTexture) {
  102955. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  102956. engine.unBindFramebuffer(internalTexture);
  102957. rtt.disposeFramebufferObjects();
  102958. passPostProcess.dispose();
  102959. internalTexture.isReady = true;
  102960. }
  102961. });
  102962. return rtt;
  102963. };
  102964. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  102965. if (!scene._environmentBRDFTexture) {
  102966. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102967. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102968. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102969. scene._environmentBRDFTexture = texture;
  102970. }
  102971. return scene._environmentBRDFTexture;
  102972. };
  102973. 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=";
  102974. return TextureTools;
  102975. }());
  102976. BABYLON.TextureTools = TextureTools;
  102977. })(BABYLON || (BABYLON = {}));
  102978. //# sourceMappingURL=babylon.textureTools.js.map
  102979. var BABYLON;
  102980. (function (BABYLON) {
  102981. var FramingBehavior = /** @class */ (function () {
  102982. function FramingBehavior() {
  102983. this._mode = FramingBehavior.FitFrustumSidesMode;
  102984. this._radiusScale = 1.0;
  102985. this._positionScale = 0.5;
  102986. this._defaultElevation = 0.3;
  102987. this._elevationReturnTime = 1500;
  102988. this._elevationReturnWaitTime = 1000;
  102989. this._zoomStopsAnimation = false;
  102990. this._framingTime = 1500;
  102991. this._isPointerDown = false;
  102992. this._lastInteractionTime = -Infinity;
  102993. // Framing control
  102994. this._animatables = new Array();
  102995. this._betaIsAnimating = false;
  102996. }
  102997. Object.defineProperty(FramingBehavior.prototype, "name", {
  102998. get: function () {
  102999. return "Framing";
  103000. },
  103001. enumerable: true,
  103002. configurable: true
  103003. });
  103004. Object.defineProperty(FramingBehavior.prototype, "mode", {
  103005. /**
  103006. * Gets current mode used by the behavior.
  103007. */
  103008. get: function () {
  103009. return this._mode;
  103010. },
  103011. /**
  103012. * Sets the current mode used by the behavior
  103013. */
  103014. set: function (mode) {
  103015. this._mode = mode;
  103016. },
  103017. enumerable: true,
  103018. configurable: true
  103019. });
  103020. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  103021. /**
  103022. * Gets the scale applied to the radius
  103023. */
  103024. get: function () {
  103025. return this._radiusScale;
  103026. },
  103027. /**
  103028. * Sets the scale applied to the radius (1 by default)
  103029. */
  103030. set: function (radius) {
  103031. this._radiusScale = radius;
  103032. },
  103033. enumerable: true,
  103034. configurable: true
  103035. });
  103036. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  103037. /**
  103038. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103039. */
  103040. get: function () {
  103041. return this._positionScale;
  103042. },
  103043. /**
  103044. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103045. */
  103046. set: function (scale) {
  103047. this._positionScale = scale;
  103048. },
  103049. enumerable: true,
  103050. configurable: true
  103051. });
  103052. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  103053. /**
  103054. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103055. * behaviour is triggered, in radians.
  103056. */
  103057. get: function () {
  103058. return this._defaultElevation;
  103059. },
  103060. /**
  103061. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103062. * behaviour is triggered, in radians.
  103063. */
  103064. set: function (elevation) {
  103065. this._defaultElevation = elevation;
  103066. },
  103067. enumerable: true,
  103068. configurable: true
  103069. });
  103070. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  103071. /**
  103072. * Gets the time (in milliseconds) taken to return to the default beta position.
  103073. * Negative value indicates camera should not return to default.
  103074. */
  103075. get: function () {
  103076. return this._elevationReturnTime;
  103077. },
  103078. /**
  103079. * Sets the time (in milliseconds) taken to return to the default beta position.
  103080. * Negative value indicates camera should not return to default.
  103081. */
  103082. set: function (speed) {
  103083. this._elevationReturnTime = speed;
  103084. },
  103085. enumerable: true,
  103086. configurable: true
  103087. });
  103088. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  103089. /**
  103090. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103091. */
  103092. get: function () {
  103093. return this._elevationReturnWaitTime;
  103094. },
  103095. /**
  103096. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103097. */
  103098. set: function (time) {
  103099. this._elevationReturnWaitTime = time;
  103100. },
  103101. enumerable: true,
  103102. configurable: true
  103103. });
  103104. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  103105. /**
  103106. * Gets the flag that indicates if user zooming should stop animation.
  103107. */
  103108. get: function () {
  103109. return this._zoomStopsAnimation;
  103110. },
  103111. /**
  103112. * Sets the flag that indicates if user zooming should stop animation.
  103113. */
  103114. set: function (flag) {
  103115. this._zoomStopsAnimation = flag;
  103116. },
  103117. enumerable: true,
  103118. configurable: true
  103119. });
  103120. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  103121. /**
  103122. * Gets the transition time when framing the mesh, in milliseconds
  103123. */
  103124. get: function () {
  103125. return this._framingTime;
  103126. },
  103127. /**
  103128. * Sets the transition time when framing the mesh, in milliseconds
  103129. */
  103130. set: function (time) {
  103131. this._framingTime = time;
  103132. },
  103133. enumerable: true,
  103134. configurable: true
  103135. });
  103136. FramingBehavior.prototype.init = function () {
  103137. // Do notihng
  103138. };
  103139. FramingBehavior.prototype.attach = function (camera) {
  103140. var _this = this;
  103141. this._attachedCamera = camera;
  103142. var scene = this._attachedCamera.getScene();
  103143. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  103144. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103145. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103146. _this._isPointerDown = true;
  103147. return;
  103148. }
  103149. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103150. _this._isPointerDown = false;
  103151. }
  103152. });
  103153. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103154. if (mesh) {
  103155. _this.zoomOnMesh(mesh);
  103156. }
  103157. });
  103158. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103159. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103160. _this._applyUserInteraction();
  103161. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  103162. // back to the default position after a given timeout
  103163. _this._maintainCameraAboveGround();
  103164. });
  103165. };
  103166. FramingBehavior.prototype.detach = function () {
  103167. if (!this._attachedCamera) {
  103168. return;
  103169. }
  103170. var scene = this._attachedCamera.getScene();
  103171. if (this._onPrePointerObservableObserver) {
  103172. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103173. }
  103174. if (this._onAfterCheckInputsObserver) {
  103175. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103176. }
  103177. if (this._onMeshTargetChangedObserver) {
  103178. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103179. }
  103180. this._attachedCamera = null;
  103181. };
  103182. /**
  103183. * Targets the given mesh and updates zoom level accordingly.
  103184. * @param mesh The mesh to target.
  103185. * @param radius Optional. If a cached radius position already exists, overrides default.
  103186. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103187. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103188. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103189. */
  103190. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103191. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103192. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103193. mesh.computeWorldMatrix(true);
  103194. var boundingBox = mesh.getBoundingInfo().boundingBox;
  103195. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  103196. };
  103197. /**
  103198. * Targets the given mesh with its children and updates zoom level accordingly.
  103199. * @param mesh The mesh to target.
  103200. * @param radius Optional. If a cached radius position already exists, overrides default.
  103201. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103202. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103203. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103204. */
  103205. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103206. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103207. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103208. mesh.computeWorldMatrix(true);
  103209. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  103210. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  103211. };
  103212. /**
  103213. * Targets the given meshes with their children and updates zoom level accordingly.
  103214. * @param meshes The mesh to target.
  103215. * @param radius Optional. If a cached radius position already exists, overrides default.
  103216. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103217. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103218. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103219. */
  103220. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  103221. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103222. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103223. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  103224. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  103225. for (var i = 0; i < meshes.length; i++) {
  103226. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  103227. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  103228. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  103229. }
  103230. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  103231. };
  103232. /**
  103233. * Targets the given mesh and updates zoom level accordingly.
  103234. * @param mesh The mesh to target.
  103235. * @param radius Optional. If a cached radius position already exists, overrides default.
  103236. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103237. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103238. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103239. */
  103240. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  103241. var _this = this;
  103242. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103243. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103244. var zoomTarget;
  103245. if (!this._attachedCamera) {
  103246. return;
  103247. }
  103248. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  103249. var bottom = minimumWorld.y;
  103250. var top = maximumWorld.y;
  103251. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  103252. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  103253. if (focusOnOriginXZ) {
  103254. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  103255. }
  103256. else {
  103257. var centerWorld = minimumWorld.add(radiusWorld);
  103258. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  103259. }
  103260. if (!this._vectorTransition) {
  103261. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  103262. }
  103263. this._betaIsAnimating = true;
  103264. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  103265. if (animatable) {
  103266. this._animatables.push(animatable);
  103267. }
  103268. // sets the radius and lower radius bounds
  103269. // Small delta ensures camera is not always at lower zoom limit.
  103270. var radius = 0;
  103271. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  103272. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103273. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  103274. radius = position;
  103275. }
  103276. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103277. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103278. if (this._attachedCamera.lowerRadiusLimit === null) {
  103279. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  103280. }
  103281. }
  103282. // Set sensibilities
  103283. var extend = maximumWorld.subtract(minimumWorld).length();
  103284. this._attachedCamera.panningSensibility = 5000 / extend;
  103285. this._attachedCamera.wheelPrecision = 100 / radius;
  103286. // transition to new radius
  103287. if (!this._radiusTransition) {
  103288. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103289. }
  103290. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  103291. _this.stopAllAnimations();
  103292. if (onAnimationEnd) {
  103293. onAnimationEnd();
  103294. }
  103295. if (_this._attachedCamera) {
  103296. _this._attachedCamera.storeState();
  103297. }
  103298. });
  103299. if (animatable) {
  103300. this._animatables.push(animatable);
  103301. }
  103302. };
  103303. /**
  103304. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  103305. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  103306. * frustum width.
  103307. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  103308. * to fully enclose the mesh in the viewing frustum.
  103309. */
  103310. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  103311. var size = maximumWorld.subtract(minimumWorld);
  103312. var boxVectorGlobalDiagonal = size.length();
  103313. var frustumSlope = this._getFrustumSlope();
  103314. // Formula for setting distance
  103315. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  103316. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  103317. // Horizon distance
  103318. var radius = radiusWithoutFraming * this._radiusScale;
  103319. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  103320. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  103321. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  103322. var camera = this._attachedCamera;
  103323. if (!camera) {
  103324. return 0;
  103325. }
  103326. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103327. // Don't exceed the requested limit
  103328. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  103329. }
  103330. // Don't exceed the upper radius limit
  103331. if (camera.upperRadiusLimit) {
  103332. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  103333. }
  103334. return distance;
  103335. };
  103336. /**
  103337. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  103338. * is automatically returned to its default position (expected to be above ground plane).
  103339. */
  103340. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  103341. var _this = this;
  103342. if (this._elevationReturnTime < 0) {
  103343. return;
  103344. }
  103345. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  103346. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  103347. var limitBeta = Math.PI * 0.5;
  103348. // Bring the camera back up if below the ground plane
  103349. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  103350. this._betaIsAnimating = true;
  103351. //Transition to new position
  103352. this.stopAllAnimations();
  103353. if (!this._betaTransition) {
  103354. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103355. }
  103356. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  103357. _this._clearAnimationLocks();
  103358. _this.stopAllAnimations();
  103359. });
  103360. if (animatabe) {
  103361. this._animatables.push(animatabe);
  103362. }
  103363. }
  103364. };
  103365. /**
  103366. * Returns the frustum slope based on the canvas ratio and camera FOV
  103367. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  103368. */
  103369. FramingBehavior.prototype._getFrustumSlope = function () {
  103370. // Calculate the viewport ratio
  103371. // Aspect Ratio is Height/Width.
  103372. var camera = this._attachedCamera;
  103373. if (!camera) {
  103374. return BABYLON.Vector2.Zero();
  103375. }
  103376. var engine = camera.getScene().getEngine();
  103377. var aspectRatio = engine.getAspectRatio(camera);
  103378. // Camera FOV is the vertical field of view (top-bottom) in radians.
  103379. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  103380. var frustumSlopeY = Math.tan(camera.fov / 2);
  103381. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  103382. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  103383. // along the forward vector.
  103384. var frustumSlopeX = frustumSlopeY * aspectRatio;
  103385. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  103386. };
  103387. /**
  103388. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  103389. */
  103390. FramingBehavior.prototype._clearAnimationLocks = function () {
  103391. this._betaIsAnimating = false;
  103392. };
  103393. /**
  103394. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103395. */
  103396. FramingBehavior.prototype._applyUserInteraction = function () {
  103397. if (this.isUserIsMoving) {
  103398. this._lastInteractionTime = BABYLON.Tools.Now;
  103399. this.stopAllAnimations();
  103400. this._clearAnimationLocks();
  103401. }
  103402. };
  103403. /**
  103404. * Stops and removes all animations that have been applied to the camera
  103405. */
  103406. FramingBehavior.prototype.stopAllAnimations = function () {
  103407. if (this._attachedCamera) {
  103408. this._attachedCamera.animations = [];
  103409. }
  103410. while (this._animatables.length) {
  103411. if (this._animatables[0]) {
  103412. this._animatables[0].onAnimationEnd = null;
  103413. this._animatables[0].stop();
  103414. }
  103415. this._animatables.shift();
  103416. }
  103417. };
  103418. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  103419. /**
  103420. * Gets a value indicating if the user is moving the camera
  103421. */
  103422. get: function () {
  103423. if (!this._attachedCamera) {
  103424. return false;
  103425. }
  103426. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103427. this._attachedCamera.inertialBetaOffset !== 0 ||
  103428. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103429. this._attachedCamera.inertialPanningX !== 0 ||
  103430. this._attachedCamera.inertialPanningY !== 0 ||
  103431. this._isPointerDown;
  103432. },
  103433. enumerable: true,
  103434. configurable: true
  103435. });
  103436. /**
  103437. * The easing function used by animations
  103438. */
  103439. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  103440. /**
  103441. * The easing mode used by animations
  103442. */
  103443. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  103444. // Statics
  103445. /**
  103446. * The camera can move all the way towards the mesh.
  103447. */
  103448. FramingBehavior.IgnoreBoundsSizeMode = 0;
  103449. /**
  103450. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  103451. */
  103452. FramingBehavior.FitFrustumSidesMode = 1;
  103453. return FramingBehavior;
  103454. }());
  103455. BABYLON.FramingBehavior = FramingBehavior;
  103456. })(BABYLON || (BABYLON = {}));
  103457. //# sourceMappingURL=babylon.framingBehavior.js.map
  103458. var BABYLON;
  103459. (function (BABYLON) {
  103460. /**
  103461. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  103462. */
  103463. var BouncingBehavior = /** @class */ (function () {
  103464. function BouncingBehavior() {
  103465. /**
  103466. * The duration of the animation, in milliseconds
  103467. */
  103468. this.transitionDuration = 450;
  103469. /**
  103470. * Length of the distance animated by the transition when lower radius is reached
  103471. */
  103472. this.lowerRadiusTransitionRange = 2;
  103473. /**
  103474. * Length of the distance animated by the transition when upper radius is reached
  103475. */
  103476. this.upperRadiusTransitionRange = -2;
  103477. this._autoTransitionRange = false;
  103478. // Animations
  103479. this._radiusIsAnimating = false;
  103480. this._radiusBounceTransition = null;
  103481. this._animatables = new Array();
  103482. }
  103483. Object.defineProperty(BouncingBehavior.prototype, "name", {
  103484. get: function () {
  103485. return "Bouncing";
  103486. },
  103487. enumerable: true,
  103488. configurable: true
  103489. });
  103490. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  103491. /**
  103492. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103493. */
  103494. get: function () {
  103495. return this._autoTransitionRange;
  103496. },
  103497. /**
  103498. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103499. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  103500. */
  103501. set: function (value) {
  103502. var _this = this;
  103503. if (this._autoTransitionRange === value) {
  103504. return;
  103505. }
  103506. this._autoTransitionRange = value;
  103507. var camera = this._attachedCamera;
  103508. if (!camera) {
  103509. return;
  103510. }
  103511. if (value) {
  103512. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103513. if (!mesh) {
  103514. return;
  103515. }
  103516. mesh.computeWorldMatrix(true);
  103517. var diagonal = mesh.getBoundingInfo().diagonalLength;
  103518. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  103519. _this.upperRadiusTransitionRange = diagonal * 0.05;
  103520. });
  103521. }
  103522. else if (this._onMeshTargetChangedObserver) {
  103523. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103524. }
  103525. },
  103526. enumerable: true,
  103527. configurable: true
  103528. });
  103529. BouncingBehavior.prototype.init = function () {
  103530. // Do notihng
  103531. };
  103532. BouncingBehavior.prototype.attach = function (camera) {
  103533. var _this = this;
  103534. this._attachedCamera = camera;
  103535. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103536. if (!_this._attachedCamera) {
  103537. return;
  103538. }
  103539. // Add the bounce animation to the lower radius limit
  103540. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  103541. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  103542. }
  103543. // Add the bounce animation to the upper radius limit
  103544. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  103545. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  103546. }
  103547. });
  103548. };
  103549. BouncingBehavior.prototype.detach = function () {
  103550. if (!this._attachedCamera) {
  103551. return;
  103552. }
  103553. if (this._onAfterCheckInputsObserver) {
  103554. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103555. }
  103556. if (this._onMeshTargetChangedObserver) {
  103557. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103558. }
  103559. this._attachedCamera = null;
  103560. };
  103561. /**
  103562. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  103563. * @param radiusLimit The limit to check against.
  103564. * @return Bool to indicate if at limit.
  103565. */
  103566. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  103567. if (!this._attachedCamera) {
  103568. return false;
  103569. }
  103570. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  103571. return true;
  103572. }
  103573. return false;
  103574. };
  103575. /**
  103576. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  103577. * @param radiusDelta The delta by which to animate to. Can be negative.
  103578. */
  103579. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  103580. var _this = this;
  103581. if (!this._attachedCamera) {
  103582. return;
  103583. }
  103584. if (!this._radiusBounceTransition) {
  103585. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  103586. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  103587. }
  103588. // Prevent zoom until bounce has completed
  103589. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  103590. this._attachedCamera.wheelPrecision = Infinity;
  103591. this._attachedCamera.inertialRadiusOffset = 0;
  103592. // Animate to the radius limit
  103593. this.stopAllAnimations();
  103594. this._radiusIsAnimating = true;
  103595. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  103596. if (animatable) {
  103597. this._animatables.push(animatable);
  103598. }
  103599. };
  103600. /**
  103601. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  103602. */
  103603. BouncingBehavior.prototype._clearAnimationLocks = function () {
  103604. this._radiusIsAnimating = false;
  103605. if (this._attachedCamera) {
  103606. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  103607. }
  103608. };
  103609. /**
  103610. * Stops and removes all animations that have been applied to the camera
  103611. */
  103612. BouncingBehavior.prototype.stopAllAnimations = function () {
  103613. if (this._attachedCamera) {
  103614. this._attachedCamera.animations = [];
  103615. }
  103616. while (this._animatables.length) {
  103617. this._animatables[0].onAnimationEnd = null;
  103618. this._animatables[0].stop();
  103619. this._animatables.shift();
  103620. }
  103621. };
  103622. /**
  103623. * The easing function used by animations
  103624. */
  103625. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  103626. /**
  103627. * The easing mode used by animations
  103628. */
  103629. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  103630. return BouncingBehavior;
  103631. }());
  103632. BABYLON.BouncingBehavior = BouncingBehavior;
  103633. })(BABYLON || (BABYLON = {}));
  103634. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  103635. var BABYLON;
  103636. (function (BABYLON) {
  103637. var AutoRotationBehavior = /** @class */ (function () {
  103638. function AutoRotationBehavior() {
  103639. this._zoomStopsAnimation = false;
  103640. this._idleRotationSpeed = 0.05;
  103641. this._idleRotationWaitTime = 2000;
  103642. this._idleRotationSpinupTime = 2000;
  103643. this._isPointerDown = false;
  103644. this._lastFrameTime = null;
  103645. this._lastInteractionTime = -Infinity;
  103646. this._cameraRotationSpeed = 0;
  103647. this._lastFrameRadius = 0;
  103648. }
  103649. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  103650. get: function () {
  103651. return "AutoRotation";
  103652. },
  103653. enumerable: true,
  103654. configurable: true
  103655. });
  103656. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  103657. /**
  103658. * Gets the flag that indicates if user zooming should stop animation.
  103659. */
  103660. get: function () {
  103661. return this._zoomStopsAnimation;
  103662. },
  103663. /**
  103664. * Sets the flag that indicates if user zooming should stop animation.
  103665. */
  103666. set: function (flag) {
  103667. this._zoomStopsAnimation = flag;
  103668. },
  103669. enumerable: true,
  103670. configurable: true
  103671. });
  103672. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  103673. /**
  103674. * Gets the default speed at which the camera rotates around the model.
  103675. */
  103676. get: function () {
  103677. return this._idleRotationSpeed;
  103678. },
  103679. /**
  103680. * Sets the default speed at which the camera rotates around the model.
  103681. */
  103682. set: function (speed) {
  103683. this._idleRotationSpeed = speed;
  103684. },
  103685. enumerable: true,
  103686. configurable: true
  103687. });
  103688. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  103689. /**
  103690. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  103691. */
  103692. get: function () {
  103693. return this._idleRotationWaitTime;
  103694. },
  103695. /**
  103696. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  103697. */
  103698. set: function (time) {
  103699. this._idleRotationWaitTime = time;
  103700. },
  103701. enumerable: true,
  103702. configurable: true
  103703. });
  103704. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  103705. /**
  103706. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103707. */
  103708. get: function () {
  103709. return this._idleRotationSpinupTime;
  103710. },
  103711. /**
  103712. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103713. */
  103714. set: function (time) {
  103715. this._idleRotationSpinupTime = time;
  103716. },
  103717. enumerable: true,
  103718. configurable: true
  103719. });
  103720. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  103721. /**
  103722. * Gets a value indicating if the camera is currently rotating because of this behavior
  103723. */
  103724. get: function () {
  103725. return Math.abs(this._cameraRotationSpeed) > 0;
  103726. },
  103727. enumerable: true,
  103728. configurable: true
  103729. });
  103730. AutoRotationBehavior.prototype.init = function () {
  103731. // Do notihng
  103732. };
  103733. AutoRotationBehavior.prototype.attach = function (camera) {
  103734. var _this = this;
  103735. this._attachedCamera = camera;
  103736. var scene = this._attachedCamera.getScene();
  103737. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103738. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103739. _this._isPointerDown = true;
  103740. return;
  103741. }
  103742. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103743. _this._isPointerDown = false;
  103744. }
  103745. });
  103746. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103747. var now = BABYLON.Tools.Now;
  103748. var dt = 0;
  103749. if (_this._lastFrameTime != null) {
  103750. dt = now - _this._lastFrameTime;
  103751. }
  103752. _this._lastFrameTime = now;
  103753. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103754. _this._applyUserInteraction();
  103755. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  103756. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  103757. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  103758. // Step camera rotation by rotation speed
  103759. if (_this._attachedCamera) {
  103760. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  103761. }
  103762. });
  103763. };
  103764. AutoRotationBehavior.prototype.detach = function () {
  103765. if (!this._attachedCamera) {
  103766. return;
  103767. }
  103768. var scene = this._attachedCamera.getScene();
  103769. if (this._onPrePointerObservableObserver) {
  103770. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103771. }
  103772. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103773. this._attachedCamera = null;
  103774. };
  103775. /**
  103776. * Returns true if user is scrolling.
  103777. * @return true if user is scrolling.
  103778. */
  103779. AutoRotationBehavior.prototype._userIsZooming = function () {
  103780. if (!this._attachedCamera) {
  103781. return false;
  103782. }
  103783. return this._attachedCamera.inertialRadiusOffset !== 0;
  103784. };
  103785. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  103786. if (!this._attachedCamera) {
  103787. return false;
  103788. }
  103789. var zoomHasHitLimit = false;
  103790. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  103791. zoomHasHitLimit = true;
  103792. }
  103793. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  103794. this._lastFrameRadius = this._attachedCamera.radius;
  103795. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  103796. };
  103797. /**
  103798. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103799. */
  103800. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  103801. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  103802. this._lastInteractionTime = BABYLON.Tools.Now;
  103803. }
  103804. };
  103805. // Tools
  103806. AutoRotationBehavior.prototype._userIsMoving = function () {
  103807. if (!this._attachedCamera) {
  103808. return false;
  103809. }
  103810. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103811. this._attachedCamera.inertialBetaOffset !== 0 ||
  103812. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103813. this._attachedCamera.inertialPanningX !== 0 ||
  103814. this._attachedCamera.inertialPanningY !== 0 ||
  103815. this._isPointerDown;
  103816. };
  103817. return AutoRotationBehavior;
  103818. }());
  103819. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  103820. })(BABYLON || (BABYLON = {}));
  103821. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  103822. var BABYLON;
  103823. (function (BABYLON) {
  103824. var NullEngineOptions = /** @class */ (function () {
  103825. function NullEngineOptions() {
  103826. this.renderWidth = 512;
  103827. this.renderHeight = 256;
  103828. this.textureSize = 512;
  103829. this.deterministicLockstep = false;
  103830. this.lockstepMaxSteps = 4;
  103831. }
  103832. return NullEngineOptions;
  103833. }());
  103834. BABYLON.NullEngineOptions = NullEngineOptions;
  103835. /**
  103836. * The null engine class provides support for headless version of babylon.js.
  103837. * This can be used in server side scenario or for testing purposes
  103838. */
  103839. var NullEngine = /** @class */ (function (_super) {
  103840. __extends(NullEngine, _super);
  103841. function NullEngine(options) {
  103842. if (options === void 0) { options = new NullEngineOptions(); }
  103843. var _this = _super.call(this, null) || this;
  103844. if (options.deterministicLockstep === undefined) {
  103845. options.deterministicLockstep = false;
  103846. }
  103847. if (options.lockstepMaxSteps === undefined) {
  103848. options.lockstepMaxSteps = 4;
  103849. }
  103850. _this._options = options;
  103851. // Init caps
  103852. // We consider we are on a webgl1 capable device
  103853. _this._caps = new BABYLON.EngineCapabilities();
  103854. _this._caps.maxTexturesImageUnits = 16;
  103855. _this._caps.maxVertexTextureImageUnits = 16;
  103856. _this._caps.maxTextureSize = 512;
  103857. _this._caps.maxCubemapTextureSize = 512;
  103858. _this._caps.maxRenderTextureSize = 512;
  103859. _this._caps.maxVertexAttribs = 16;
  103860. _this._caps.maxVaryingVectors = 16;
  103861. _this._caps.maxFragmentUniformVectors = 16;
  103862. _this._caps.maxVertexUniformVectors = 16;
  103863. // Extensions
  103864. _this._caps.standardDerivatives = false;
  103865. _this._caps.astc = null;
  103866. _this._caps.s3tc = null;
  103867. _this._caps.pvrtc = null;
  103868. _this._caps.etc1 = null;
  103869. _this._caps.etc2 = null;
  103870. _this._caps.textureAnisotropicFilterExtension = null;
  103871. _this._caps.maxAnisotropy = 0;
  103872. _this._caps.uintIndices = false;
  103873. _this._caps.fragmentDepthSupported = false;
  103874. _this._caps.highPrecisionShaderSupported = true;
  103875. _this._caps.colorBufferFloat = false;
  103876. _this._caps.textureFloat = false;
  103877. _this._caps.textureFloatLinearFiltering = false;
  103878. _this._caps.textureFloatRender = false;
  103879. _this._caps.textureHalfFloat = false;
  103880. _this._caps.textureHalfFloatLinearFiltering = false;
  103881. _this._caps.textureHalfFloatRender = false;
  103882. _this._caps.textureLOD = false;
  103883. _this._caps.drawBuffersExtension = false;
  103884. _this._caps.depthTextureExtension = false;
  103885. _this._caps.vertexArrayObject = false;
  103886. _this._caps.instancedArrays = false;
  103887. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  103888. // Wrappers
  103889. if (typeof URL === "undefined") {
  103890. URL = {
  103891. createObjectURL: function () { },
  103892. revokeObjectURL: function () { }
  103893. };
  103894. }
  103895. if (typeof Blob === "undefined") {
  103896. Blob = function () { };
  103897. }
  103898. return _this;
  103899. }
  103900. NullEngine.prototype.isDeterministicLockStep = function () {
  103901. return this._options.deterministicLockstep;
  103902. };
  103903. NullEngine.prototype.getLockstepMaxSteps = function () {
  103904. return this._options.lockstepMaxSteps;
  103905. };
  103906. NullEngine.prototype.getHardwareScalingLevel = function () {
  103907. return 1.0;
  103908. };
  103909. NullEngine.prototype.createVertexBuffer = function (vertices) {
  103910. return {
  103911. capacity: 0,
  103912. references: 1,
  103913. is32Bits: false
  103914. };
  103915. };
  103916. NullEngine.prototype.createIndexBuffer = function (indices) {
  103917. return {
  103918. capacity: 0,
  103919. references: 1,
  103920. is32Bits: false
  103921. };
  103922. };
  103923. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  103924. if (stencil === void 0) { stencil = false; }
  103925. };
  103926. NullEngine.prototype.getRenderWidth = function (useScreen) {
  103927. if (useScreen === void 0) { useScreen = false; }
  103928. if (!useScreen && this._currentRenderTarget) {
  103929. return this._currentRenderTarget.width;
  103930. }
  103931. return this._options.renderWidth;
  103932. };
  103933. NullEngine.prototype.getRenderHeight = function (useScreen) {
  103934. if (useScreen === void 0) { useScreen = false; }
  103935. if (!useScreen && this._currentRenderTarget) {
  103936. return this._currentRenderTarget.height;
  103937. }
  103938. return this._options.renderHeight;
  103939. };
  103940. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  103941. this._cachedViewport = viewport;
  103942. };
  103943. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  103944. return {
  103945. transformFeedback: null,
  103946. __SPECTOR_rebuildProgram: null
  103947. };
  103948. };
  103949. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  103950. return [];
  103951. };
  103952. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  103953. return [];
  103954. };
  103955. NullEngine.prototype.bindSamplers = function (effect) {
  103956. this._currentEffect = null;
  103957. };
  103958. NullEngine.prototype.enableEffect = function (effect) {
  103959. this._currentEffect = effect;
  103960. if (effect.onBind) {
  103961. effect.onBind(effect);
  103962. }
  103963. if (effect._onBindObservable) {
  103964. effect._onBindObservable.notifyObservers(effect);
  103965. }
  103966. };
  103967. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  103968. if (zOffset === void 0) { zOffset = 0; }
  103969. if (reverseSide === void 0) { reverseSide = false; }
  103970. };
  103971. NullEngine.prototype.setIntArray = function (uniform, array) {
  103972. };
  103973. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  103974. };
  103975. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  103976. };
  103977. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  103978. };
  103979. NullEngine.prototype.setFloatArray = function (uniform, array) {
  103980. };
  103981. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  103982. };
  103983. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  103984. };
  103985. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  103986. };
  103987. NullEngine.prototype.setArray = function (uniform, array) {
  103988. };
  103989. NullEngine.prototype.setArray2 = function (uniform, array) {
  103990. };
  103991. NullEngine.prototype.setArray3 = function (uniform, array) {
  103992. };
  103993. NullEngine.prototype.setArray4 = function (uniform, array) {
  103994. };
  103995. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  103996. };
  103997. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  103998. };
  103999. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  104000. };
  104001. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  104002. };
  104003. NullEngine.prototype.setFloat = function (uniform, value) {
  104004. };
  104005. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  104006. };
  104007. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  104008. };
  104009. NullEngine.prototype.setBool = function (uniform, bool) {
  104010. };
  104011. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  104012. };
  104013. NullEngine.prototype.setColor3 = function (uniform, color3) {
  104014. };
  104015. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  104016. };
  104017. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  104018. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  104019. if (this._alphaMode === mode) {
  104020. return;
  104021. }
  104022. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  104023. if (!noDepthWriteChange) {
  104024. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  104025. }
  104026. this._alphaMode = mode;
  104027. };
  104028. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  104029. };
  104030. NullEngine.prototype.wipeCaches = function (bruteForce) {
  104031. if (this.preventCacheWipeBetweenFrames) {
  104032. return;
  104033. }
  104034. this.resetTextureCache();
  104035. this._currentEffect = null;
  104036. if (bruteForce) {
  104037. this._currentProgram = null;
  104038. this._stencilState.reset();
  104039. this._depthCullingState.reset();
  104040. this._alphaState.reset();
  104041. }
  104042. this._cachedVertexBuffers = null;
  104043. this._cachedIndexBuffer = null;
  104044. this._cachedEffectForVertexBuffers = null;
  104045. };
  104046. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  104047. };
  104048. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  104049. };
  104050. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  104051. };
  104052. /** @hidden */
  104053. NullEngine.prototype._createTexture = function () {
  104054. return {};
  104055. };
  104056. /** @hidden */
  104057. NullEngine.prototype._releaseTexture = function (texture) {
  104058. };
  104059. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  104060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104061. if (onLoad === void 0) { onLoad = null; }
  104062. if (onError === void 0) { onError = null; }
  104063. if (buffer === void 0) { buffer = null; }
  104064. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  104065. var url = String(urlArg);
  104066. texture.url = url;
  104067. texture.generateMipMaps = !noMipmap;
  104068. texture.samplingMode = samplingMode;
  104069. texture.invertY = invertY;
  104070. texture.baseWidth = this._options.textureSize;
  104071. texture.baseHeight = this._options.textureSize;
  104072. texture.width = this._options.textureSize;
  104073. texture.height = this._options.textureSize;
  104074. if (format) {
  104075. texture.format = format;
  104076. }
  104077. texture.isReady = true;
  104078. if (onLoad) {
  104079. onLoad();
  104080. }
  104081. this._internalTexturesCache.push(texture);
  104082. return texture;
  104083. };
  104084. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  104085. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  104086. if (options !== undefined && typeof options === "object") {
  104087. fullOptions.generateMipMaps = options.generateMipMaps;
  104088. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  104089. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  104090. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  104091. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  104092. }
  104093. else {
  104094. fullOptions.generateMipMaps = options;
  104095. fullOptions.generateDepthBuffer = true;
  104096. fullOptions.generateStencilBuffer = false;
  104097. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104098. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104099. }
  104100. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  104101. var width = size.width || size;
  104102. var height = size.height || size;
  104103. texture._depthStencilBuffer = {};
  104104. texture._framebuffer = {};
  104105. texture.baseWidth = width;
  104106. texture.baseHeight = height;
  104107. texture.width = width;
  104108. texture.height = height;
  104109. texture.isReady = true;
  104110. texture.samples = 1;
  104111. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  104112. texture.samplingMode = fullOptions.samplingMode;
  104113. texture.type = fullOptions.type;
  104114. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  104115. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  104116. this._internalTexturesCache.push(texture);
  104117. return texture;
  104118. };
  104119. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  104120. texture.samplingMode = samplingMode;
  104121. };
  104122. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  104123. if (this._currentRenderTarget) {
  104124. this.unBindFramebuffer(this._currentRenderTarget);
  104125. }
  104126. this._currentRenderTarget = texture;
  104127. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  104128. if (this._cachedViewport && !forceFullscreenViewport) {
  104129. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  104130. }
  104131. };
  104132. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  104133. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  104134. this._currentRenderTarget = null;
  104135. if (onBeforeUnbind) {
  104136. if (texture._MSAAFramebuffer) {
  104137. this._currentFramebuffer = texture._framebuffer;
  104138. }
  104139. onBeforeUnbind();
  104140. }
  104141. this._currentFramebuffer = null;
  104142. };
  104143. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  104144. var vbo = {
  104145. capacity: 1,
  104146. references: 1,
  104147. is32Bits: false
  104148. };
  104149. return vbo;
  104150. };
  104151. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  104152. if (premulAlpha === void 0) { premulAlpha = false; }
  104153. };
  104154. /**
  104155. * @hidden
  104156. * Get the current error code of the webGL context
  104157. * @returns the error code
  104158. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  104159. */
  104160. NullEngine.prototype.getError = function () {
  104161. return 0;
  104162. };
  104163. /** @hidden */
  104164. NullEngine.prototype._getUnpackAlignement = function () {
  104165. return 1;
  104166. };
  104167. /** @hidden */
  104168. NullEngine.prototype._unpackFlipY = function (value) {
  104169. };
  104170. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  104171. if (offset === void 0) { offset = 0; }
  104172. };
  104173. /**
  104174. * Updates a dynamic vertex buffer.
  104175. * @param vertexBuffer the vertex buffer to update
  104176. * @param data the data used to update the vertex buffer
  104177. * @param byteOffset the byte offset of the data (optional)
  104178. * @param byteLength the byte length of the data (optional)
  104179. */
  104180. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  104181. };
  104182. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  104183. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  104184. this._boundTexturesCache[this._activeChannel] = texture;
  104185. return true;
  104186. }
  104187. return false;
  104188. };
  104189. /** @hidden */
  104190. NullEngine.prototype._bindTexture = function (channel, texture) {
  104191. if (channel < 0) {
  104192. return;
  104193. }
  104194. this._bindTextureDirectly(0, texture);
  104195. };
  104196. /** @hidden */
  104197. NullEngine.prototype._releaseBuffer = function (buffer) {
  104198. buffer.references--;
  104199. if (buffer.references === 0) {
  104200. return true;
  104201. }
  104202. return false;
  104203. };
  104204. NullEngine.prototype.releaseEffects = function () {
  104205. };
  104206. NullEngine.prototype.displayLoadingUI = function () {
  104207. };
  104208. NullEngine.prototype.hideLoadingUI = function () {
  104209. };
  104210. /** @hidden */
  104211. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  104212. if (faceIndex === void 0) { faceIndex = 0; }
  104213. if (lod === void 0) { lod = 0; }
  104214. };
  104215. /** @hidden */
  104216. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  104217. if (faceIndex === void 0) { faceIndex = 0; }
  104218. if (lod === void 0) { lod = 0; }
  104219. };
  104220. /** @hidden */
  104221. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  104222. if (faceIndex === void 0) { faceIndex = 0; }
  104223. if (lod === void 0) { lod = 0; }
  104224. };
  104225. /** @hidden */
  104226. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  104227. if (faceIndex === void 0) { faceIndex = 0; }
  104228. if (lod === void 0) { lod = 0; }
  104229. };
  104230. return NullEngine;
  104231. }(BABYLON.Engine));
  104232. BABYLON.NullEngine = NullEngine;
  104233. })(BABYLON || (BABYLON = {}));
  104234. //# sourceMappingURL=babylon.nullEngine.js.map
  104235. var BABYLON;
  104236. (function (BABYLON) {
  104237. /**
  104238. * This class can be used to get instrumentation data from a Babylon engine
  104239. */
  104240. var EngineInstrumentation = /** @class */ (function () {
  104241. function EngineInstrumentation(engine) {
  104242. this.engine = engine;
  104243. this._captureGPUFrameTime = false;
  104244. this._gpuFrameTime = new BABYLON.PerfCounter();
  104245. this._captureShaderCompilationTime = false;
  104246. this._shaderCompilationTime = new BABYLON.PerfCounter();
  104247. // Observers
  104248. this._onBeginFrameObserver = null;
  104249. this._onEndFrameObserver = null;
  104250. this._onBeforeShaderCompilationObserver = null;
  104251. this._onAfterShaderCompilationObserver = null;
  104252. }
  104253. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  104254. // Properties
  104255. /**
  104256. * Gets the perf counter used for GPU frame time
  104257. */
  104258. get: function () {
  104259. return this._gpuFrameTime;
  104260. },
  104261. enumerable: true,
  104262. configurable: true
  104263. });
  104264. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  104265. /**
  104266. * Gets the GPU frame time capture status
  104267. */
  104268. get: function () {
  104269. return this._captureGPUFrameTime;
  104270. },
  104271. /**
  104272. * Enable or disable the GPU frame time capture
  104273. */
  104274. set: function (value) {
  104275. var _this = this;
  104276. if (value === this._captureGPUFrameTime) {
  104277. return;
  104278. }
  104279. this._captureGPUFrameTime = value;
  104280. if (value) {
  104281. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  104282. if (!_this._gpuFrameTimeToken) {
  104283. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  104284. }
  104285. });
  104286. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  104287. if (!_this._gpuFrameTimeToken) {
  104288. return;
  104289. }
  104290. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  104291. if (time > -1) {
  104292. _this._gpuFrameTimeToken = null;
  104293. _this._gpuFrameTime.fetchNewFrame();
  104294. _this._gpuFrameTime.addCount(time, true);
  104295. }
  104296. });
  104297. }
  104298. else {
  104299. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104300. this._onBeginFrameObserver = null;
  104301. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104302. this._onEndFrameObserver = null;
  104303. }
  104304. },
  104305. enumerable: true,
  104306. configurable: true
  104307. });
  104308. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  104309. /**
  104310. * Gets the perf counter used for shader compilation time
  104311. */
  104312. get: function () {
  104313. return this._shaderCompilationTime;
  104314. },
  104315. enumerable: true,
  104316. configurable: true
  104317. });
  104318. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  104319. /**
  104320. * Gets the shader compilation time capture status
  104321. */
  104322. get: function () {
  104323. return this._captureShaderCompilationTime;
  104324. },
  104325. /**
  104326. * Enable or disable the shader compilation time capture
  104327. */
  104328. set: function (value) {
  104329. var _this = this;
  104330. if (value === this._captureShaderCompilationTime) {
  104331. return;
  104332. }
  104333. this._captureShaderCompilationTime = value;
  104334. if (value) {
  104335. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  104336. _this._shaderCompilationTime.fetchNewFrame();
  104337. _this._shaderCompilationTime.beginMonitoring();
  104338. });
  104339. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  104340. _this._shaderCompilationTime.endMonitoring();
  104341. });
  104342. }
  104343. else {
  104344. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104345. this._onBeforeShaderCompilationObserver = null;
  104346. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104347. this._onAfterShaderCompilationObserver = null;
  104348. }
  104349. },
  104350. enumerable: true,
  104351. configurable: true
  104352. });
  104353. EngineInstrumentation.prototype.dispose = function () {
  104354. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104355. this._onBeginFrameObserver = null;
  104356. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104357. this._onEndFrameObserver = null;
  104358. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104359. this._onBeforeShaderCompilationObserver = null;
  104360. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104361. this._onAfterShaderCompilationObserver = null;
  104362. this.engine = null;
  104363. };
  104364. return EngineInstrumentation;
  104365. }());
  104366. BABYLON.EngineInstrumentation = EngineInstrumentation;
  104367. })(BABYLON || (BABYLON = {}));
  104368. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  104369. var BABYLON;
  104370. (function (BABYLON) {
  104371. /**
  104372. * This class can be used to get instrumentation data from a Babylon engine
  104373. */
  104374. var SceneInstrumentation = /** @class */ (function () {
  104375. function SceneInstrumentation(scene) {
  104376. var _this = this;
  104377. this.scene = scene;
  104378. this._captureActiveMeshesEvaluationTime = false;
  104379. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  104380. this._captureRenderTargetsRenderTime = false;
  104381. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  104382. this._captureFrameTime = false;
  104383. this._frameTime = new BABYLON.PerfCounter();
  104384. this._captureRenderTime = false;
  104385. this._renderTime = new BABYLON.PerfCounter();
  104386. this._captureInterFrameTime = false;
  104387. this._interFrameTime = new BABYLON.PerfCounter();
  104388. this._captureParticlesRenderTime = false;
  104389. this._particlesRenderTime = new BABYLON.PerfCounter();
  104390. this._captureSpritesRenderTime = false;
  104391. this._spritesRenderTime = new BABYLON.PerfCounter();
  104392. this._capturePhysicsTime = false;
  104393. this._physicsTime = new BABYLON.PerfCounter();
  104394. this._captureAnimationsTime = false;
  104395. this._animationsTime = new BABYLON.PerfCounter();
  104396. this._captureCameraRenderTime = false;
  104397. this._cameraRenderTime = new BABYLON.PerfCounter();
  104398. // Observers
  104399. this._onBeforeActiveMeshesEvaluationObserver = null;
  104400. this._onAfterActiveMeshesEvaluationObserver = null;
  104401. this._onBeforeRenderTargetsRenderObserver = null;
  104402. this._onAfterRenderTargetsRenderObserver = null;
  104403. this._onAfterRenderObserver = null;
  104404. this._onBeforeDrawPhaseObserver = null;
  104405. this._onAfterDrawPhaseObserver = null;
  104406. this._onBeforeAnimationsObserver = null;
  104407. this._onBeforeParticlesRenderingObserver = null;
  104408. this._onAfterParticlesRenderingObserver = null;
  104409. this._onBeforeSpritesRenderingObserver = null;
  104410. this._onAfterSpritesRenderingObserver = null;
  104411. this._onBeforePhysicsObserver = null;
  104412. this._onAfterPhysicsObserver = null;
  104413. this._onAfterAnimationsObserver = null;
  104414. this._onBeforeCameraRenderObserver = null;
  104415. this._onAfterCameraRenderObserver = null;
  104416. // Before render
  104417. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  104418. if (_this._captureActiveMeshesEvaluationTime) {
  104419. _this._activeMeshesEvaluationTime.fetchNewFrame();
  104420. }
  104421. if (_this._captureRenderTargetsRenderTime) {
  104422. _this._renderTargetsRenderTime.fetchNewFrame();
  104423. }
  104424. if (_this._captureFrameTime) {
  104425. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  104426. _this._frameTime.beginMonitoring();
  104427. }
  104428. if (_this._captureInterFrameTime) {
  104429. _this._interFrameTime.endMonitoring();
  104430. }
  104431. if (_this._captureParticlesRenderTime) {
  104432. _this._particlesRenderTime.fetchNewFrame();
  104433. }
  104434. if (_this._captureSpritesRenderTime) {
  104435. _this._spritesRenderTime.fetchNewFrame();
  104436. }
  104437. if (_this._captureAnimationsTime) {
  104438. _this._animationsTime.beginMonitoring();
  104439. }
  104440. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  104441. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  104442. });
  104443. // After render
  104444. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  104445. if (_this._captureFrameTime) {
  104446. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  104447. _this._frameTime.endMonitoring();
  104448. }
  104449. if (_this._captureRenderTime) {
  104450. _this._renderTime.endMonitoring(false);
  104451. }
  104452. if (_this._captureInterFrameTime) {
  104453. _this._interFrameTime.beginMonitoring();
  104454. }
  104455. });
  104456. }
  104457. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  104458. // Properties
  104459. /**
  104460. * Gets the perf counter used for active meshes evaluation time
  104461. */
  104462. get: function () {
  104463. return this._activeMeshesEvaluationTime;
  104464. },
  104465. enumerable: true,
  104466. configurable: true
  104467. });
  104468. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  104469. /**
  104470. * Gets the active meshes evaluation time capture status
  104471. */
  104472. get: function () {
  104473. return this._captureActiveMeshesEvaluationTime;
  104474. },
  104475. /**
  104476. * Enable or disable the active meshes evaluation time capture
  104477. */
  104478. set: function (value) {
  104479. var _this = this;
  104480. if (value === this._captureActiveMeshesEvaluationTime) {
  104481. return;
  104482. }
  104483. this._captureActiveMeshesEvaluationTime = value;
  104484. if (value) {
  104485. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  104486. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  104487. _this._activeMeshesEvaluationTime.beginMonitoring();
  104488. });
  104489. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  104490. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  104491. _this._activeMeshesEvaluationTime.endMonitoring();
  104492. });
  104493. }
  104494. else {
  104495. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104496. this._onBeforeActiveMeshesEvaluationObserver = null;
  104497. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104498. this._onAfterActiveMeshesEvaluationObserver = null;
  104499. }
  104500. },
  104501. enumerable: true,
  104502. configurable: true
  104503. });
  104504. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  104505. /**
  104506. * Gets the perf counter used for render targets render time
  104507. */
  104508. get: function () {
  104509. return this._renderTargetsRenderTime;
  104510. },
  104511. enumerable: true,
  104512. configurable: true
  104513. });
  104514. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  104515. /**
  104516. * Gets the render targets render time capture status
  104517. */
  104518. get: function () {
  104519. return this._captureRenderTargetsRenderTime;
  104520. },
  104521. /**
  104522. * Enable or disable the render targets render time capture
  104523. */
  104524. set: function (value) {
  104525. var _this = this;
  104526. if (value === this._captureRenderTargetsRenderTime) {
  104527. return;
  104528. }
  104529. this._captureRenderTargetsRenderTime = value;
  104530. if (value) {
  104531. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  104532. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  104533. _this._renderTargetsRenderTime.beginMonitoring();
  104534. });
  104535. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  104536. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  104537. _this._renderTargetsRenderTime.endMonitoring(false);
  104538. });
  104539. }
  104540. else {
  104541. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104542. this._onBeforeRenderTargetsRenderObserver = null;
  104543. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104544. this._onAfterRenderTargetsRenderObserver = null;
  104545. }
  104546. },
  104547. enumerable: true,
  104548. configurable: true
  104549. });
  104550. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  104551. /**
  104552. * Gets the perf counter used for particles render time
  104553. */
  104554. get: function () {
  104555. return this._particlesRenderTime;
  104556. },
  104557. enumerable: true,
  104558. configurable: true
  104559. });
  104560. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  104561. /**
  104562. * Gets the particles render time capture status
  104563. */
  104564. get: function () {
  104565. return this._captureParticlesRenderTime;
  104566. },
  104567. /**
  104568. * Enable or disable the particles render time capture
  104569. */
  104570. set: function (value) {
  104571. var _this = this;
  104572. if (value === this._captureParticlesRenderTime) {
  104573. return;
  104574. }
  104575. this._captureParticlesRenderTime = value;
  104576. if (value) {
  104577. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  104578. BABYLON.Tools.StartPerformanceCounter("Particles");
  104579. _this._particlesRenderTime.beginMonitoring();
  104580. });
  104581. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  104582. BABYLON.Tools.EndPerformanceCounter("Particles");
  104583. _this._particlesRenderTime.endMonitoring(false);
  104584. });
  104585. }
  104586. else {
  104587. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104588. this._onBeforeParticlesRenderingObserver = null;
  104589. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104590. this._onAfterParticlesRenderingObserver = null;
  104591. }
  104592. },
  104593. enumerable: true,
  104594. configurable: true
  104595. });
  104596. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  104597. /**
  104598. * Gets the perf counter used for sprites render time
  104599. */
  104600. get: function () {
  104601. return this._spritesRenderTime;
  104602. },
  104603. enumerable: true,
  104604. configurable: true
  104605. });
  104606. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  104607. /**
  104608. * Gets the sprites render time capture status
  104609. */
  104610. get: function () {
  104611. return this._captureSpritesRenderTime;
  104612. },
  104613. /**
  104614. * Enable or disable the sprites render time capture
  104615. */
  104616. set: function (value) {
  104617. var _this = this;
  104618. if (value === this._captureSpritesRenderTime) {
  104619. return;
  104620. }
  104621. this._captureSpritesRenderTime = value;
  104622. if (value) {
  104623. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  104624. BABYLON.Tools.StartPerformanceCounter("Sprites");
  104625. _this._spritesRenderTime.beginMonitoring();
  104626. });
  104627. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  104628. BABYLON.Tools.EndPerformanceCounter("Sprites");
  104629. _this._spritesRenderTime.endMonitoring(false);
  104630. });
  104631. }
  104632. else {
  104633. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104634. this._onBeforeSpritesRenderingObserver = null;
  104635. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104636. this._onAfterSpritesRenderingObserver = null;
  104637. }
  104638. },
  104639. enumerable: true,
  104640. configurable: true
  104641. });
  104642. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  104643. /**
  104644. * Gets the perf counter used for physics time
  104645. */
  104646. get: function () {
  104647. return this._physicsTime;
  104648. },
  104649. enumerable: true,
  104650. configurable: true
  104651. });
  104652. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  104653. /**
  104654. * Gets the physics time capture status
  104655. */
  104656. get: function () {
  104657. return this._capturePhysicsTime;
  104658. },
  104659. /**
  104660. * Enable or disable the physics time capture
  104661. */
  104662. set: function (value) {
  104663. var _this = this;
  104664. if (value === this._capturePhysicsTime) {
  104665. return;
  104666. }
  104667. this._capturePhysicsTime = value;
  104668. if (value) {
  104669. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  104670. BABYLON.Tools.StartPerformanceCounter("Physics");
  104671. _this._physicsTime.beginMonitoring();
  104672. });
  104673. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  104674. BABYLON.Tools.EndPerformanceCounter("Physics");
  104675. _this._physicsTime.endMonitoring();
  104676. });
  104677. }
  104678. else {
  104679. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104680. this._onBeforePhysicsObserver = null;
  104681. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104682. this._onAfterPhysicsObserver = null;
  104683. }
  104684. },
  104685. enumerable: true,
  104686. configurable: true
  104687. });
  104688. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  104689. /**
  104690. * Gets the perf counter used for animations time
  104691. */
  104692. get: function () {
  104693. return this._animationsTime;
  104694. },
  104695. enumerable: true,
  104696. configurable: true
  104697. });
  104698. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  104699. /**
  104700. * Gets the animations time capture status
  104701. */
  104702. get: function () {
  104703. return this._captureAnimationsTime;
  104704. },
  104705. /**
  104706. * Enable or disable the animations time capture
  104707. */
  104708. set: function (value) {
  104709. var _this = this;
  104710. if (value === this._captureAnimationsTime) {
  104711. return;
  104712. }
  104713. this._captureAnimationsTime = value;
  104714. if (value) {
  104715. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  104716. _this._animationsTime.endMonitoring();
  104717. });
  104718. }
  104719. else {
  104720. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104721. this._onAfterAnimationsObserver = null;
  104722. }
  104723. },
  104724. enumerable: true,
  104725. configurable: true
  104726. });
  104727. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  104728. /**
  104729. * Gets the perf counter used for frame time capture
  104730. */
  104731. get: function () {
  104732. return this._frameTime;
  104733. },
  104734. enumerable: true,
  104735. configurable: true
  104736. });
  104737. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  104738. /**
  104739. * Gets the frame time capture status
  104740. */
  104741. get: function () {
  104742. return this._captureFrameTime;
  104743. },
  104744. /**
  104745. * Enable or disable the frame time capture
  104746. */
  104747. set: function (value) {
  104748. this._captureFrameTime = value;
  104749. },
  104750. enumerable: true,
  104751. configurable: true
  104752. });
  104753. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  104754. /**
  104755. * Gets the perf counter used for inter-frames time capture
  104756. */
  104757. get: function () {
  104758. return this._interFrameTime;
  104759. },
  104760. enumerable: true,
  104761. configurable: true
  104762. });
  104763. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  104764. /**
  104765. * Gets the inter-frames time capture status
  104766. */
  104767. get: function () {
  104768. return this._captureInterFrameTime;
  104769. },
  104770. /**
  104771. * Enable or disable the inter-frames time capture
  104772. */
  104773. set: function (value) {
  104774. this._captureInterFrameTime = value;
  104775. },
  104776. enumerable: true,
  104777. configurable: true
  104778. });
  104779. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  104780. /**
  104781. * Gets the perf counter used for render time capture
  104782. */
  104783. get: function () {
  104784. return this._renderTime;
  104785. },
  104786. enumerable: true,
  104787. configurable: true
  104788. });
  104789. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  104790. /**
  104791. * Gets the render time capture status
  104792. */
  104793. get: function () {
  104794. return this._captureRenderTime;
  104795. },
  104796. /**
  104797. * Enable or disable the render time capture
  104798. */
  104799. set: function (value) {
  104800. var _this = this;
  104801. if (value === this._captureRenderTime) {
  104802. return;
  104803. }
  104804. this._captureRenderTime = value;
  104805. if (value) {
  104806. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  104807. _this._renderTime.beginMonitoring();
  104808. BABYLON.Tools.StartPerformanceCounter("Main render");
  104809. });
  104810. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  104811. _this._renderTime.endMonitoring(false);
  104812. BABYLON.Tools.EndPerformanceCounter("Main render");
  104813. });
  104814. }
  104815. else {
  104816. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104817. this._onBeforeDrawPhaseObserver = null;
  104818. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104819. this._onAfterDrawPhaseObserver = null;
  104820. }
  104821. },
  104822. enumerable: true,
  104823. configurable: true
  104824. });
  104825. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  104826. /**
  104827. * Gets the perf counter used for camera render time capture
  104828. */
  104829. get: function () {
  104830. return this._cameraRenderTime;
  104831. },
  104832. enumerable: true,
  104833. configurable: true
  104834. });
  104835. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  104836. /**
  104837. * Gets the camera render time capture status
  104838. */
  104839. get: function () {
  104840. return this._captureCameraRenderTime;
  104841. },
  104842. /**
  104843. * Enable or disable the camera render time capture
  104844. */
  104845. set: function (value) {
  104846. var _this = this;
  104847. if (value === this._captureCameraRenderTime) {
  104848. return;
  104849. }
  104850. this._captureCameraRenderTime = value;
  104851. if (value) {
  104852. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  104853. _this._cameraRenderTime.beginMonitoring();
  104854. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  104855. });
  104856. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  104857. _this._cameraRenderTime.endMonitoring(false);
  104858. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  104859. });
  104860. }
  104861. else {
  104862. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104863. this._onBeforeCameraRenderObserver = null;
  104864. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104865. this._onAfterCameraRenderObserver = null;
  104866. }
  104867. },
  104868. enumerable: true,
  104869. configurable: true
  104870. });
  104871. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  104872. /**
  104873. * Gets the perf counter used for draw calls
  104874. */
  104875. get: function () {
  104876. return this.scene.getEngine()._drawCalls;
  104877. },
  104878. enumerable: true,
  104879. configurable: true
  104880. });
  104881. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  104882. /**
  104883. * Gets the perf counter used for texture collisions
  104884. */
  104885. get: function () {
  104886. return this.scene.getEngine()._textureCollisions;
  104887. },
  104888. enumerable: true,
  104889. configurable: true
  104890. });
  104891. SceneInstrumentation.prototype.dispose = function () {
  104892. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104893. this._onAfterRenderObserver = null;
  104894. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104895. this._onBeforeActiveMeshesEvaluationObserver = null;
  104896. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104897. this._onAfterActiveMeshesEvaluationObserver = null;
  104898. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104899. this._onBeforeRenderTargetsRenderObserver = null;
  104900. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104901. this._onAfterRenderTargetsRenderObserver = null;
  104902. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  104903. this._onBeforeAnimationsObserver = null;
  104904. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104905. this._onBeforeParticlesRenderingObserver = null;
  104906. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104907. this._onAfterParticlesRenderingObserver = null;
  104908. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104909. this._onBeforeSpritesRenderingObserver = null;
  104910. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104911. this._onAfterSpritesRenderingObserver = null;
  104912. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104913. this._onBeforeDrawPhaseObserver = null;
  104914. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104915. this._onAfterDrawPhaseObserver = null;
  104916. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104917. this._onBeforePhysicsObserver = null;
  104918. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104919. this._onAfterPhysicsObserver = null;
  104920. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104921. this._onAfterAnimationsObserver = null;
  104922. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104923. this._onBeforeCameraRenderObserver = null;
  104924. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104925. this._onAfterCameraRenderObserver = null;
  104926. this.scene = null;
  104927. };
  104928. return SceneInstrumentation;
  104929. }());
  104930. BABYLON.SceneInstrumentation = SceneInstrumentation;
  104931. })(BABYLON || (BABYLON = {}));
  104932. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  104933. var BABYLON;
  104934. (function (BABYLON) {
  104935. /**
  104936. * @hidden
  104937. **/
  104938. var _TimeToken = /** @class */ (function () {
  104939. function _TimeToken() {
  104940. this._timeElapsedQueryEnded = false;
  104941. }
  104942. return _TimeToken;
  104943. }());
  104944. BABYLON._TimeToken = _TimeToken;
  104945. })(BABYLON || (BABYLON = {}));
  104946. //# sourceMappingURL=babylon.timeToken.js.map
  104947. var BABYLON;
  104948. (function (BABYLON) {
  104949. /**
  104950. * Background material defines definition.
  104951. * @hidden Mainly internal Use
  104952. */
  104953. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  104954. __extends(BackgroundMaterialDefines, _super);
  104955. /**
  104956. * Constructor of the defines.
  104957. */
  104958. function BackgroundMaterialDefines() {
  104959. var _this = _super.call(this) || this;
  104960. /**
  104961. * True if the diffuse texture is in use.
  104962. */
  104963. _this.DIFFUSE = false;
  104964. /**
  104965. * The direct UV channel to use.
  104966. */
  104967. _this.DIFFUSEDIRECTUV = 0;
  104968. /**
  104969. * True if the diffuse texture is in gamma space.
  104970. */
  104971. _this.GAMMADIFFUSE = false;
  104972. /**
  104973. * True if the diffuse texture has opacity in the alpha channel.
  104974. */
  104975. _this.DIFFUSEHASALPHA = false;
  104976. /**
  104977. * True if you want the material to fade to transparent at grazing angle.
  104978. */
  104979. _this.OPACITYFRESNEL = false;
  104980. /**
  104981. * True if an extra blur needs to be added in the reflection.
  104982. */
  104983. _this.REFLECTIONBLUR = false;
  104984. /**
  104985. * True if you want the material to fade to reflection at grazing angle.
  104986. */
  104987. _this.REFLECTIONFRESNEL = false;
  104988. /**
  104989. * True if you want the material to falloff as far as you move away from the scene center.
  104990. */
  104991. _this.REFLECTIONFALLOFF = false;
  104992. /**
  104993. * False if the current Webgl implementation does not support the texture lod extension.
  104994. */
  104995. _this.TEXTURELODSUPPORT = false;
  104996. /**
  104997. * True to ensure the data are premultiplied.
  104998. */
  104999. _this.PREMULTIPLYALPHA = false;
  105000. /**
  105001. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  105002. */
  105003. _this.USERGBCOLOR = false;
  105004. /**
  105005. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  105006. * stays aligned with the desired configuration.
  105007. */
  105008. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  105009. /**
  105010. * True to add noise in order to reduce the banding effect.
  105011. */
  105012. _this.NOISE = false;
  105013. /**
  105014. * is the reflection texture in BGR color scheme?
  105015. * Mainly used to solve a bug in ios10 video tag
  105016. */
  105017. _this.REFLECTIONBGR = false;
  105018. _this.IMAGEPROCESSING = false;
  105019. _this.VIGNETTE = false;
  105020. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  105021. _this.VIGNETTEBLENDMODEOPAQUE = false;
  105022. _this.TONEMAPPING = false;
  105023. _this.TONEMAPPING_ACES = false;
  105024. _this.CONTRAST = false;
  105025. _this.COLORCURVES = false;
  105026. _this.COLORGRADING = false;
  105027. _this.COLORGRADING3D = false;
  105028. _this.SAMPLER3DGREENDEPTH = false;
  105029. _this.SAMPLER3DBGRMAP = false;
  105030. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  105031. _this.EXPOSURE = false;
  105032. // Reflection.
  105033. _this.REFLECTION = false;
  105034. _this.REFLECTIONMAP_3D = false;
  105035. _this.REFLECTIONMAP_SPHERICAL = false;
  105036. _this.REFLECTIONMAP_PLANAR = false;
  105037. _this.REFLECTIONMAP_CUBIC = false;
  105038. _this.REFLECTIONMAP_PROJECTION = false;
  105039. _this.REFLECTIONMAP_SKYBOX = false;
  105040. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105041. _this.REFLECTIONMAP_EXPLICIT = false;
  105042. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105043. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105044. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105045. _this.INVERTCUBICMAP = false;
  105046. _this.REFLECTIONMAP_OPPOSITEZ = false;
  105047. _this.LODINREFLECTIONALPHA = false;
  105048. _this.GAMMAREFLECTION = false;
  105049. _this.RGBDREFLECTION = false;
  105050. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  105051. // Default BJS.
  105052. _this.MAINUV1 = false;
  105053. _this.MAINUV2 = false;
  105054. _this.UV1 = false;
  105055. _this.UV2 = false;
  105056. _this.CLIPPLANE = false;
  105057. _this.CLIPPLANE2 = false;
  105058. _this.CLIPPLANE3 = false;
  105059. _this.CLIPPLANE4 = false;
  105060. _this.POINTSIZE = false;
  105061. _this.FOG = false;
  105062. _this.NORMAL = false;
  105063. _this.NUM_BONE_INFLUENCERS = 0;
  105064. _this.BonesPerMesh = 0;
  105065. _this.INSTANCES = false;
  105066. _this.SHADOWFLOAT = false;
  105067. _this.rebuild();
  105068. return _this;
  105069. }
  105070. return BackgroundMaterialDefines;
  105071. }(BABYLON.MaterialDefines));
  105072. /**
  105073. * Background material used to create an efficient environement around your scene.
  105074. */
  105075. var BackgroundMaterial = /** @class */ (function (_super) {
  105076. __extends(BackgroundMaterial, _super);
  105077. /**
  105078. * Instantiates a Background Material in the given scene
  105079. * @param name The friendly name of the material
  105080. * @param scene The scene to add the material to
  105081. */
  105082. function BackgroundMaterial(name, scene) {
  105083. var _this = _super.call(this, name, scene) || this;
  105084. /**
  105085. * Key light Color (multiply against the environement texture)
  105086. */
  105087. _this.primaryColor = BABYLON.Color3.White();
  105088. _this._primaryColorShadowLevel = 0;
  105089. _this._primaryColorHighlightLevel = 0;
  105090. /**
  105091. * Reflection Texture used in the material.
  105092. * Should be author in a specific way for the best result (refer to the documentation).
  105093. */
  105094. _this.reflectionTexture = null;
  105095. /**
  105096. * Reflection Texture level of blur.
  105097. *
  105098. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  105099. * texture twice.
  105100. */
  105101. _this.reflectionBlur = 0;
  105102. /**
  105103. * Diffuse Texture used in the material.
  105104. * Should be author in a specific way for the best result (refer to the documentation).
  105105. */
  105106. _this.diffuseTexture = null;
  105107. _this._shadowLights = null;
  105108. /**
  105109. * Specify the list of lights casting shadow on the material.
  105110. * All scene shadow lights will be included if null.
  105111. */
  105112. _this.shadowLights = null;
  105113. /**
  105114. * Helps adjusting the shadow to a softer level if required.
  105115. * 0 means black shadows and 1 means no shadows.
  105116. */
  105117. _this.shadowLevel = 0;
  105118. /**
  105119. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  105120. * It is usually zero but might be interesting to modify according to your setup.
  105121. */
  105122. _this.sceneCenter = BABYLON.Vector3.Zero();
  105123. /**
  105124. * This helps specifying that the material is falling off to the sky box at grazing angle.
  105125. * This helps ensuring a nice transition when the camera goes under the ground.
  105126. */
  105127. _this.opacityFresnel = true;
  105128. /**
  105129. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  105130. * This helps adding a mirror texture on the ground.
  105131. */
  105132. _this.reflectionFresnel = false;
  105133. /**
  105134. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  105135. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  105136. */
  105137. _this.reflectionFalloffDistance = 0.0;
  105138. /**
  105139. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  105140. */
  105141. _this.reflectionAmount = 1.0;
  105142. /**
  105143. * This specifies the weight of the reflection at grazing angle.
  105144. */
  105145. _this.reflectionReflectance0 = 0.05;
  105146. /**
  105147. * This specifies the weight of the reflection at a perpendicular point of view.
  105148. */
  105149. _this.reflectionReflectance90 = 0.5;
  105150. /**
  105151. * Helps to directly use the maps channels instead of their level.
  105152. */
  105153. _this.useRGBColor = true;
  105154. /**
  105155. * This helps reducing the banding effect that could occur on the background.
  105156. */
  105157. _this.enableNoise = false;
  105158. _this._fovMultiplier = 1.0;
  105159. /**
  105160. * Enable the FOV adjustment feature controlled by fovMultiplier.
  105161. */
  105162. _this.useEquirectangularFOV = false;
  105163. _this._maxSimultaneousLights = 4;
  105164. /**
  105165. * Number of Simultaneous lights allowed on the material.
  105166. */
  105167. _this.maxSimultaneousLights = 4;
  105168. /**
  105169. * Keep track of the image processing observer to allow dispose and replace.
  105170. */
  105171. _this._imageProcessingObserver = null;
  105172. /**
  105173. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  105174. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  105175. */
  105176. _this.switchToBGR = false;
  105177. // Temp values kept as cache in the material.
  105178. _this._renderTargets = new BABYLON.SmartArray(16);
  105179. _this._reflectionControls = BABYLON.Vector4.Zero();
  105180. _this._white = BABYLON.Color3.White();
  105181. _this._primaryShadowColor = BABYLON.Color3.Black();
  105182. _this._primaryHighlightColor = BABYLON.Color3.Black();
  105183. // Setup the default processing configuration to the scene.
  105184. _this._attachImageProcessingConfiguration(null);
  105185. _this.getRenderTargetTextures = function () {
  105186. _this._renderTargets.reset();
  105187. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  105188. _this._renderTargets.push(_this._diffuseTexture);
  105189. }
  105190. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  105191. _this._renderTargets.push(_this._reflectionTexture);
  105192. }
  105193. return _this._renderTargets;
  105194. };
  105195. return _this;
  105196. }
  105197. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  105198. /**
  105199. * Experimental Internal Use Only.
  105200. *
  105201. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  105202. * This acts as a helper to set the primary color to a more "human friendly" value.
  105203. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  105204. * output color as close as possible from the chosen value.
  105205. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  105206. * part of lighting setup.)
  105207. */
  105208. get: function () {
  105209. return this.__perceptualColor;
  105210. },
  105211. set: function (value) {
  105212. this.__perceptualColor = value;
  105213. this._computePrimaryColorFromPerceptualColor();
  105214. this._markAllSubMeshesAsLightsDirty();
  105215. },
  105216. enumerable: true,
  105217. configurable: true
  105218. });
  105219. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  105220. /**
  105221. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  105222. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  105223. */
  105224. get: function () {
  105225. return this._primaryColorShadowLevel;
  105226. },
  105227. set: function (value) {
  105228. this._primaryColorShadowLevel = value;
  105229. this._computePrimaryColors();
  105230. this._markAllSubMeshesAsLightsDirty();
  105231. },
  105232. enumerable: true,
  105233. configurable: true
  105234. });
  105235. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  105236. /**
  105237. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  105238. * The primary color is used at the level chosen to define what the white area would look.
  105239. */
  105240. get: function () {
  105241. return this._primaryColorHighlightLevel;
  105242. },
  105243. set: function (value) {
  105244. this._primaryColorHighlightLevel = value;
  105245. this._computePrimaryColors();
  105246. this._markAllSubMeshesAsLightsDirty();
  105247. },
  105248. enumerable: true,
  105249. configurable: true
  105250. });
  105251. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  105252. /**
  105253. * Sets the reflection reflectance fresnel values according to the default standard
  105254. * empirically know to work well :-)
  105255. */
  105256. set: function (value) {
  105257. var reflectionWeight = value;
  105258. if (reflectionWeight < 0.5) {
  105259. reflectionWeight = reflectionWeight * 2.0;
  105260. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  105261. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  105262. }
  105263. else {
  105264. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  105265. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  105266. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  105267. }
  105268. },
  105269. enumerable: true,
  105270. configurable: true
  105271. });
  105272. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  105273. /**
  105274. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105275. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  105276. * Recommended to be keep at 1.0 except for special cases.
  105277. */
  105278. get: function () {
  105279. return this._fovMultiplier;
  105280. },
  105281. set: function (value) {
  105282. if (isNaN(value)) {
  105283. value = 1.0;
  105284. }
  105285. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  105286. },
  105287. enumerable: true,
  105288. configurable: true
  105289. });
  105290. /**
  105291. * Attaches a new image processing configuration to the PBR Material.
  105292. * @param configuration (if null the scene configuration will be use)
  105293. */
  105294. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  105295. var _this = this;
  105296. if (configuration === this._imageProcessingConfiguration) {
  105297. return;
  105298. }
  105299. // Detaches observer.
  105300. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105301. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105302. }
  105303. // Pick the scene configuration if needed.
  105304. if (!configuration) {
  105305. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  105306. }
  105307. else {
  105308. this._imageProcessingConfiguration = configuration;
  105309. }
  105310. // Attaches observer.
  105311. if (this._imageProcessingConfiguration) {
  105312. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  105313. _this._computePrimaryColorFromPerceptualColor();
  105314. _this._markAllSubMeshesAsImageProcessingDirty();
  105315. });
  105316. }
  105317. };
  105318. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  105319. /**
  105320. * Gets the image processing configuration used either in this material.
  105321. */
  105322. get: function () {
  105323. return this._imageProcessingConfiguration;
  105324. },
  105325. /**
  105326. * Sets the Default image processing configuration used either in the this material.
  105327. *
  105328. * If sets to null, the scene one is in use.
  105329. */
  105330. set: function (value) {
  105331. this._attachImageProcessingConfiguration(value);
  105332. // Ensure the effect will be rebuilt.
  105333. this._markAllSubMeshesAsTexturesDirty();
  105334. },
  105335. enumerable: true,
  105336. configurable: true
  105337. });
  105338. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  105339. /**
  105340. * Gets wether the color curves effect is enabled.
  105341. */
  105342. get: function () {
  105343. return this.imageProcessingConfiguration.colorCurvesEnabled;
  105344. },
  105345. /**
  105346. * Sets wether the color curves effect is enabled.
  105347. */
  105348. set: function (value) {
  105349. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  105350. },
  105351. enumerable: true,
  105352. configurable: true
  105353. });
  105354. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  105355. /**
  105356. * Gets wether the color grading effect is enabled.
  105357. */
  105358. get: function () {
  105359. return this.imageProcessingConfiguration.colorGradingEnabled;
  105360. },
  105361. /**
  105362. * Gets wether the color grading effect is enabled.
  105363. */
  105364. set: function (value) {
  105365. this.imageProcessingConfiguration.colorGradingEnabled = value;
  105366. },
  105367. enumerable: true,
  105368. configurable: true
  105369. });
  105370. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  105371. /**
  105372. * Gets wether tonemapping is enabled or not.
  105373. */
  105374. get: function () {
  105375. return this._imageProcessingConfiguration.toneMappingEnabled;
  105376. },
  105377. /**
  105378. * Sets wether tonemapping is enabled or not
  105379. */
  105380. set: function (value) {
  105381. this._imageProcessingConfiguration.toneMappingEnabled = value;
  105382. },
  105383. enumerable: true,
  105384. configurable: true
  105385. });
  105386. ;
  105387. ;
  105388. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  105389. /**
  105390. * The camera exposure used on this material.
  105391. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105392. * This corresponds to a photographic exposure.
  105393. */
  105394. get: function () {
  105395. return this._imageProcessingConfiguration.exposure;
  105396. },
  105397. /**
  105398. * The camera exposure used on this material.
  105399. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105400. * This corresponds to a photographic exposure.
  105401. */
  105402. set: function (value) {
  105403. this._imageProcessingConfiguration.exposure = value;
  105404. },
  105405. enumerable: true,
  105406. configurable: true
  105407. });
  105408. ;
  105409. ;
  105410. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  105411. /**
  105412. * Gets The camera contrast used on this material.
  105413. */
  105414. get: function () {
  105415. return this._imageProcessingConfiguration.contrast;
  105416. },
  105417. /**
  105418. * Sets The camera contrast used on this material.
  105419. */
  105420. set: function (value) {
  105421. this._imageProcessingConfiguration.contrast = value;
  105422. },
  105423. enumerable: true,
  105424. configurable: true
  105425. });
  105426. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  105427. /**
  105428. * Gets the Color Grading 2D Lookup Texture.
  105429. */
  105430. get: function () {
  105431. return this._imageProcessingConfiguration.colorGradingTexture;
  105432. },
  105433. /**
  105434. * Sets the Color Grading 2D Lookup Texture.
  105435. */
  105436. set: function (value) {
  105437. this.imageProcessingConfiguration.colorGradingTexture = value;
  105438. },
  105439. enumerable: true,
  105440. configurable: true
  105441. });
  105442. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  105443. /**
  105444. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105445. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105446. * 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;
  105447. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105448. */
  105449. get: function () {
  105450. return this.imageProcessingConfiguration.colorCurves;
  105451. },
  105452. /**
  105453. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105454. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105455. * 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;
  105456. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105457. */
  105458. set: function (value) {
  105459. this.imageProcessingConfiguration.colorCurves = value;
  105460. },
  105461. enumerable: true,
  105462. configurable: true
  105463. });
  105464. /**
  105465. * The entire material has been created in order to prevent overdraw.
  105466. * @returns false
  105467. */
  105468. BackgroundMaterial.prototype.needAlphaTesting = function () {
  105469. return true;
  105470. };
  105471. /**
  105472. * The entire material has been created in order to prevent overdraw.
  105473. * @returns true if blending is enable
  105474. */
  105475. BackgroundMaterial.prototype.needAlphaBlending = function () {
  105476. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  105477. };
  105478. /**
  105479. * Checks wether the material is ready to be rendered for a given mesh.
  105480. * @param mesh The mesh to render
  105481. * @param subMesh The submesh to check against
  105482. * @param useInstances Specify wether or not the material is used with instances
  105483. * @returns true if all the dependencies are ready (Textures, Effects...)
  105484. */
  105485. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  105486. var _this = this;
  105487. if (useInstances === void 0) { useInstances = false; }
  105488. if (subMesh.effect && this.isFrozen) {
  105489. if (this._wasPreviouslyReady) {
  105490. return true;
  105491. }
  105492. }
  105493. if (!subMesh._materialDefines) {
  105494. subMesh._materialDefines = new BackgroundMaterialDefines();
  105495. }
  105496. var scene = this.getScene();
  105497. var defines = subMesh._materialDefines;
  105498. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  105499. if (defines._renderId === scene.getRenderId()) {
  105500. return true;
  105501. }
  105502. }
  105503. var engine = scene.getEngine();
  105504. // Lights
  105505. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  105506. defines._needNormals = true;
  105507. // Textures
  105508. if (defines._areTexturesDirty) {
  105509. defines._needUVs = false;
  105510. if (scene.texturesEnabled) {
  105511. if (scene.getEngine().getCaps().textureLOD) {
  105512. defines.TEXTURELODSUPPORT = true;
  105513. }
  105514. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105515. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  105516. return false;
  105517. }
  105518. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  105519. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  105520. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  105521. defines.OPACITYFRESNEL = this._opacityFresnel;
  105522. }
  105523. else {
  105524. defines.DIFFUSE = false;
  105525. defines.DIFFUSEHASALPHA = false;
  105526. defines.GAMMADIFFUSE = false;
  105527. defines.OPACITYFRESNEL = false;
  105528. }
  105529. var reflectionTexture = this._reflectionTexture;
  105530. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105531. if (!reflectionTexture.isReadyOrNotBlocking()) {
  105532. return false;
  105533. }
  105534. defines.REFLECTION = true;
  105535. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  105536. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  105537. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  105538. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  105539. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  105540. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  105541. defines.REFLECTIONBGR = this.switchToBGR;
  105542. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  105543. defines.INVERTCUBICMAP = true;
  105544. }
  105545. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  105546. switch (reflectionTexture.coordinatesMode) {
  105547. case BABYLON.Texture.EXPLICIT_MODE:
  105548. defines.REFLECTIONMAP_EXPLICIT = true;
  105549. break;
  105550. case BABYLON.Texture.PLANAR_MODE:
  105551. defines.REFLECTIONMAP_PLANAR = true;
  105552. break;
  105553. case BABYLON.Texture.PROJECTION_MODE:
  105554. defines.REFLECTIONMAP_PROJECTION = true;
  105555. break;
  105556. case BABYLON.Texture.SKYBOX_MODE:
  105557. defines.REFLECTIONMAP_SKYBOX = true;
  105558. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  105559. break;
  105560. case BABYLON.Texture.SPHERICAL_MODE:
  105561. defines.REFLECTIONMAP_SPHERICAL = true;
  105562. break;
  105563. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  105564. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  105565. break;
  105566. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  105567. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  105568. break;
  105569. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  105570. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  105571. break;
  105572. case BABYLON.Texture.CUBIC_MODE:
  105573. case BABYLON.Texture.INVCUBIC_MODE:
  105574. default:
  105575. defines.REFLECTIONMAP_CUBIC = true;
  105576. break;
  105577. }
  105578. if (this.reflectionFresnel) {
  105579. defines.REFLECTIONFRESNEL = true;
  105580. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  105581. this._reflectionControls.x = this.reflectionAmount;
  105582. this._reflectionControls.y = this.reflectionReflectance0;
  105583. this._reflectionControls.z = this.reflectionReflectance90;
  105584. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  105585. }
  105586. else {
  105587. defines.REFLECTIONFRESNEL = false;
  105588. defines.REFLECTIONFALLOFF = false;
  105589. }
  105590. }
  105591. else {
  105592. defines.REFLECTION = false;
  105593. defines.REFLECTIONFRESNEL = false;
  105594. defines.REFLECTIONFALLOFF = false;
  105595. defines.REFLECTIONBLUR = false;
  105596. defines.REFLECTIONMAP_3D = false;
  105597. defines.REFLECTIONMAP_SPHERICAL = false;
  105598. defines.REFLECTIONMAP_PLANAR = false;
  105599. defines.REFLECTIONMAP_CUBIC = false;
  105600. defines.REFLECTIONMAP_PROJECTION = false;
  105601. defines.REFLECTIONMAP_SKYBOX = false;
  105602. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105603. defines.REFLECTIONMAP_EXPLICIT = false;
  105604. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105605. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105606. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105607. defines.INVERTCUBICMAP = false;
  105608. defines.REFLECTIONMAP_OPPOSITEZ = false;
  105609. defines.LODINREFLECTIONALPHA = false;
  105610. defines.GAMMAREFLECTION = false;
  105611. defines.RGBDREFLECTION = false;
  105612. }
  105613. }
  105614. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  105615. defines.USERGBCOLOR = this._useRGBColor;
  105616. defines.NOISE = this._enableNoise;
  105617. }
  105618. if (defines._areLightsDirty) {
  105619. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  105620. }
  105621. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  105622. if (!this._imageProcessingConfiguration.isReady()) {
  105623. return false;
  105624. }
  105625. this._imageProcessingConfiguration.prepareDefines(defines);
  105626. }
  105627. // Misc.
  105628. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  105629. // Values that need to be evaluated on every frame
  105630. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  105631. // Attribs
  105632. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  105633. if (mesh) {
  105634. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  105635. mesh.createNormals(true);
  105636. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  105637. }
  105638. }
  105639. }
  105640. // Get correct effect
  105641. if (defines.isDirty) {
  105642. defines.markAsProcessed();
  105643. scene.resetCachedMaterial();
  105644. // Fallbacks
  105645. var fallbacks = new BABYLON.EffectFallbacks();
  105646. if (defines.FOG) {
  105647. fallbacks.addFallback(0, "FOG");
  105648. }
  105649. if (defines.POINTSIZE) {
  105650. fallbacks.addFallback(1, "POINTSIZE");
  105651. }
  105652. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  105653. if (defines.NUM_BONE_INFLUENCERS > 0) {
  105654. fallbacks.addCPUSkinningFallback(0, mesh);
  105655. }
  105656. //Attributes
  105657. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105658. if (defines.NORMAL) {
  105659. attribs.push(BABYLON.VertexBuffer.NormalKind);
  105660. }
  105661. if (defines.UV1) {
  105662. attribs.push(BABYLON.VertexBuffer.UVKind);
  105663. }
  105664. if (defines.UV2) {
  105665. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105666. }
  105667. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  105668. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  105669. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  105670. "vFogInfos", "vFogColor", "pointSize",
  105671. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  105672. "vPrimaryColor", "vPrimaryColorShadow",
  105673. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  105674. "shadowLevel", "alpha",
  105675. "vBackgroundCenter", "vReflectionControl",
  105676. "vDiffuseInfos", "diffuseMatrix",
  105677. ];
  105678. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  105679. var uniformBuffers = ["Material", "Scene"];
  105680. if (BABYLON.ImageProcessingConfiguration) {
  105681. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  105682. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  105683. }
  105684. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  105685. uniformsNames: uniforms,
  105686. uniformBuffersNames: uniformBuffers,
  105687. samplers: samplers,
  105688. defines: defines,
  105689. maxSimultaneousLights: this._maxSimultaneousLights
  105690. });
  105691. var onCompiled = function (effect) {
  105692. if (_this.onCompiled) {
  105693. _this.onCompiled(effect);
  105694. }
  105695. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  105696. };
  105697. var join = defines.toString();
  105698. subMesh.setEffect(scene.getEngine().createEffect("background", {
  105699. attributes: attribs,
  105700. uniformsNames: uniforms,
  105701. uniformBuffersNames: uniformBuffers,
  105702. samplers: samplers,
  105703. defines: join,
  105704. fallbacks: fallbacks,
  105705. onCompiled: onCompiled,
  105706. onError: this.onError,
  105707. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  105708. }, engine), defines);
  105709. this.buildUniformLayout();
  105710. }
  105711. if (!subMesh.effect || !subMesh.effect.isReady()) {
  105712. return false;
  105713. }
  105714. defines._renderId = scene.getRenderId();
  105715. this._wasPreviouslyReady = true;
  105716. return true;
  105717. };
  105718. /**
  105719. * Compute the primary color according to the chosen perceptual color.
  105720. */
  105721. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  105722. if (!this.__perceptualColor) {
  105723. return;
  105724. }
  105725. this._primaryColor.copyFrom(this.__perceptualColor);
  105726. // Revert gamma space.
  105727. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  105728. // Revert image processing configuration.
  105729. if (this._imageProcessingConfiguration) {
  105730. // Revert Exposure.
  105731. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  105732. }
  105733. this._computePrimaryColors();
  105734. };
  105735. /**
  105736. * Compute the highlights and shadow colors according to their chosen levels.
  105737. */
  105738. BackgroundMaterial.prototype._computePrimaryColors = function () {
  105739. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  105740. return;
  105741. }
  105742. // Find the highlight color based on the configuration.
  105743. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  105744. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  105745. // Find the shadow color based on the configuration.
  105746. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  105747. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  105748. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  105749. };
  105750. /**
  105751. * Build the uniform buffer used in the material.
  105752. */
  105753. BackgroundMaterial.prototype.buildUniformLayout = function () {
  105754. // Order is important !
  105755. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  105756. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  105757. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  105758. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  105759. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  105760. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  105761. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  105762. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  105763. this._uniformBuffer.addUniform("pointSize", 1);
  105764. this._uniformBuffer.addUniform("shadowLevel", 1);
  105765. this._uniformBuffer.addUniform("alpha", 1);
  105766. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  105767. this._uniformBuffer.addUniform("vReflectionControl", 4);
  105768. this._uniformBuffer.create();
  105769. };
  105770. /**
  105771. * Unbind the material.
  105772. */
  105773. BackgroundMaterial.prototype.unbind = function () {
  105774. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  105775. this._uniformBuffer.setTexture("diffuseSampler", null);
  105776. }
  105777. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  105778. this._uniformBuffer.setTexture("reflectionSampler", null);
  105779. }
  105780. _super.prototype.unbind.call(this);
  105781. };
  105782. /**
  105783. * Bind only the world matrix to the material.
  105784. * @param world The world matrix to bind.
  105785. */
  105786. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  105787. this._activeEffect.setMatrix("world", world);
  105788. };
  105789. /**
  105790. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  105791. * @param world The world matrix to bind.
  105792. * @param subMesh The submesh to bind for.
  105793. */
  105794. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  105795. var scene = this.getScene();
  105796. var defines = subMesh._materialDefines;
  105797. if (!defines) {
  105798. return;
  105799. }
  105800. var effect = subMesh.effect;
  105801. if (!effect) {
  105802. return;
  105803. }
  105804. this._activeEffect = effect;
  105805. // Matrices
  105806. this.bindOnlyWorldMatrix(world);
  105807. // Bones
  105808. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  105809. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  105810. if (mustRebind) {
  105811. this._uniformBuffer.bindToEffect(effect, "Material");
  105812. this.bindViewProjection(effect);
  105813. var reflectionTexture = this._reflectionTexture;
  105814. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  105815. // Texture uniforms
  105816. if (scene.texturesEnabled) {
  105817. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105818. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  105819. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  105820. }
  105821. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105822. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  105823. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  105824. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  105825. }
  105826. }
  105827. if (this.shadowLevel > 0) {
  105828. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  105829. }
  105830. this._uniformBuffer.updateFloat("alpha", this.alpha);
  105831. // Point size
  105832. if (this.pointsCloud) {
  105833. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  105834. }
  105835. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  105836. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  105837. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  105838. }
  105839. else {
  105840. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  105841. }
  105842. }
  105843. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  105844. // Textures
  105845. if (scene.texturesEnabled) {
  105846. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105847. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  105848. }
  105849. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105850. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  105851. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105852. }
  105853. else if (!defines.REFLECTIONBLUR) {
  105854. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105855. }
  105856. else {
  105857. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  105858. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  105859. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  105860. }
  105861. if (defines.REFLECTIONFRESNEL) {
  105862. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  105863. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  105864. }
  105865. }
  105866. }
  105867. // Clip plane
  105868. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  105869. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  105870. }
  105871. if (mustRebind || !this.isFrozen) {
  105872. if (scene.lightsEnabled) {
  105873. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  105874. }
  105875. // View
  105876. this.bindView(effect);
  105877. // Fog
  105878. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  105879. // image processing
  105880. if (this._imageProcessingConfiguration) {
  105881. this._imageProcessingConfiguration.bind(this._activeEffect);
  105882. }
  105883. }
  105884. this._uniformBuffer.update();
  105885. this._afterBind(mesh, this._activeEffect);
  105886. };
  105887. /**
  105888. * Dispose the material.
  105889. * @param forceDisposeEffect Force disposal of the associated effect.
  105890. * @param forceDisposeTextures Force disposal of the associated textures.
  105891. */
  105892. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  105893. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  105894. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  105895. if (forceDisposeTextures) {
  105896. if (this.diffuseTexture) {
  105897. this.diffuseTexture.dispose();
  105898. }
  105899. if (this.reflectionTexture) {
  105900. this.reflectionTexture.dispose();
  105901. }
  105902. }
  105903. this._renderTargets.dispose();
  105904. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105905. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105906. }
  105907. _super.prototype.dispose.call(this, forceDisposeEffect);
  105908. };
  105909. /**
  105910. * Clones the material.
  105911. * @param name The cloned name.
  105912. * @returns The cloned material.
  105913. */
  105914. BackgroundMaterial.prototype.clone = function (name) {
  105915. var _this = this;
  105916. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  105917. };
  105918. /**
  105919. * Serializes the current material to its JSON representation.
  105920. * @returns The JSON representation.
  105921. */
  105922. BackgroundMaterial.prototype.serialize = function () {
  105923. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105924. serializationObject.customType = "BABYLON.BackgroundMaterial";
  105925. return serializationObject;
  105926. };
  105927. /**
  105928. * Gets the class name of the material
  105929. * @returns "BackgroundMaterial"
  105930. */
  105931. BackgroundMaterial.prototype.getClassName = function () {
  105932. return "BackgroundMaterial";
  105933. };
  105934. /**
  105935. * Parse a JSON input to create back a background material.
  105936. * @param source The JSON data to parse
  105937. * @param scene The scene to create the parsed material in
  105938. * @param rootUrl The root url of the assets the material depends upon
  105939. * @returns the instantiated BackgroundMaterial.
  105940. */
  105941. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  105942. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  105943. };
  105944. /**
  105945. * Standard reflectance value at parallel view angle.
  105946. */
  105947. BackgroundMaterial.StandardReflectance0 = 0.05;
  105948. /**
  105949. * Standard reflectance value at grazing angle.
  105950. */
  105951. BackgroundMaterial.StandardReflectance90 = 0.5;
  105952. __decorate([
  105953. BABYLON.serializeAsColor3()
  105954. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  105955. __decorate([
  105956. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105957. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  105958. __decorate([
  105959. BABYLON.serializeAsColor3()
  105960. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  105961. __decorate([
  105962. BABYLON.serialize()
  105963. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  105964. __decorate([
  105965. BABYLON.serialize()
  105966. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  105967. __decorate([
  105968. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105969. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  105970. __decorate([
  105971. BABYLON.serializeAsTexture()
  105972. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  105973. __decorate([
  105974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105975. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  105976. __decorate([
  105977. BABYLON.serialize()
  105978. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  105979. __decorate([
  105980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105981. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  105982. __decorate([
  105983. BABYLON.serializeAsTexture()
  105984. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  105985. __decorate([
  105986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105987. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  105988. __decorate([
  105989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105990. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  105991. __decorate([
  105992. BABYLON.serialize()
  105993. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  105994. __decorate([
  105995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105996. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  105997. __decorate([
  105998. BABYLON.serializeAsVector3()
  105999. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  106000. __decorate([
  106001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106002. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  106003. __decorate([
  106004. BABYLON.serialize()
  106005. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  106006. __decorate([
  106007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106008. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  106009. __decorate([
  106010. BABYLON.serialize()
  106011. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  106012. __decorate([
  106013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106014. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  106015. __decorate([
  106016. BABYLON.serialize()
  106017. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  106018. __decorate([
  106019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106020. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  106021. __decorate([
  106022. BABYLON.serialize()
  106023. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  106024. __decorate([
  106025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106026. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  106027. __decorate([
  106028. BABYLON.serialize()
  106029. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  106030. __decorate([
  106031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106032. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  106033. __decorate([
  106034. BABYLON.serialize()
  106035. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  106036. __decorate([
  106037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106038. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  106039. __decorate([
  106040. BABYLON.serialize()
  106041. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  106042. __decorate([
  106043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106044. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  106045. __decorate([
  106046. BABYLON.serialize()
  106047. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  106048. __decorate([
  106049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106050. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  106051. __decorate([
  106052. BABYLON.serialize()
  106053. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  106054. __decorate([
  106055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106056. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  106057. __decorate([
  106058. BABYLON.serializeAsImageProcessingConfiguration()
  106059. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  106060. return BackgroundMaterial;
  106061. }(BABYLON.PushMaterial));
  106062. BABYLON.BackgroundMaterial = BackgroundMaterial;
  106063. })(BABYLON || (BABYLON = {}));
  106064. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  106065. var __assign = (this && this.__assign) || function () {
  106066. __assign = Object.assign || function(t) {
  106067. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106068. s = arguments[i];
  106069. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106070. t[p] = s[p];
  106071. }
  106072. return t;
  106073. };
  106074. return __assign.apply(this, arguments);
  106075. };
  106076. var BABYLON;
  106077. (function (BABYLON) {
  106078. /**
  106079. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  106080. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  106081. * It also helps with the default setup of your imageProcessing configuration.
  106082. */
  106083. var EnvironmentHelper = /** @class */ (function () {
  106084. /**
  106085. * constructor
  106086. * @param options
  106087. * @param scene The scene to add the material to
  106088. */
  106089. function EnvironmentHelper(options, scene) {
  106090. var _this = this;
  106091. this._errorHandler = function (message, exception) {
  106092. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  106093. };
  106094. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  106095. this._scene = scene;
  106096. this.onErrorObservable = new BABYLON.Observable();
  106097. this._setupBackground();
  106098. this._setupImageProcessing();
  106099. }
  106100. /**
  106101. * Creates the default options for the helper.
  106102. */
  106103. EnvironmentHelper._getDefaultOptions = function () {
  106104. return {
  106105. createGround: true,
  106106. groundSize: 15,
  106107. groundTexture: this._groundTextureCDNUrl,
  106108. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106109. groundOpacity: 0.9,
  106110. enableGroundShadow: true,
  106111. groundShadowLevel: 0.5,
  106112. enableGroundMirror: false,
  106113. groundMirrorSizeRatio: 0.3,
  106114. groundMirrorBlurKernel: 64,
  106115. groundMirrorAmount: 1,
  106116. groundMirrorFresnelWeight: 1,
  106117. groundMirrorFallOffDistance: 0,
  106118. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  106119. groundYBias: 0.00001,
  106120. createSkybox: true,
  106121. skyboxSize: 20,
  106122. skyboxTexture: this._skyboxTextureCDNUrl,
  106123. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106124. backgroundYRotation: 0,
  106125. sizeAuto: true,
  106126. rootPosition: BABYLON.Vector3.Zero(),
  106127. setupImageProcessing: true,
  106128. environmentTexture: this._environmentTextureCDNUrl,
  106129. cameraExposure: 0.8,
  106130. cameraContrast: 1.2,
  106131. toneMappingEnabled: true,
  106132. };
  106133. };
  106134. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  106135. /**
  106136. * Gets the root mesh created by the helper.
  106137. */
  106138. get: function () {
  106139. return this._rootMesh;
  106140. },
  106141. enumerable: true,
  106142. configurable: true
  106143. });
  106144. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  106145. /**
  106146. * Gets the skybox created by the helper.
  106147. */
  106148. get: function () {
  106149. return this._skybox;
  106150. },
  106151. enumerable: true,
  106152. configurable: true
  106153. });
  106154. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  106155. /**
  106156. * Gets the skybox texture created by the helper.
  106157. */
  106158. get: function () {
  106159. return this._skyboxTexture;
  106160. },
  106161. enumerable: true,
  106162. configurable: true
  106163. });
  106164. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  106165. /**
  106166. * Gets the skybox material created by the helper.
  106167. */
  106168. get: function () {
  106169. return this._skyboxMaterial;
  106170. },
  106171. enumerable: true,
  106172. configurable: true
  106173. });
  106174. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  106175. /**
  106176. * Gets the ground mesh created by the helper.
  106177. */
  106178. get: function () {
  106179. return this._ground;
  106180. },
  106181. enumerable: true,
  106182. configurable: true
  106183. });
  106184. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  106185. /**
  106186. * Gets the ground texture created by the helper.
  106187. */
  106188. get: function () {
  106189. return this._groundTexture;
  106190. },
  106191. enumerable: true,
  106192. configurable: true
  106193. });
  106194. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  106195. /**
  106196. * Gets the ground mirror created by the helper.
  106197. */
  106198. get: function () {
  106199. return this._groundMirror;
  106200. },
  106201. enumerable: true,
  106202. configurable: true
  106203. });
  106204. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  106205. /**
  106206. * Gets the ground mirror render list to helps pushing the meshes
  106207. * you wish in the ground reflection.
  106208. */
  106209. get: function () {
  106210. if (this._groundMirror) {
  106211. return this._groundMirror.renderList;
  106212. }
  106213. return null;
  106214. },
  106215. enumerable: true,
  106216. configurable: true
  106217. });
  106218. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  106219. /**
  106220. * Gets the ground material created by the helper.
  106221. */
  106222. get: function () {
  106223. return this._groundMaterial;
  106224. },
  106225. enumerable: true,
  106226. configurable: true
  106227. });
  106228. /**
  106229. * Updates the background according to the new options
  106230. * @param options
  106231. */
  106232. EnvironmentHelper.prototype.updateOptions = function (options) {
  106233. var newOptions = __assign({}, this._options, options);
  106234. if (this._ground && !newOptions.createGround) {
  106235. this._ground.dispose();
  106236. this._ground = null;
  106237. }
  106238. if (this._groundMaterial && !newOptions.createGround) {
  106239. this._groundMaterial.dispose();
  106240. this._groundMaterial = null;
  106241. }
  106242. if (this._groundTexture) {
  106243. if (this._options.groundTexture != newOptions.groundTexture) {
  106244. this._groundTexture.dispose();
  106245. this._groundTexture = null;
  106246. }
  106247. }
  106248. if (this._skybox && !newOptions.createSkybox) {
  106249. this._skybox.dispose();
  106250. this._skybox = null;
  106251. }
  106252. if (this._skyboxMaterial && !newOptions.createSkybox) {
  106253. this._skyboxMaterial.dispose();
  106254. this._skyboxMaterial = null;
  106255. }
  106256. if (this._skyboxTexture) {
  106257. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  106258. this._skyboxTexture.dispose();
  106259. this._skyboxTexture = null;
  106260. }
  106261. }
  106262. if (this._groundMirror && !newOptions.enableGroundMirror) {
  106263. this._groundMirror.dispose();
  106264. this._groundMirror = null;
  106265. }
  106266. if (this._scene.environmentTexture) {
  106267. if (this._options.environmentTexture != newOptions.environmentTexture) {
  106268. this._scene.environmentTexture.dispose();
  106269. }
  106270. }
  106271. this._options = newOptions;
  106272. this._setupBackground();
  106273. this._setupImageProcessing();
  106274. };
  106275. /**
  106276. * Sets the primary color of all the available elements.
  106277. * @param color the main color to affect to the ground and the background
  106278. */
  106279. EnvironmentHelper.prototype.setMainColor = function (color) {
  106280. if (this.groundMaterial) {
  106281. this.groundMaterial.primaryColor = color;
  106282. }
  106283. if (this.skyboxMaterial) {
  106284. this.skyboxMaterial.primaryColor = color;
  106285. }
  106286. if (this.groundMirror) {
  106287. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  106288. }
  106289. };
  106290. /**
  106291. * Setup the image processing according to the specified options.
  106292. */
  106293. EnvironmentHelper.prototype._setupImageProcessing = function () {
  106294. if (this._options.setupImageProcessing) {
  106295. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  106296. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  106297. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  106298. this._setupEnvironmentTexture();
  106299. }
  106300. };
  106301. /**
  106302. * Setup the environment texture according to the specified options.
  106303. */
  106304. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  106305. if (this._scene.environmentTexture) {
  106306. return;
  106307. }
  106308. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  106309. this._scene.environmentTexture = this._options.environmentTexture;
  106310. return;
  106311. }
  106312. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  106313. this._scene.environmentTexture = environmentTexture;
  106314. };
  106315. /**
  106316. * Setup the background according to the specified options.
  106317. */
  106318. EnvironmentHelper.prototype._setupBackground = function () {
  106319. if (!this._rootMesh) {
  106320. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  106321. }
  106322. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  106323. var sceneSize = this._getSceneSize();
  106324. if (this._options.createGround) {
  106325. this._setupGround(sceneSize);
  106326. this._setupGroundMaterial();
  106327. this._setupGroundDiffuseTexture();
  106328. if (this._options.enableGroundMirror) {
  106329. this._setupGroundMirrorTexture(sceneSize);
  106330. }
  106331. this._setupMirrorInGroundMaterial();
  106332. }
  106333. if (this._options.createSkybox) {
  106334. this._setupSkybox(sceneSize);
  106335. this._setupSkyboxMaterial();
  106336. this._setupSkyboxReflectionTexture();
  106337. }
  106338. this._rootMesh.position.x = sceneSize.rootPosition.x;
  106339. this._rootMesh.position.z = sceneSize.rootPosition.z;
  106340. this._rootMesh.position.y = sceneSize.rootPosition.y;
  106341. };
  106342. /**
  106343. * Get the scene sizes according to the setup.
  106344. */
  106345. EnvironmentHelper.prototype._getSceneSize = function () {
  106346. var _this = this;
  106347. var groundSize = this._options.groundSize;
  106348. var skyboxSize = this._options.skyboxSize;
  106349. var rootPosition = this._options.rootPosition;
  106350. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  106351. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106352. }
  106353. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  106354. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  106355. });
  106356. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  106357. if (this._options.sizeAuto) {
  106358. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  106359. this._scene.activeCamera.upperRadiusLimit) {
  106360. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  106361. skyboxSize = groundSize;
  106362. }
  106363. var sceneDiagonalLenght = sceneDiagonal.length();
  106364. if (sceneDiagonalLenght > groundSize) {
  106365. groundSize = sceneDiagonalLenght * 2;
  106366. skyboxSize = groundSize;
  106367. }
  106368. // 10 % bigger.
  106369. groundSize *= 1.1;
  106370. skyboxSize *= 1.5;
  106371. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  106372. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  106373. }
  106374. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106375. };
  106376. /**
  106377. * Setup the ground according to the specified options.
  106378. */
  106379. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  106380. var _this = this;
  106381. if (!this._ground || this._ground.isDisposed()) {
  106382. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  106383. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  106384. this._ground.parent = this._rootMesh;
  106385. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  106386. }
  106387. this._ground.receiveShadows = this._options.enableGroundShadow;
  106388. };
  106389. /**
  106390. * Setup the ground material according to the specified options.
  106391. */
  106392. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  106393. if (!this._groundMaterial) {
  106394. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  106395. }
  106396. this._groundMaterial.alpha = this._options.groundOpacity;
  106397. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  106398. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  106399. this._groundMaterial.primaryColor = this._options.groundColor;
  106400. this._groundMaterial.useRGBColor = false;
  106401. this._groundMaterial.enableNoise = true;
  106402. if (this._ground) {
  106403. this._ground.material = this._groundMaterial;
  106404. }
  106405. };
  106406. /**
  106407. * Setup the ground diffuse texture according to the specified options.
  106408. */
  106409. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  106410. if (!this._groundMaterial) {
  106411. return;
  106412. }
  106413. if (this._groundTexture) {
  106414. return;
  106415. }
  106416. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  106417. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  106418. return;
  106419. }
  106420. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106421. diffuseTexture.gammaSpace = false;
  106422. diffuseTexture.hasAlpha = true;
  106423. this._groundMaterial.diffuseTexture = diffuseTexture;
  106424. };
  106425. /**
  106426. * Setup the ground mirror texture according to the specified options.
  106427. */
  106428. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  106429. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106430. if (!this._groundMirror) {
  106431. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  106432. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  106433. this._groundMirror.anisotropicFilteringLevel = 1;
  106434. this._groundMirror.wrapU = wrapping;
  106435. this._groundMirror.wrapV = wrapping;
  106436. this._groundMirror.gammaSpace = false;
  106437. if (this._groundMirror.renderList) {
  106438. for (var i = 0; i < this._scene.meshes.length; i++) {
  106439. var mesh = this._scene.meshes[i];
  106440. if (mesh !== this._ground &&
  106441. mesh !== this._skybox &&
  106442. mesh !== this._rootMesh) {
  106443. this._groundMirror.renderList.push(mesh);
  106444. }
  106445. }
  106446. }
  106447. }
  106448. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  106449. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  106450. };
  106451. /**
  106452. * Setup the ground to receive the mirror texture.
  106453. */
  106454. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  106455. if (this._groundMaterial) {
  106456. this._groundMaterial.reflectionTexture = this._groundMirror;
  106457. this._groundMaterial.reflectionFresnel = true;
  106458. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  106459. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  106460. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  106461. }
  106462. };
  106463. /**
  106464. * Setup the skybox according to the specified options.
  106465. */
  106466. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  106467. var _this = this;
  106468. if (!this._skybox || this._skybox.isDisposed()) {
  106469. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  106470. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  106471. }
  106472. this._skybox.parent = this._rootMesh;
  106473. };
  106474. /**
  106475. * Setup the skybox material according to the specified options.
  106476. */
  106477. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  106478. if (!this._skybox) {
  106479. return;
  106480. }
  106481. if (!this._skyboxMaterial) {
  106482. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  106483. }
  106484. this._skyboxMaterial.useRGBColor = false;
  106485. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  106486. this._skyboxMaterial.enableNoise = true;
  106487. this._skybox.material = this._skyboxMaterial;
  106488. };
  106489. /**
  106490. * Setup the skybox reflection texture according to the specified options.
  106491. */
  106492. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  106493. if (!this._skyboxMaterial) {
  106494. return;
  106495. }
  106496. if (this._skyboxTexture) {
  106497. return;
  106498. }
  106499. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  106500. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  106501. return;
  106502. }
  106503. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106504. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  106505. this._skyboxTexture.gammaSpace = false;
  106506. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  106507. };
  106508. /**
  106509. * Dispose all the elements created by the Helper.
  106510. */
  106511. EnvironmentHelper.prototype.dispose = function () {
  106512. if (this._groundMaterial) {
  106513. this._groundMaterial.dispose(true, true);
  106514. }
  106515. if (this._skyboxMaterial) {
  106516. this._skyboxMaterial.dispose(true, true);
  106517. }
  106518. this._rootMesh.dispose(false);
  106519. };
  106520. /**
  106521. * Default ground texture URL.
  106522. */
  106523. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  106524. /**
  106525. * Default skybox texture URL.
  106526. */
  106527. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  106528. /**
  106529. * Default environment texture URL.
  106530. */
  106531. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  106532. return EnvironmentHelper;
  106533. }());
  106534. BABYLON.EnvironmentHelper = EnvironmentHelper;
  106535. })(BABYLON || (BABYLON = {}));
  106536. //# sourceMappingURL=babylon.environmentHelper.js.map
  106537. var BABYLON;
  106538. (function (BABYLON) {
  106539. /** Internal class used to store shapes for emitters */
  106540. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  106541. function ParticleSystemSetEmitterCreationOptions() {
  106542. }
  106543. return ParticleSystemSetEmitterCreationOptions;
  106544. }());
  106545. /**
  106546. * Represents a set of particle systems working together to create a specific effect
  106547. */
  106548. var ParticleSystemSet = /** @class */ (function () {
  106549. function ParticleSystemSet() {
  106550. /**
  106551. * Gets the particle system list
  106552. */
  106553. this.systems = new Array();
  106554. }
  106555. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  106556. /**
  106557. * Gets the emitter node used with this set
  106558. */
  106559. get: function () {
  106560. return this._emitterNode;
  106561. },
  106562. enumerable: true,
  106563. configurable: true
  106564. });
  106565. /**
  106566. * Creates a new emitter mesh as a sphere
  106567. * @param options defines the options used to create the sphere
  106568. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  106569. * @param scene defines the hosting scene
  106570. */
  106571. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  106572. if (this._emitterNode) {
  106573. this._emitterNode.dispose();
  106574. }
  106575. this._emitterCreationOptions = {
  106576. kind: "Sphere",
  106577. options: options,
  106578. renderingGroupId: renderingGroupId
  106579. };
  106580. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  106581. emitterMesh.renderingGroupId = renderingGroupId;
  106582. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  106583. material.emissiveColor = options.color;
  106584. emitterMesh.material = material;
  106585. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106586. var system = _a[_i];
  106587. system.emitter = emitterMesh;
  106588. }
  106589. this._emitterNode = emitterMesh;
  106590. };
  106591. /**
  106592. * Starts all particle systems of the set
  106593. * @param emitter defines an optional mesh to use as emitter for the particle systems
  106594. */
  106595. ParticleSystemSet.prototype.start = function (emitter) {
  106596. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106597. var system = _a[_i];
  106598. if (emitter) {
  106599. system.emitter = emitter;
  106600. }
  106601. system.start();
  106602. }
  106603. };
  106604. /**
  106605. * Release all associated resources
  106606. */
  106607. ParticleSystemSet.prototype.dispose = function () {
  106608. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106609. var system = _a[_i];
  106610. system.dispose();
  106611. }
  106612. this.systems = [];
  106613. if (this._emitterNode) {
  106614. this._emitterNode.dispose();
  106615. this._emitterNode = null;
  106616. }
  106617. };
  106618. /**
  106619. * Serialize the set into a JSON compatible object
  106620. * @returns a JSON compatible representation of the set
  106621. */
  106622. ParticleSystemSet.prototype.serialize = function () {
  106623. var result = {};
  106624. result.systems = [];
  106625. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106626. var system = _a[_i];
  106627. result.systems.push(system.serialize());
  106628. }
  106629. if (this._emitterNode) {
  106630. result.emitter = this._emitterCreationOptions;
  106631. }
  106632. return result;
  106633. };
  106634. /**
  106635. * Parse a new ParticleSystemSet from a serialized source
  106636. * @param data defines a JSON compatible representation of the set
  106637. * @param scene defines the hosting scene
  106638. * @param gpu defines if we want GPU particles or CPU particles
  106639. * @returns a new ParticleSystemSet
  106640. */
  106641. ParticleSystemSet.Parse = function (data, scene, gpu) {
  106642. if (gpu === void 0) { gpu = false; }
  106643. var result = new ParticleSystemSet();
  106644. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  106645. scene = scene || BABYLON.Engine.LastCreatedScene;
  106646. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  106647. var system = _a[_i];
  106648. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  106649. }
  106650. if (data.emitter) {
  106651. var options = data.emitter.options;
  106652. switch (data.emitter.kind) {
  106653. case "Sphere":
  106654. result.setEmitterAsSphere({
  106655. diameter: options.diameter,
  106656. segments: options.segments,
  106657. color: BABYLON.Color3.FromArray(options.color)
  106658. }, data.emitter.renderingGroupId, scene);
  106659. break;
  106660. }
  106661. }
  106662. return result;
  106663. };
  106664. return ParticleSystemSet;
  106665. }());
  106666. BABYLON.ParticleSystemSet = ParticleSystemSet;
  106667. })(BABYLON || (BABYLON = {}));
  106668. //# sourceMappingURL=babylon.particleSystemSet.js.map
  106669. var BABYLON;
  106670. (function (BABYLON) {
  106671. /**
  106672. * This class is made for on one-liner static method to help creating particle system set.
  106673. */
  106674. var ParticleHelper = /** @class */ (function () {
  106675. function ParticleHelper() {
  106676. }
  106677. /**
  106678. * Create a default particle system that you can tweak
  106679. * @param emitter defines the emitter to use
  106680. * @param capacity defines the system capacity (default is 500 particles)
  106681. * @param scene defines the hosting scene
  106682. * @returns the new Particle system
  106683. */
  106684. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  106685. if (capacity === void 0) { capacity = 500; }
  106686. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  106687. system.emitter = emitter;
  106688. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  106689. system.createConeEmitter(0.1, Math.PI / 4);
  106690. // Particle color
  106691. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106692. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106693. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  106694. // Particle Size
  106695. system.minSize = 0.1;
  106696. system.maxSize = 0.1;
  106697. // Emission speed
  106698. system.minEmitPower = 2;
  106699. system.maxEmitPower = 2;
  106700. // Update speed
  106701. system.updateSpeed = 1 / 60;
  106702. system.emitRate = 30;
  106703. return system;
  106704. };
  106705. /**
  106706. * This is the main static method (one-liner) of this helper to create different particle systems
  106707. * @param type This string represents the type to the particle system to create
  106708. * @param scene The scene where the particle system should live
  106709. * @param gpu If the system will use gpu
  106710. * @returns the ParticleSystemSet created
  106711. */
  106712. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  106713. if (gpu === void 0) { gpu = false; }
  106714. if (!scene) {
  106715. scene = BABYLON.Engine.LastCreatedScene;
  106716. ;
  106717. }
  106718. var token = {};
  106719. scene._addPendingData(token);
  106720. return new Promise(function (resolve, reject) {
  106721. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  106722. scene._removePendingData(token);
  106723. return reject("Particle system with GPU is not supported.");
  106724. }
  106725. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  106726. scene._removePendingData(token);
  106727. var newData = JSON.parse(data.toString());
  106728. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  106729. }, undefined, undefined, undefined, function (req, exception) {
  106730. scene._removePendingData(token);
  106731. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  106732. });
  106733. });
  106734. };
  106735. /**
  106736. * Static function used to export a particle system to a ParticleSystemSet variable.
  106737. * Please note that the emitter shape is not exported
  106738. * @param system defines the particle systems to export
  106739. */
  106740. ParticleHelper.ExportSet = function (systems) {
  106741. var set = new BABYLON.ParticleSystemSet();
  106742. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  106743. var system = systems_1[_i];
  106744. set.systems.push(system);
  106745. }
  106746. return set;
  106747. };
  106748. /**
  106749. * Gets or sets base Assets URL
  106750. */
  106751. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  106752. return ParticleHelper;
  106753. }());
  106754. BABYLON.ParticleHelper = ParticleHelper;
  106755. })(BABYLON || (BABYLON = {}));
  106756. //# sourceMappingURL=babylon.particleHelper.js.map
  106757. var BABYLON;
  106758. (function (BABYLON) {
  106759. /**
  106760. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  106761. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  106762. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  106763. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106764. */
  106765. var VideoDome = /** @class */ (function (_super) {
  106766. __extends(VideoDome, _super);
  106767. /**
  106768. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  106769. * @param name Element's name, child elements will append suffixes for their own names.
  106770. * @param urlsOrVideo defines the url(s) or the video element to use
  106771. * @param options An object containing optional or exposed sub element properties
  106772. */
  106773. function VideoDome(name, urlsOrVideo, options, scene) {
  106774. var _this = _super.call(this, name, scene) || this;
  106775. _this._useDirectMapping = false;
  106776. // set defaults and manage values
  106777. name = name || "videoDome";
  106778. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106779. options.clickToPlay = Boolean(options.clickToPlay);
  106780. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  106781. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  106782. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106783. if (options.useDirectMapping === undefined) {
  106784. _this._useDirectMapping = true;
  106785. }
  106786. else {
  106787. _this._useDirectMapping = options.useDirectMapping;
  106788. }
  106789. _this._setReady(false);
  106790. // create
  106791. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  106792. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106793. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  106794. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106795. texture.onLoadObservable.addOnce(function () {
  106796. _this._setReady(true);
  106797. });
  106798. // configure material
  106799. material.useEquirectangularFOV = true;
  106800. material.fovMultiplier = 1.0;
  106801. material.opacityFresnel = false;
  106802. if (_this._useDirectMapping) {
  106803. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106804. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106805. material.diffuseTexture = texture;
  106806. }
  106807. else {
  106808. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106809. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106810. material.reflectionTexture = texture;
  106811. }
  106812. // configure mesh
  106813. _this._mesh.material = material;
  106814. _this._mesh.parent = _this;
  106815. // optional configuration
  106816. if (options.clickToPlay) {
  106817. scene.onPointerUp = function () {
  106818. _this._videoTexture.video.play();
  106819. };
  106820. }
  106821. return _this;
  106822. }
  106823. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  106824. /**
  106825. * Gets the video texture being displayed on the sphere
  106826. */
  106827. get: function () {
  106828. return this._videoTexture;
  106829. },
  106830. enumerable: true,
  106831. configurable: true
  106832. });
  106833. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  106834. /**
  106835. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106836. * Also see the options.resolution property.
  106837. */
  106838. get: function () {
  106839. return this._material.fovMultiplier;
  106840. },
  106841. set: function (value) {
  106842. this._material.fovMultiplier = value;
  106843. },
  106844. enumerable: true,
  106845. configurable: true
  106846. });
  106847. /**
  106848. * Releases resources associated with this node.
  106849. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106850. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106851. */
  106852. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106853. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106854. this._videoTexture.dispose();
  106855. this._mesh.dispose();
  106856. this._material.dispose();
  106857. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106858. };
  106859. return VideoDome;
  106860. }(BABYLON.TransformNode));
  106861. BABYLON.VideoDome = VideoDome;
  106862. })(BABYLON || (BABYLON = {}));
  106863. //# sourceMappingURL=babylon.videoDome.js.map
  106864. var BABYLON;
  106865. (function (BABYLON) {
  106866. /**
  106867. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  106868. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  106869. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  106870. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106871. */
  106872. var PhotoDome = /** @class */ (function (_super) {
  106873. __extends(PhotoDome, _super);
  106874. /**
  106875. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  106876. * @param name Element's name, child elements will append suffixes for their own names.
  106877. * @param urlsOfPhoto defines the url of the photo to display
  106878. * @param options defines an object containing optional or exposed sub element properties
  106879. * @param onError defines a callback called when an error occured while loading the texture
  106880. */
  106881. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  106882. if (onError === void 0) { onError = null; }
  106883. var _this = _super.call(this, name, scene) || this;
  106884. _this._useDirectMapping = false;
  106885. /**
  106886. * Observable raised when an error occured while loading the 360 image
  106887. */
  106888. _this.onLoadErrorObservable = new BABYLON.Observable();
  106889. // set defaults and manage values
  106890. name = name || "photoDome";
  106891. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106892. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106893. if (options.useDirectMapping === undefined) {
  106894. _this._useDirectMapping = true;
  106895. }
  106896. else {
  106897. _this._useDirectMapping = options.useDirectMapping;
  106898. }
  106899. _this._setReady(false);
  106900. // create
  106901. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106902. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106903. // configure material
  106904. material.opacityFresnel = false;
  106905. material.useEquirectangularFOV = true;
  106906. material.fovMultiplier = 1.0;
  106907. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  106908. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  106909. if (onError) {
  106910. onError(message, exception);
  106911. }
  106912. });
  106913. _this.photoTexture.onLoadObservable.addOnce(function () {
  106914. _this._setReady(true);
  106915. });
  106916. // configure mesh
  106917. _this._mesh.material = material;
  106918. _this._mesh.parent = _this;
  106919. return _this;
  106920. }
  106921. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  106922. /**
  106923. * Gets or sets the texture being displayed on the sphere
  106924. */
  106925. get: function () {
  106926. return this._photoTexture;
  106927. },
  106928. set: function (value) {
  106929. if (this._photoTexture === value) {
  106930. return;
  106931. }
  106932. this._photoTexture = value;
  106933. if (this._useDirectMapping) {
  106934. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106935. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106936. this._material.diffuseTexture = this._photoTexture;
  106937. }
  106938. else {
  106939. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106940. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106941. this._material.reflectionTexture = this._photoTexture;
  106942. }
  106943. },
  106944. enumerable: true,
  106945. configurable: true
  106946. });
  106947. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  106948. /**
  106949. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106950. * Also see the options.resolution property.
  106951. */
  106952. get: function () {
  106953. return this._material.fovMultiplier;
  106954. },
  106955. set: function (value) {
  106956. this._material.fovMultiplier = value;
  106957. },
  106958. enumerable: true,
  106959. configurable: true
  106960. });
  106961. /**
  106962. * Releases resources associated with this node.
  106963. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106964. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106965. */
  106966. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106967. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106968. this._photoTexture.dispose();
  106969. this._mesh.dispose();
  106970. this._material.dispose();
  106971. this.onLoadErrorObservable.clear();
  106972. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106973. };
  106974. return PhotoDome;
  106975. }(BABYLON.TransformNode));
  106976. BABYLON.PhotoDome = PhotoDome;
  106977. })(BABYLON || (BABYLON = {}));
  106978. //# sourceMappingURL=babylon.photoDome.js.map
  106979. var BABYLON;
  106980. (function (BABYLON) {
  106981. BABYLON.Engine.prototype.createQuery = function () {
  106982. return this._gl.createQuery();
  106983. };
  106984. BABYLON.Engine.prototype.deleteQuery = function (query) {
  106985. this._gl.deleteQuery(query);
  106986. return this;
  106987. };
  106988. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  106989. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  106990. };
  106991. BABYLON.Engine.prototype.getQueryResult = function (query) {
  106992. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  106993. };
  106994. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  106995. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  106996. this._gl.beginQuery(glAlgorithm, query);
  106997. return this;
  106998. };
  106999. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  107000. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107001. this._gl.endQuery(glAlgorithm);
  107002. return this;
  107003. };
  107004. BABYLON.Engine.prototype._createTimeQuery = function () {
  107005. var timerQuery = this.getCaps().timerQuery;
  107006. if (timerQuery.createQueryEXT) {
  107007. return timerQuery.createQueryEXT();
  107008. }
  107009. return this.createQuery();
  107010. };
  107011. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  107012. var timerQuery = this.getCaps().timerQuery;
  107013. if (timerQuery.deleteQueryEXT) {
  107014. timerQuery.deleteQueryEXT(query);
  107015. return;
  107016. }
  107017. this.deleteQuery(query);
  107018. };
  107019. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  107020. var timerQuery = this.getCaps().timerQuery;
  107021. if (timerQuery.getQueryObjectEXT) {
  107022. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  107023. }
  107024. return this.getQueryResult(query);
  107025. };
  107026. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  107027. var timerQuery = this.getCaps().timerQuery;
  107028. if (timerQuery.getQueryObjectEXT) {
  107029. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  107030. }
  107031. return this.isQueryResultAvailable(query);
  107032. };
  107033. BABYLON.Engine.prototype.startTimeQuery = function () {
  107034. var caps = this.getCaps();
  107035. var timerQuery = caps.timerQuery;
  107036. if (!timerQuery) {
  107037. return null;
  107038. }
  107039. var token = new BABYLON._TimeToken();
  107040. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107041. if (caps.canUseTimestampForTimerQuery) {
  107042. token._startTimeQuery = this._createTimeQuery();
  107043. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  107044. }
  107045. else {
  107046. if (this._currentNonTimestampToken) {
  107047. return this._currentNonTimestampToken;
  107048. }
  107049. token._timeElapsedQuery = this._createTimeQuery();
  107050. if (timerQuery.beginQueryEXT) {
  107051. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107052. }
  107053. else {
  107054. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107055. }
  107056. this._currentNonTimestampToken = token;
  107057. }
  107058. return token;
  107059. };
  107060. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  107061. var caps = this.getCaps();
  107062. var timerQuery = caps.timerQuery;
  107063. if (!timerQuery || !token) {
  107064. return -1;
  107065. }
  107066. if (caps.canUseTimestampForTimerQuery) {
  107067. if (!token._startTimeQuery) {
  107068. return -1;
  107069. }
  107070. if (!token._endTimeQuery) {
  107071. token._endTimeQuery = this._createTimeQuery();
  107072. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  107073. }
  107074. }
  107075. else if (!token._timeElapsedQueryEnded) {
  107076. if (!token._timeElapsedQuery) {
  107077. return -1;
  107078. }
  107079. if (timerQuery.endQueryEXT) {
  107080. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  107081. }
  107082. else {
  107083. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  107084. }
  107085. token._timeElapsedQueryEnded = true;
  107086. }
  107087. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107088. var available = false;
  107089. if (token._endTimeQuery) {
  107090. available = this._getTimeQueryAvailability(token._endTimeQuery);
  107091. }
  107092. else if (token._timeElapsedQuery) {
  107093. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  107094. }
  107095. if (available && !disjoint) {
  107096. var result = 0;
  107097. if (caps.canUseTimestampForTimerQuery) {
  107098. if (!token._startTimeQuery || !token._endTimeQuery) {
  107099. return -1;
  107100. }
  107101. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  107102. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  107103. result = timeEnd - timeStart;
  107104. this._deleteTimeQuery(token._startTimeQuery);
  107105. this._deleteTimeQuery(token._endTimeQuery);
  107106. token._startTimeQuery = null;
  107107. token._endTimeQuery = null;
  107108. }
  107109. else {
  107110. if (!token._timeElapsedQuery) {
  107111. return -1;
  107112. }
  107113. result = this._getTimeQueryResult(token._timeElapsedQuery);
  107114. this._deleteTimeQuery(token._timeElapsedQuery);
  107115. token._timeElapsedQuery = null;
  107116. token._timeElapsedQueryEnded = false;
  107117. this._currentNonTimestampToken = null;
  107118. }
  107119. return result;
  107120. }
  107121. return -1;
  107122. };
  107123. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  107124. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  107125. };
  107126. // We also need to update AbstractMesh as there is a portion of the code there
  107127. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  107128. var engine = this.getEngine();
  107129. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  107130. this._isOccluded = false;
  107131. return;
  107132. }
  107133. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  107134. this._isOccluded = false;
  107135. return;
  107136. }
  107137. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  107138. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  107139. if (isOcclusionQueryAvailable) {
  107140. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  107141. this._isOcclusionQueryInProgress = false;
  107142. this._occlusionInternalRetryCounter = 0;
  107143. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  107144. }
  107145. else {
  107146. this._occlusionInternalRetryCounter++;
  107147. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  107148. this._isOcclusionQueryInProgress = false;
  107149. this._occlusionInternalRetryCounter = 0;
  107150. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  107151. // if strict continue the last state of the object.
  107152. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  107153. }
  107154. else {
  107155. return;
  107156. }
  107157. }
  107158. }
  107159. var scene = this.getScene();
  107160. if (scene.getBoundingBoxRenderer) {
  107161. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  107162. if (!this._occlusionQuery) {
  107163. this._occlusionQuery = engine.createQuery();
  107164. }
  107165. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  107166. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  107167. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  107168. this._isOcclusionQueryInProgress = true;
  107169. }
  107170. };
  107171. })(BABYLON || (BABYLON = {}));
  107172. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  107173. var BABYLON;
  107174. (function (BABYLON) {
  107175. /**
  107176. * Class used to generate noise procedural textures
  107177. */
  107178. var NoiseProceduralTexture = /** @class */ (function (_super) {
  107179. __extends(NoiseProceduralTexture, _super);
  107180. /**
  107181. * Creates a new NoiseProceduralTexture
  107182. * @param name defines the name fo the texture
  107183. * @param size defines the size of the texture (default is 256)
  107184. * @param scene defines the hosting scene
  107185. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  107186. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  107187. */
  107188. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  107189. if (size === void 0) { size = 256; }
  107190. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  107191. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  107192. _this._time = 0;
  107193. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  107194. _this.brightness = 0.2;
  107195. /** Defines the number of octaves to process */
  107196. _this.octaves = 3;
  107197. /** Defines the level of persistence (0.8 by default) */
  107198. _this.persistence = 0.8;
  107199. /** Gets or sets animation speed factor (default is 1) */
  107200. _this.animationSpeedFactor = 1;
  107201. _this._updateShaderUniforms();
  107202. return _this;
  107203. }
  107204. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  107205. var scene = this.getScene();
  107206. if (!scene) {
  107207. return;
  107208. }
  107209. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  107210. this.setFloat("brightness", this.brightness);
  107211. this.setInt("octaves", this.octaves);
  107212. this.setFloat("persistence", this.persistence);
  107213. this.setFloat("timeScale", this._time);
  107214. };
  107215. /** Generate the current state of the procedural texture */
  107216. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  107217. this._updateShaderUniforms();
  107218. _super.prototype.render.call(this, useCameraPostProcess);
  107219. };
  107220. /**
  107221. * Serializes this noise procedural texture
  107222. * @returns a serialized noise procedural texture object
  107223. */
  107224. NoiseProceduralTexture.prototype.serialize = function () {
  107225. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  107226. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  107227. return serializationObject;
  107228. };
  107229. /**
  107230. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  107231. * @param parsedTexture defines parsed texture data
  107232. * @param scene defines the current scene
  107233. * @param rootUrl defines the root URL containing noise procedural texture information
  107234. * @returns a parsed NoiseProceduralTexture
  107235. */
  107236. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  107237. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  107238. return texture;
  107239. };
  107240. return NoiseProceduralTexture;
  107241. }(BABYLON.ProceduralTexture));
  107242. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  107243. })(BABYLON || (BABYLON = {}));
  107244. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  107245. var __assign = (this && this.__assign) || function () {
  107246. __assign = Object.assign || function(t) {
  107247. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107248. s = arguments[i];
  107249. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107250. t[p] = s[p];
  107251. }
  107252. return t;
  107253. };
  107254. return __assign.apply(this, arguments);
  107255. };
  107256. var BABYLON;
  107257. (function (BABYLON) {
  107258. /**
  107259. * This can helps recording videos from BabylonJS.
  107260. * This is based on the available WebRTC functionalities of the browser.
  107261. *
  107262. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  107263. */
  107264. var VideoRecorder = /** @class */ (function () {
  107265. /**
  107266. * Create a new VideoCapture object which can help converting what you see in Babylon to
  107267. * a video file.
  107268. * @param engine Defines the BabylonJS Engine you wish to record
  107269. * @param options Defines options that can be used to customized the capture
  107270. */
  107271. function VideoRecorder(engine, options) {
  107272. if (options === void 0) { options = null; }
  107273. if (!VideoRecorder.IsSupported(engine)) {
  107274. throw "Your browser does not support recording so far.";
  107275. }
  107276. var canvas = engine.getRenderingCanvas();
  107277. if (!canvas) {
  107278. throw "The babylon engine must have a canvas to be recorded";
  107279. }
  107280. this._canvas = canvas;
  107281. this._canvas.isRecording = false;
  107282. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  107283. var stream = this._canvas.captureStream(this._options.fps);
  107284. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  107285. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  107286. this._mediaRecorder.onerror = this._handleError.bind(this);
  107287. this._mediaRecorder.onstop = this._handleStop.bind(this);
  107288. }
  107289. /**
  107290. * Returns wehther or not the VideoRecorder is available in your browser.
  107291. * @param engine Defines the Babylon Engine to check the support for
  107292. * @returns true if supported otherwise false
  107293. */
  107294. VideoRecorder.IsSupported = function (engine) {
  107295. var canvas = engine.getRenderingCanvas();
  107296. return (!!canvas && typeof canvas.captureStream === "function");
  107297. };
  107298. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  107299. /**
  107300. * True wether a recording is already in progress.
  107301. */
  107302. get: function () {
  107303. return !!this._canvas && this._canvas.isRecording;
  107304. },
  107305. enumerable: true,
  107306. configurable: true
  107307. });
  107308. /**
  107309. * Stops the current recording before the default capture timeout passed in the startRecording
  107310. * functions.
  107311. */
  107312. VideoRecorder.prototype.stopRecording = function () {
  107313. if (!this._canvas || !this._mediaRecorder) {
  107314. return;
  107315. }
  107316. if (!this.isRecording) {
  107317. return;
  107318. }
  107319. this._canvas.isRecording = false;
  107320. this._mediaRecorder.stop();
  107321. };
  107322. /**
  107323. * Starts recording the canvas for a max duration specified in parameters.
  107324. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  107325. * @param maxDuration Defines the maximum recording time in seconds.
  107326. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  107327. * @return a promise callback at the end of the recording with the video data in Blob.
  107328. */
  107329. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  107330. var _this = this;
  107331. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  107332. if (maxDuration === void 0) { maxDuration = 7; }
  107333. if (!this._canvas || !this._mediaRecorder) {
  107334. throw "Recorder has already been disposed";
  107335. }
  107336. if (this.isRecording) {
  107337. throw "Recording already in progress";
  107338. }
  107339. if (maxDuration > 0) {
  107340. setTimeout(function () {
  107341. _this.stopRecording();
  107342. }, maxDuration * 1000);
  107343. }
  107344. this._fileName = fileName;
  107345. this._recordedChunks = [];
  107346. this._resolve = null;
  107347. this._reject = null;
  107348. this._canvas.isRecording = true;
  107349. this._mediaRecorder.start(this._options.recordChunckSize);
  107350. return new Promise(function (resolve, reject) {
  107351. _this._resolve = resolve;
  107352. _this._reject = reject;
  107353. });
  107354. };
  107355. /**
  107356. * Releases internal resources used during the recording.
  107357. */
  107358. VideoRecorder.prototype.dispose = function () {
  107359. this._canvas = null;
  107360. this._mediaRecorder = null;
  107361. this._recordedChunks = [];
  107362. this._fileName = null;
  107363. this._resolve = null;
  107364. this._reject = null;
  107365. };
  107366. VideoRecorder.prototype._handleDataAvailable = function (event) {
  107367. if (event.data.size > 0) {
  107368. this._recordedChunks.push(event.data);
  107369. }
  107370. };
  107371. VideoRecorder.prototype._handleError = function (event) {
  107372. this.stopRecording();
  107373. if (this._reject) {
  107374. this._reject(event.error);
  107375. }
  107376. else {
  107377. throw new event.error;
  107378. }
  107379. };
  107380. VideoRecorder.prototype._handleStop = function () {
  107381. this.stopRecording();
  107382. var superBuffer = new Blob(this._recordedChunks);
  107383. if (this._resolve) {
  107384. this._resolve(superBuffer);
  107385. }
  107386. window.URL.createObjectURL(superBuffer);
  107387. if (this._fileName) {
  107388. BABYLON.Tools.Download(superBuffer, this._fileName);
  107389. }
  107390. };
  107391. VideoRecorder._defaultOptions = {
  107392. mimeType: "video/webm",
  107393. fps: 25,
  107394. recordChunckSize: 3000
  107395. };
  107396. return VideoRecorder;
  107397. }());
  107398. BABYLON.VideoRecorder = VideoRecorder;
  107399. })(BABYLON || (BABYLON = {}));
  107400. //# sourceMappingURL=babylon.videoRecorder.js.map
  107401. 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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 baseColor=texture2D(diffuseSampler,vUV);\nbaseColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \noutFragColor=texture(textureSampler,vUV)*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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}","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;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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}","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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  107402. 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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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 REFLECTION\nuniform mat4 reflectionMatrix;\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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(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#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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 vec4 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 vec4 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 vec4 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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\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;\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}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","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","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};","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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  107403. globalObject["BABYLON"] = BABYLON;
  107404. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var ColorGradient = BABYLON.ColorGradient;var FactorGradient = BABYLON.FactorGradient;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var SceneComponentConstants = BABYLON.SceneComponentConstants;var Stage = BABYLON.Stage;var AbstractScene = BABYLON.AbstractScene;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var BaseParticleSystem = BABYLON.BaseParticleSystem;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var CylinderParticleEmitter = BABYLON.CylinderParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var HemisphericParticleEmitter = BABYLON.HemisphericParticleEmitter;var PointParticleEmitter = BABYLON.PointParticleEmitter;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var StringDictionary = BABYLON.StringDictionary;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var WeightedSound = BABYLON.WeightedSound;var CubeTexture = BABYLON.CubeTexture;var RawCubeTexture = BABYLON.RawCubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcessManager = BABYLON.PostProcessManager;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var GamepadSystemSceneComponent = BABYLON.GamepadSystemSceneComponent;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderPipelineManagerSceneComponent = BABYLON.PostProcessRenderPipelineManagerSceneComponent;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var DepthRendererSceneComponent = BABYLON.DepthRendererSceneComponent;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var GeometryBufferRendererSceneComponent = BABYLON.GeometryBufferRendererSceneComponent;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var ImageProcessingConfigurationDefines = BABYLON.ImageProcessingConfigurationDefines;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystemSceneComponent = BABYLON.LensFlareSystemSceneComponent;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var DDSTools = BABYLON.DDSTools;var TGATools = BABYLON.TGATools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var EnvironmentTextureTools = BABYLON.EnvironmentTextureTools;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var PointerDragBehavior = BABYLON.PointerDragBehavior;var MultiPointerScaleBehavior = BABYLON.MultiPointerScaleBehavior;var SixDofDragBehavior = BABYLON.SixDofDragBehavior;var AttachToBoxBehavior = BABYLON.AttachToBoxBehavior;var FadeInOutBehavior = BABYLON.FadeInOutBehavior;var Gizmo = BABYLON.Gizmo;var AxisDragGizmo = BABYLON.AxisDragGizmo;var AxisScaleGizmo = BABYLON.AxisScaleGizmo;var PlaneRotationGizmo = BABYLON.PlaneRotationGizmo;var PositionGizmo = BABYLON.PositionGizmo;var RotationGizmo = BABYLON.RotationGizmo;var ScaleGizmo = BABYLON.ScaleGizmo;var BoundingBoxGizmo = BABYLON.BoundingBoxGizmo;var GizmoManager = BABYLON.GizmoManager;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var SimplicationQueueSceneComponent = BABYLON.SimplicationQueueSceneComponent;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var LineEdgesRenderer = BABYLON.LineEdgesRenderer;var EffectLayerSceneComponent = BABYLON.EffectLayerSceneComponent;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var LayerSceneComponent = BABYLON.LayerSceneComponent;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var ParticleSystemSet = BABYLON.ParticleSystemSet;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var PhotoDome = BABYLON.PhotoDome;var NoiseProceduralTexture = BABYLON.NoiseProceduralTexture;var VideoRecorder = BABYLON.VideoRecorder;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Debug = BABYLON.Debug ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  107405. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,ColorGradient,FactorGradient,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,SceneComponentConstants,Stage,AbstractScene,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PerformanceMonitor,RollingAverage,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,BaseParticleSystem,ParticleSystem,BoxParticleEmitter,CylinderParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,HemisphericParticleEmitter,PointParticleEmitter,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,StringDictionary,RayHelper,DebugLayer,BoundingBoxRenderer,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,WeightedSound,CubeTexture,RawCubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcessManager,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,GamepadSystemSceneComponent,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderPipelineManagerSceneComponent,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,DepthRendererSceneComponent,GeometryBufferRenderer,GeometryBufferRendererSceneComponent,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,ImageProcessingConfigurationDefines,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,HDRTools,HDRCubeTexture,PanoramaToCubeMapTools,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystemSceneComponent,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,DDSTools,TGATools,KhronosTextureContainer,EnvironmentTextureTools,UtilityLayerRenderer,PointerDragBehavior,MultiPointerScaleBehavior,SixDofDragBehavior,AttachToBoxBehavior,FadeInOutBehavior,Gizmo,AxisDragGizmo,AxisScaleGizmo,PlaneRotationGizmo,PositionGizmo,RotationGizmo,ScaleGizmo,BoundingBoxGizmo,GizmoManager,MorphTarget,MorphTargetManager,Octree,OctreeBlock,AnaglyphPostProcess,AnaglyphArcRotateCamera,AnaglyphFreeCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicInterlacePostProcess,StereoscopicArcRotateCamera,StereoscopicFreeCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRDistortionCorrectionPostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationArcRotateCamera,VRDeviceOrientationGamepadCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,SimplicationQueueSceneComponent,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,LineEdgesRenderer,EffectLayerSceneComponent,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,LayerSceneComponent,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleSystemSet,ParticleHelper,VideoDome,PhotoDome,NoiseProceduralTexture,VideoRecorder,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Debug ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };